Goにおけるコマンドインジェクションの脆弱性を理解する
2024年11月14日
14 分で読めますGoの
また、
いずれの
コマンドインジェクションとは?
コマンドインジェクションとは、
Goでは、os/execパッケージを
次の
func handler(req *http.Request) {
cmdName := req.URL.Query()["cmd"][0]
cmd := exec.Command(cmdName)
cmd.Run()
}このcmdNameをcmdクエリ文字列の
攻撃者は、
http://example.com/execute?cmd=rm%20-rf%20/コマンドインジェクションは
データ侵害:攻撃者は
サーバーに 保存された 機密データに アクセスできます。 リソースや 認証情報が 記載された config.tomlなどの設定ファイルに アクセスされる 事態を 想像してみてください。 システムの
侵害:攻撃者は サーバーを 制御し、 さらなる 攻撃を 仕掛ける ことができます。 侵害された システム内で 横方向に 移動したり、 侵害可能な 別の サーバーを 探したりする ケースが よく 見られます。 サービスの
中断:攻撃者は サービスを 妨害する コマンドを 実行し、 ダウンタイムを 引き起こせます。 サービス拒否攻撃に よる 損失は、 直接的な 金銭的損害や ビジネスリスクに つながる 可能性が あります。
コマンドインジェクション攻撃が
Goにおける脆弱なプロセス実行とコマンドインジェクション
シンプルさと
よりconvertのような
画像の/cloudpawnery/imageをtenantID、fileID、fileSizeなどのfileSizeパラメーターは
次の
func main() {
// Create a Gin router
router := gin.Default()
// Define a POST endpoint
router.POST("/cloudpawnery/image", func(c *gin.Context) {
tenantID := c.Query("tenantID")
fileID := c.Query("fileID")
fileSize := c.Query("fileSize")
if fileSize == "" {
fileSize = "200"
}
// Validate tenantID and fileID
if tenantID == "" || fileID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing tenantID or fileID"})
return
}
// Call the download and resize function
err := downloadAndResize(c, tenantID, fileID, fileSize)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Return a success response
c.JSON(http.StatusOK, gin.H{"message": "File downloaded and resized successfully"})
})
// Start the HTTP server
router.Run(":7000")
}
func downloadAndResize(ctx *gin.Context, tenantID, fileID, fileSize string) error {
slog.Info("Processing request", "tenantID", tenantID, "fileID", fileID)
convertCmd := fmt.Sprintf("convert %s -resize %sx%s %s", targetFilename, fileSize, fileSize, targetFilename)
slog.Info("Running command", "command", convertCmd)
_, err := exec.CommandContext(ctx, "sh", "-c", convertCmd).CombinedOutput()
if err != nil {
slog.Error("Error resizing image", "error", err)
return fmt.Errorf("%w: %v", ErrImageResize, err)
}
slog.Info("Downloaded and resized image", "filename", targetFilename)
return nil
}downloadAndResize関数は、exec.CommandContextで
downloadAndResize関数は、fileSizeの
コマンドインジェクションの脆弱性を軽減する
Goの
こうした
入力の検証とサニタイズ
コマンドインジェクションをdownloadAndResize関数がfileSizeなどの
入力の
許可リストを
使う: fileSizeなどの入力に 対して、 許容する 値を 定義します。 たとえば、 妥当な 範囲内の 数値だけを 許可します。 入力を
サニタイズする:ユーザー入力から、 危険な 可能性の ある 文字を 削除または エスケープします。 これには ;、|、&などのシェルの メタ文字も 含まれます。 コマンドは ハードコードし、 ユーザー入力に よって 制御されないように するのが 最善です。 厳密な
型を 使う:入力は できるだけ 早く、 想定される データ型に 変換します。 たとえば、 fileSizeを整数に 変換し、 その 範囲を 検証します。
これらの
func sanitizeInput(input string) (int, error) {
size, err := strconv.Atoi(input)
if err != nil || size <= 0 || size > 1000 {
return 0, fmt.Errorf("invalid input")
}
return size, nil
}
func downloadAndResize(ctx *gin.Context, tenantID, fileID, fileSize string) error {
size, err := sanitizeInput(fileSize)
if err != nil {
return fmt.Errorf("invalid file size: %w", err)
}
convertCmd := fmt.Sprintf("convert %s -resize %dx%d %s", targetFilename, size, size, targetFilename)
// ...
}それでも、
システムコマンドの代わりに安全なAPIやライブラリを使う
もう
たとえば、convertをgithub.com/disintegration/imagingのような
import (
"github.com/disintegration/imaging"
// ...
)
func resizeImage(inputPath, outputPath string, width, height int) error {
img, err := imaging.Open(inputPath)
if err != nil {
return fmt.Errorf("failed to open image: %w", err)
}
resizedImg := imaging.Resize(img, width, height, imaging.Lanczos)
err = imaging.Save(resizedImg, outputPath)
if err != nil {
return fmt.Errorf("failed to save image: %w", err)
}
return nil
}Goでimagingのような
脆弱なdownloadAndResize関数をリファクタリングしてインジェクションを防ぐ
先ほどのexec.CommandContext関数を
ユーザー入力にdownloadAndResize関数を
コマンドインジェクションをexec.Command関数と
コマンドインジェクションのdownloadAndResize関数の
func downloadAndResize(ctx *gin.Context, tenantID, fileID, fileSize string) error {
slog.Info("Processing request", "tenantID", tenantID, "fileID", fileID)
// Define the command and its arguments separately
args := []string{targetFilename, "-resize", fmt.Sprintf("%sx%s", fileSize, fileSize), targetFilename}
cmd := exec.CommandContext(ctx, "convert", args...)
slog.Info("Running command", "command", cmd.String())
// Execute the command
_, err := cmd.CombinedOutput()
if err != nil {
slog.Error("Error resizing image", "error", err)
return fmt.Errorf("%w: %v", ErrImageResize, err)
}
slog.Info("Downloaded and resized image", "filename", targetFilename)
return nil
}このexec.CommandContextに
また、sh -c)を
コードセキュリティにSnykを活用する
Snyk Codeは、
SnykがGoのコマンドインジェクションの脆弱性を特定する方法
先ほどのdownloadAndResize関数が
convertCmd := fmt.Sprintf("convert %s -resize %sx%s %s", targetFilename, fileSize, fileSize, targetFilename)
_, err := exec.CommandContext(ctx, "sh", "-c", convertCmd).CombinedOutput()この
チームの
コードレビューで
そんな
VS Codeエディターで

Snykは
さらに、ISSUE OVERVIEWタブを

こうした
無料の コードチェッカーツール
次の


