0

ファイル全体を検索して、Java XML パーサーの最初の部分に一致するものを見つけますが、2 番目の部分には一致しない正規表現を 1 つ作成する必要があります。これは、いくつかの XXE 攻撃から保護するために使用されます。残念ながら、単一の正規表現である必要あり、(行ごとではなく) ファイル全体を検索する必要があります。

DocumentBuilderFactory を見つけるために Java ファイルを検索しています。初期化された変数が以下の setFeature または setEntity を介して実行されない場合、または変数が以下の setFeature を介して実行されないSAXParserFactory を検索する場合を探しています。

正規表現を失敗させたい場合の私のケースは次のとおりです。

ケース A (単純なケース):

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
...
docBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);

ケース B (複数行):

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
...
docBuilderFactory
.setExpandEntityReferences(false);

ケース C (DocumentBuilder の代わりに SAXParser を使用):

SAXParserFactory spf = SAXParserFactory.newInstance();
...
spf.setFeature("http://xml.org/sax/features/external-general-entities", false);

繰り返しますが、DocumentBuilderFactory または SAXParserFactory の後に setFeature または setExpandEntity が続いていないケースを正規表現で検出する必要があります。

これは私がこれまでに持っているものです(願わくば、少し理解を深めるためにフォーマットされています):

DocumentBuilderFactory (\w+).*=.*DocumentBuilderFactory
[\n|\r]?.*?
\.
[\n|\r]?.*?
newInstance\(\)
(?>.|\n|\r)*
(\1[\n|\r]?.*?\.[\n|\r]?.*?setExpandEntityReferences\(false\)
|\1[\n|\r]?.*?\.[\n|\r]?.*?setFeature\("http://xml.org/sax/features/external-general-entities", false\)
|\1[\n|\r]?.*?\.[\n|\r]?.*?setFeature\("http://apache.org/xml/features/disallow-doctype-decl", false\)).*

|SAXParserFactory (\w+).*=.*SAXParserFactory
[\n|\r]?.*?
\.
[\n|\r]?.*?
newInstance\(\)
(?>.|\n|\r)*
(\1[\n|\r]?.*?\.[\n|\r]?.*?setFeature\("http://xml.org/sax/features/external-general-entities", false\)
|\1[\n|\r]?.*?\.[\n|\r]?.*?setFeature\("http://apache.org/xml/features/disallow-doctype-decl", false\)).*

これらの setFeatures が見つからないようにするのが困難であり、setFeatures がまったく見られていないと確信しています。

4

1 に答える 1

2

This is a tough problem when you add the restriction that you have to do it in a single global regex, but I was able to get the following to work, as long as you set . to match newline characters:

(?:DocumentBuilderFactory|SAXParserFactory)[\s\r\n]+?(\w+)[\s\r\n]*?=[\s\r\n]*?(?:DocumentBuilderFactory|SAXParserFactory)[\.\r\n]+newInstance(?!.*\1(?=[\.\r\n]+(:?setFeature|setExpandEntity)))

The only way I can find to do it is to put a positive lookahead inside a negative lookahead, which may not be supported by some engines, and runs quite slowly.

于 2013-07-12T17:00:57.847 に答える