C#Windows IPSECモニタ(この1社のみ、支店なし)
17410 ワード
Windows IPSECモニタは、C#を使用して作成され、1行の文字列として出力され、既存のIPSECルールに従ってテンプレートを生成することができます
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace WindowsIPSecMonitor
{
class WindowsIPSecMonitor
{
//***** *****
//
private static void RedError(string text)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(text);
Console.ForegroundColor = ConsoleColor.White;
}
//
private static void YellowWarn(string text)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(text);
Console.ForegroundColor = ConsoleColor.White;
}
//
private static void GreenPrint(string text)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(text);
Console.ForegroundColor = ConsoleColor.White;
}
//
private static string Execute(string command, int seconds)
{
string output = ""; //
if (command != null && !command.Equals(""))
{
Process process = new Process();//
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";//
startInfo.Arguments = "/C " + command;//“/C”
startInfo.UseShellExecute = false;//
startInfo.RedirectStandardInput = false;//
startInfo.RedirectStandardOutput = true; //
startInfo.CreateNoWindow = true;//
process.StartInfo = startInfo;
try
{
if (process.Start())//
{
if (seconds == 0)
{
process.WaitForExit();//
}
else
{
process.WaitForExit(seconds); // ,
}
output = process.StandardOutput.ReadToEnd();//
}
}
catch
{
}
finally
{
if (process != null)
process.Close();
}
}
return output;
}
//
private static void FileRec(string input, string filename)
{
FileStream fs = new FileStream(filename, FileMode.Append);
StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("GB2312"));
//
sw.Write(input);
//
sw.Flush();
//
sw.Close();
fs.Close();
}
//
private static void AppendFile(string Filenamesrc, string Filenamedst)
{
string command = "type " + Filenamesrc + ">>" + Filenamedst;
Execute(command, 1);
}
//
private static void GenCurrentLocalTemplates()
{
//
string cmd;
//
//cmd = "netsh ipsec static show policy all | findstr \" \" 2>&1"; //
cmd = "netsh ipsec static show policy all | findstr \"Policy name\" 2>&1";//
string[] policy = Execute(cmd, 1).Replace(" ", "").Replace("Policy Name", "").Replace("\r
", "").Replace(":", "").Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
foreach (string policyname in policy)
{
//
cmd = "netsh ipsec static show rule all policy = " + policyname + " level = Verbose Format = table>CurrentFullIPSec.log 2>&1";
Execute(cmd, 1);
//
try
{
//int Counter = 0;
string line;
// “ ”/“YES”
StreamReader file1 = new StreamReader("CurrentFullIPSec.log", Encoding.GetEncoding("GB2312"));
while ((line = file1.ReadLine()) != null)
{
//if (line.StartsWith(" "))//
if (line.StartsWith("YES"))//
{
string ProcessedData = Environment.NewLine + line.TrimEnd();
FileRec(ProcessedData, "Temp1.log");
}
else
{
FileRec(line + Environment.NewLine, "Temp1.log");
}
//Counter++;//
}
file1.Close();//
// YES
//Counter = 0;
StreamReader file2 = new StreamReader("Temp1.log", Encoding.GetEncoding("GB2312"));
while ((line = file2.ReadLine()) != null)
{
//if (line.StartsWith(" ") || line.StartsWith("YES") || line.StartsWith(" ") || line.StartsWith("Rule Name") || line.StartsWith(" ") || line.StartsWith("FilterAction Name") || line.StartsWith(" ") || line.StartsWith("Action") || line.StartsWith(" ") || line.StartsWith("No. of Filters"))
if (line.StartsWith(" ") || line.StartsWith("YES") || line.StartsWith(" ") || line.StartsWith("Action"))
{
string ProcessedData = line.Trim() + Environment.NewLine;
ProcessedData = ProcessedData.Replace(" ", "").Replace("\t", "");
FileRec(ProcessedData, "LocalTemplate.log");
}
//Counter++;//
}
file2.Close();//
//
File.Delete("Temp1.log");
File.Delete("CurrentFullIPSec.log");
//Counter = 0;
StreamReader file3 = new StreamReader("LocalTemplate.log", Encoding.GetEncoding("GB2312"));
while ((line = file3.ReadLine()) != null)
{
if (line.StartsWith(" ") || line.StartsWith("Action"))
{
//
string NewFilename = line.Trim() + ".txt";
//
AppendFile("Temp2.log", NewFilename);
File.Delete("Temp2.log");
}
else
{
FileRec(line + Environment.NewLine, "Temp2.log");
}
//Counter++;//
}
file3.Close();//
File.Delete("LocalTemplate.log");
}
catch (IOException)
{
Console.WriteLine("IO Error! Please consult the programmer!" + Environment.NewLine);
}
}
}
//
private static void GenMonitorTemplates(string TemplateFile)
{
string line;
try
{
StreamReader file = new StreamReader(TemplateFile, Encoding.GetEncoding("GB2312"));
line = file.ReadToEnd();
string[] policylines = line.Split(new string[] { "BLOCK", "PERMIT" }, StringSplitOptions.RemoveEmptyEntries);
FileRec(policylines[0], "MonitorPermitTemplate.txt");
FileRec(policylines[1], "MonitorBlockTemplate.txt");
file.Close();//
}
catch (Exception)
{
Console.WriteLine("File IO Error!");
}
}
//
private static string CompareFile(string FileSRC, string FileDST)
{
//int Counter = 0;
string lineA;
string lineB;
string lineC = "";
if (!File.Exists(FileSRC) || !File.Exists(FileDST))
{
return "Files don't exist! Comparation failed!";
}
else
{
try
{
StreamReader fileA = new StreamReader(FileSRC, Encoding.GetEncoding("GB2312"));
StreamReader fileB = new StreamReader(FileDST, Encoding.GetEncoding("GB2312"));
lineB = fileB.ReadToEnd();
while ((lineA = fileA.ReadLine()) != null)
{
if (!lineB.Contains(lineA.Trim()))
{
lineC += lineA + Environment.NewLine;
}
//Counter++;//
}
fileA.Close();//
fileB.Close();//
}
catch (Exception)
{
Console.WriteLine("File IO error!");
}
return lineC;
}
}
//
private static void DeleteFile()
{
//File.Delete(" .txt");//
//File.Delete(" .txt");//
File.Delete("ActionPERMIT.txt");//
File.Delete("ActionBLOCK.txt");//
File.Delete("MonitorPermitTemplate.txt");// PERMIT
File.Delete("MonitorBlockTemplate.txt");// BLOCK
}
//
public class Data
{
public string time;
public string result;
public string status;
public string JobID;
public void Print_data()
{
Console.WriteLine("{\"result\":\"" + result + "\",\"status\":\"" + status + "\",\"time\":\"" + time + "\",\"id\":\"" + JobID + "\",\"info\":\"\"}");
}
}
//
static void Main(string[] args)
{
string Current_Path = AppDomain.CurrentDomain.BaseDirectory;
// ,
string cmd;
try
{
//***** *****
if (args[0] == "-h" || args[0] == "--help")
{
GreenPrint("Usage:");
GreenPrint("Use WindowsIPSecMonitor.exe --Backup to backup current localmachine's IPSec");
GreenPrint("Use WindowsIPSecMonitor.exe --GCLMT to generate current localmachine's IPSec monitor tempalte");
GreenPrint("Use WindowsIPSecMonitor.exe --Investigate --idle [MonitorTemplateFileName] to see the IPSec comparation result");
GreenPrint("Use WindowsIPSecMonitor.exe [JobID] [Server] [MonitorTemplateFileName] to see the monitor result");
Environment.Exit(0);
}
// IPSec
if (args[0] == "--Backup")
{
string time = DateTime.Now.ToString("yyyy-MM-dd#HH.mm.ss");
cmd = "netsh ipsec static exportpolicy file=" + time;
Execute(cmd, 1);
YellowWarn("IPSec has been backed up as " + time + ".ipsec!");
Environment.Exit(0);
}
//
if (args[0] == "--GCLMT")
{
//
GenCurrentLocalTemplates();
//cmd = "(echo PERMIT&type .txt&echo BLOCK&type .txt)>NewlyGeneratedTempalteForMonitor.txt";//
cmd = "(echo PERMIT&type ActionPERMIT.txt&echo BLOCK&type ActionBLOCK.txt)>NewlyGeneratedTempalteForMonitor.txt";//
Execute(cmd, 1);
YellowWarn("Template generated! Filename is NewlyGeneratedTempalteForMonitor.txt.");
//File.Delete(" .txt");//
//File.Delete(" .txt");//
File.Delete("ActionPERMIT.txt");//
File.Delete("ActionBLOCK.txt");//
Environment.Exit(0);
}
}
catch (Exception)
{
RedError("Parameter error! Use -h or --help for help");
Environment.Exit(0);
}
//
Data D = new Data();
D.status = "2";
D.result = "IPSec is fine!";
D.time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
try
{
D.JobID = args[0];
}
catch (Exception)
{
RedError("Parameter error! Use -h or --help for help");
Environment.Exit(0);
}
// IPSec
cmd = "netsh ipsec static show policy all";
bool NotAssigned1 = Execute(cmd, 1).Contains("Assigned : NO");
bool NotAssigned2 = Execute(cmd, 1).Contains(" : ");
if (NotAssigned1 || NotAssigned2)
{
D.status = "4";
D.result = "Policy is not assigned!";
D.Print_data();
Environment.Exit(0);
}
//
GenCurrentLocalTemplates();
try
{
// ,
GenMonitorTemplates(Current_Path + args[2]);
//
//string result1 = CompareFile("MonitorPermitTemplate.txt", " .txt");//
//string result2 = CompareFile(" .txt", "MonitorPermitTemplate.txt");//
//string result3 = CompareFile("MonitorBlockTemplate.txt", " .txt");//
//string result4 = CompareFile(" .txt", "MonitorBlockTemplate.txt");//
string result1 = CompareFile("MonitorPermitTemplate.txt", "ActionPERMIT.txt");//
string result2 = CompareFile("ActionPERMIT.txt", "MonitorPermitTemplate.txt");//
string result3 = CompareFile("MonitorBlockTemplate.txt", "ActionBLOCK.txt");//
string result4 = CompareFile("ActionBLOCK.txt", "MonitorBlockTemplate.txt");//
//
if (args[0] == "--Investigate")
{
YellowWarn("LocalPermit lacks the following line(s):");
Console.WriteLine(result1);
YellowWarn("MonitorPermit lacks the fowllowing line(s):");
Console.WriteLine(result2);
YellowWarn("LocalBlock lakcs the following line(s):");
Console.WriteLine(result3);
YellowWarn("MonitorBlock lacks the following line(s):");
Console.WriteLine(result4);
DeleteFile();
}
else
{
if (result1 != "" || result2 != "" || result3 != "" || result4 != "")
{
D.status = "4";
D.result = "IPSec error!";
D.Print_data();
DeleteFile();
Environment.Exit(0);
}
//
D.Print_data();
DeleteFile();
Environment.Exit(0);
}
}
catch (Exception)
{
RedError("Error! No filename parameter provided!");
DeleteFile();
}
}
}
}