1

私は、ユーザーが出発地と到着地の住所を入力し、ルートを示す地図とともに道案内表 (ターンバイターン情報を提供する) を取得する道案内サービスに取り組んでいます。

以下は、完全なソース コード ( getdirections.php ) です。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <title>Directions</title>
 <style>
  * { font-family: Verdana; font-size: 96%; }
  label { width: 15em; float: left; }
  label.error { display: block; float: none; color: red; vertical-align: top; }
  p { clear: both; }
  .submit { margin-left: 12em; }
  em { font-weight: bold; padding-right: 1em; vertical-align: top; }
 </style>
 <script src="jquery-1.3.1.js" type="text/javascript">
 </script>
 <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false& amp;key=[Your Key Here]" 
type="text/javascript">
 </script>
</head>
<body onunload="GUnload()">
<div id="container">    
<div id="directform">
    <form id="direct" action="getdirections.php" method="get">
<p><label for="loc1">From Here:</label>
<input id="loc1" type="text" name="location1" class="required" /></p>
<p><label for="loc2">To Here:</label>
<input id="loc2" type="text" name="location2" class="required" /></p>
<p><input type="submit" value="Search" /></p>
    </form>
</div>
<?php
function filterInput ( $input ) {
$replacement = ',';
$input = preg_replace('/(\n|\r)+/', $replacement, $input);
$replacement = " ";
$input = preg_replace('/(\t)+/', $replacement, $input);
$inputarray = explode(' ', $input);
foreach ( $inputarray as $i => $value ) {
     $ch = '';
     if ( $value[strlen($value)-1] == ',') {
    $ch = ',';
    $value = substr($value, 0, -1);
     }

$value = 
      preg_replace('/^(\&|\(|\)|\[|\]|\{|\}|\"|\.|\!|\?|\'|\:|\;)+/', "", $value);

$inputarray[$i] = 
      preg_replace('/(\&|\(|\)|\[|\]|\{|\}|\"|\.|\!|\?|\'|\:|\;)+$/', "", $value);
$inputarray[$i] = $inputarray[$i].$ch;
}
$filteredString = implode(" ", $inputarray);
return $filteredString;
}

?>
</div>    
<table class="directions">
 <tr>
 <td valign="top">
  <div id="directions" style="width: 100%"></div>
 </td>
</tr>
<tr>
 <td valign="top">
 <div id="map_canvas" style="width: 250px; height: 400px"></div>
 </td>
</tr>
<td valign="top">
 <div id="directions_url"></div>
</td>   
</table>

 <noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> 
  However, it seems JavaScript is either disabled or not supported by your browser. 
  To view Google Maps, enable JavaScript by changing your browser options, and then 
  try again.
 </noscript>
 <script type="text/javascript">

 // This programming pattern limits the number of global variables
 // Thus it does not pollute the global namespace
 // for_directions is the only global object here.
 for_directions = function(){

// The map is loaded into the div element having id specified by mapid
// private variable
var mapid = "map_canvas";

// The direction listing is loaded into the div element having id specified by directionsid.
// private variable
var directionsid = "directions";

// From here
// private variable
var location1;

// To here
// private variable
var location2;

// The functions ( init and addevent )  are public methods of for_directions object
return {
    // Called on loading of this page
    // public method
    init: function (){
        location1 = "<?= filterInput($_GET['location1']) ?>" || 0;
        location2 = "<?= filterInput($_GET['location2']) ?>" || 0;
        var directions = document.getElementById(directionsid);
        directions.innerHTML = "Please check the address and try again";

        if ( GBrowserIsCompatible() && location1 != 0  && location2 != 0){
            mapAddress(location1, location2);
            }
    },

    // This method is cross browser compliant and is used to add an event listener
    // public method
    addEvent:function(elm,evType,fn,useCapture){
        if(elm.addEventListener){
            elm.addEventListener(evType, fn, useCapture);
            return true;
        } else if (elm.attachEvent) {
            var r = elm.attachEvent('on' + evType, fn);
            return r;
        } else {
            elm['on' + evType] = fn;
        }
    }
};

// Called from init 
// private method
    function mapAddress ( address1, address2 ){
        var geocoder = new GClientGeocoder();
    var directions = document.getElementById(directionsid);
    var i = 0;

    geocoder.getLatLng( address1, function(point1){
        if (point1){
        geocoder.getLatLng ( address2, function(point2){
            if (point2){
            getDirections();
            } else {
            directions.innerHTML = "Please check the address and try again";
            }

        });
        } else {
        directions.innerHTML = "Please check the address and try again";
        }

    });
}

// Called from mapAddress to load the directions and map
// private method
function getDirections( ){
     var gmap = new GMap2(document.getElementById(mapid));
     var gdir = new GDirections(gmap,document.getElementById(directionsid));
     gdir.load("from: " + location1 + " to: " + location2,
            { "locale": "en_US" });
     generateURL();
}

function generateURL(){
    var url = "http://maps.google.com/maps?saddr=";
    url += location1;
    url += "&daddr=";
    url += location2;
    var a = $("<a></a>").attr('href',url);
    $(a).text("Google Maps");
    $("#directions_url").append(a);
}
}();
// The (); above results in the function being interpreted by the browser just before   the page is loaded.

