내용으로 건너뛰기

How to fix CWE-89- SQL Injection for golang

0

Normally we avoid using sprint to join SQL with parameters. We follow this rule, but the code guru always detects it(CWE-89- SQL Injection) . Sample Code: At execContext function, always identify the SQL injection issue

sql := "SELECT * FROM organization where id = ?"
tx := db.begin()
stmt, err := tx.PrepareContext(ctx, sql)
stmt.ExecContext(ctx, orgID)
질문됨 일 년 전206회 조회
2개 답변
0

Is this piece of code useful to you ?

sql := "SELECT * FROM organization WHERE id = ?"
tx, err := db.Begin()
if err != nil {
    return err // handle error appropriately
}
defer tx.Rollback() // ensure rollback in case of error

stmt, err := tx.PrepareContext(ctx, sql)
if err != nil {
    return err // handle error appropriately
}
defer stmt.Close() // ensure statement is closed

rows, err := stmt.QueryContext(ctx, orgID)
if err != nil {
    return err // handle error appropriately
}
defer rows.Close() // ensure rows are closed

// Process rows here

if err := tx.Commit(); err != nil {
    return err // handle error appropriately
}

Key Points:

Error Handling: Each step checks for errors and handles them appropriately.

Transaction Handling: The transaction is rolled back if any error occurs, and committed only if everything succeeds.

Resource Management: Statements and rows are properly closed to avoid resource leaks.

전문가
답변함 일 년 전
0

Thanks for your reply. But the issue is occurring at "stmt.ExecContext(ctx, orgID)", It can't directly input orgID to ExecContext function. When using struct to wrapper orgID can pass SQL Injection verification. But this solution is not generally way to operate SQL.

The sample code can pass verification

type Input struct{
    OrgID string
}

func Query(input *Input){
    sql := "SELECT * FROM organization where id = ?"
    tx := db.begin()
    stmt, err := tx.Prepare(SQL)
    stmt.ExecContext(ctx, input.OrgID)
}
답변함 일 년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

관련 콘텐츠