// Make for_directions.init as the listener to load event
// Note that the init method is public that why its accessible outside the object scope
for_directions.addEvent(window, 'load', for_directions.init, false);
</script>
</body>
</html>

システム名でこのコードを試す場合は、getdirections.php とします。変更する必要があるのは、Google マップの API キーだけです。ここで鍵を入手できます。

キーを生成したら、 key パラメータに入れます (便宜上、以下の行を再現します):

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false& amp;key=[Your key here]" 
type="text/javascript">

上記のコードからわかるように、PHP を介して入力を取得し、Javascript で処理を行います。今、私は、ユーザーがどんな種類の入力 (javascript、危険な HTML など) でも逃れることを望んでいません。PHPでurlencode関数を使ってみました。ただし、エンコードされたユーザー入力は JavaScript コードによって受け入れられず、適切な入力でも失敗します。

この問題の回避策として、特定の文字を置換/削除し、ユーザーが入力を通じて Javascript コードを実行しようとする試みを阻止する filterInput 関数を PHP で作成しました。

これはうまくいきました。ただし、ユーザーが悪意のある入力を試みた場合、たとえば "+alert("hello")+" のように開始引用符と終了引用符の両方が含まれている場合、filterInput 関数は先頭と末尾の引用符を削除し、結果の文字列は次のようになります。

+alert("hello")+

以下のコードが実行されると:

location1 = "<?= filterInput($_GET['location1']) ?>" || 0;

PHP は、以下のように関数呼び出しをその戻り値に置き換えます。

location1 = "+alert("hello")+" || 0;

上記の行でスクリプトの実行がエラーで停止します ( missing ; before statement )

引用符をトリミングせずに $_GET['location1'] を直接使用した場合は、取得できることに注意してください。

location1 = ""+alert("hello")+"" || 0;

alert("hello") が実行されます!!

だから、私は修正中です。入力をフィルタリングすると、特定のユーザー入力で JavaScript エラーが発生し、入力をフィルタリングしないと、ユーザーはあらゆる種類の JavaScript を実行できます。

私の質問は次のとおりです。

  • Web で入力を処理するための適切で安全な方法は何ですか?
  • この種のユーザー入力はクロス言語 (PHP から Javascript へ) で大丈夫ですか?
  • ユーザーが JavaScript を実行できること以外に、このコードの脆弱性はどのような種類のセキュリティ脅威に影響されますか?

読んでくれてありがとう!!

助けてください。

4

1 に答える 1

2

php で json_encode を、javascript で eval を試すことができます。

入力が行われるのと同じマシンで JS が実行される場合、セキュリティについてあまり心配する必要はありません。ハッカーは自分のマシンをハッキングできますが、問題はないはずです。

于 2009-07-08T18:32:55.093 に答える