Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

UtilityConfig.cpp 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. // UtilityConfig.cpp
  2. //
  3. // Copyright (C) 2011, ARM Research Labs, LLC.
  4. // See www.armresearch.com for the copyright terms.
  5. //
  6. // This file implements the common functionality for the configuration
  7. // utilities.
  8. #include <cerrno>
  9. #include <cstring>
  10. #include <unistd.h>
  11. #include <pwd.h>
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #include <stdexcept>
  15. #include <sstream>
  16. #include <iostream>
  17. #include <fstream>
  18. #include <vector>
  19. #include "UtilityConfig.hpp"
  20. using namespace std;
  21. //////////////////////////////////////////////////////////////////////////////////////////////////////////
  22. // Configuration. ////////////////////////////////////////////////////////////////////////////////////////
  23. //////////////////////////////////////////////////////////////////////////////////////////////////////////
  24. // Initialize OS-dependent constants.
  25. #ifdef WIN
  26. // Windows OS.
  27. const std::string UtilityConfig::SampleIgnoreListFile("C:\\SNF\\GBUdbIgnoreList.txt.sample");
  28. const std::string UtilityConfig::RulebaseDownloadCommand("FIX THIS");
  29. const std::string ScriptNameKey("FIX THIS"); ///< Text to replace with script name.
  30. const std::string SnifferPathKey("FIX THIS"); ///< Text to replace with directory of the rulebase.
  31. const std::string UtilityConfig::SampleRulebaseScriptFile("C:\\SNF\\getRulebase.sample");
  32. const std::string UtilityConfig::OperatingSystemType("Windows");
  33. #else
  34. // *nix OS.
  35. // SCRIPT is replaced with the full path of the script run,
  36. // SNIFFER_PATH is replaced with the path of the rulebase.
  37. const std::string UtilityConfig::RulebaseDownloadCommand
  38. ("(cd SNIFFER_PATH; touch UpdateReady.txt; chown snfuser UpdateReady.txt; su -m snfuser -c SCRIPT)");
  39. const std::string ScriptNameKey("SCRIPT"); ///< Text to replace with script name.
  40. const std::string SnifferPathKey("SNIFFER_PATH"); ///< Text to replace with directory of the rulebase.
  41. #ifdef DEFAULT_DATA_DIR
  42. // *nix, DEFAULT_DATA_DIR is specified on the compile command line.
  43. const std::string UtilityConfig::SampleIgnoreListFile(DEFAULT_DATA_DIR "/GBUdbIgnoreList.txt.sample");
  44. #else
  45. // Not Windows, and DEFAULT_DATA_DIR is not specified on the compile
  46. // command line. In this case, we don't know the path for the sample
  47. // ignore list file.
  48. #error DEFAULT_DATA_DIR must be defined by -DDEFAULT_DATA_DIR="..." when compiling.
  49. #endif
  50. #ifdef SBIN_DIR
  51. // *nix, SBIN_DIR is specified on the compile command line.
  52. const std::string UtilityConfig::SampleRulebaseScriptFile(SBIN_DIR "/getRulebase.sample");
  53. #else
  54. // Not Windows, and SBIN_DIR is not specified on the compile
  55. // command line. In this case, we don't know the path for the sample
  56. // ignore list file.
  57. #error SBIN_DIR must be defined by -DSBIN_DIR="..." when compiling.
  58. #endif
  59. #ifdef SNF_OSTYPE
  60. // *nix, SNF_OSTYPE is specified on the compile command line.
  61. const std::string UtilityConfig::OperatingSystemType(SNF_OSTYPE);
  62. #else
  63. // Not Windows, and SNF_OSTYPE is not specified on the compile command
  64. // line. In this case, we don't know the operating system.
  65. #error SNF_OSTYPE must be defined by -DSNF_OSTYPE="..." when compiling.
  66. #endif
  67. #endif
  68. /// Verbose command-line input.
  69. const string VerboseKey("-v");
  70. /// Explain command-line input.
  71. const string ExplainKey("-explain");
  72. /// Help command-line input.
  73. const string HelpKey("-h");
  74. /// Configuration file command-line input.
  75. const string ConfigFileKey("-config=");
  76. /// License ID command-line input.
  77. const string LicenseIdKey("-id=");
  78. /// Authentication command-line input.
  79. const string AuthenticationKey("-auth=");
  80. const string LicenseSearchString = "LICENSE_ID=";
  81. const string AuthSearchString = "AUTHENTICATION=";
  82. //////////////////////////////////////////////////////////////////////////////////////////////////////////
  83. // End of configuration. /////////////////////////////////////////////////////////////////////////////////
  84. //////////////////////////////////////////////////////////////////////////////////////////////////////////
  85. UtilityConfig::UtilityConfig() :
  86. LicenseIdIsSpecified(false), AuthenticationIsSpecified(false), ConfigFileExists(true)
  87. {
  88. SetExplain(false);
  89. SetVerbose(false);
  90. SetHelp(false);
  91. }
  92. void
  93. UtilityConfig::CheckAndSetConfigFileName(const std::string DefaultFile[], int NumDefaultFiles) {
  94. string ProvisionalConfigFile = ConfigFileName;
  95. if (ProvisionalConfigFile.length() == 0) {
  96. int i;
  97. vector<string> FoundFile;
  98. for (i = 0; i < NumDefaultFiles; i++) {
  99. if (!FileExists(DefaultFile[i])) {
  100. continue; // File doesn't exist.
  101. }
  102. FoundFile.push_back(DefaultFile[i]); // Update list of found files.
  103. ProvisionalConfigFile = DefaultFile[i]; // Found configuration file.
  104. }
  105. if (0 == FoundFile.size()) { // No default file found.
  106. if (NumDefaultFiles > 0) {
  107. ProvisionalConfigFile = DefaultFile[0]; // Use the first default file.
  108. ConfigFileExists = false;
  109. } else { // No default config file was specified.
  110. ostringstream Temp;
  111. Temp << "Internal error: NumDefaultFiles <= 0 at " << __FILE__ << ":" << __LINE__;
  112. throw runtime_error(Temp.str());
  113. }
  114. } else if (FoundFile.size() > 1) { // Multiple default files found.
  115. string Temp;
  116. Temp = "Configuration file was not specified, and more than one default configuration file was found::\n\n";
  117. for (i = 0; i < FoundFile.size(); i++) {
  118. Temp += " ";
  119. Temp += FoundFile[i] + "\n";
  120. }
  121. throw runtime_error(Temp);
  122. } else {
  123. ConfigFileExists = true; // Config file was found.
  124. }
  125. } else {
  126. ConfigFileExists = FileExists(ProvisionalConfigFile);
  127. }
  128. SetConfigFileName(ProvisionalConfigFile);
  129. }
  130. void
  131. UtilityConfig::CreateDefaultConfigFile(std::string SampleConfigFile) {
  132. std::string File = GetConfigFileName();
  133. if (!ConfigFileExists) {
  134. // Create the config file.
  135. Copy(SampleConfigFile, File);
  136. }
  137. }
  138. void
  139. UtilityConfig::CreateDefaultIdentityFile(std::string SampleIdentityFile) {
  140. std::string File = GetIdentityFileName();
  141. if (!FileExists(File)) {
  142. // Create the config file.
  143. Copy(SampleIdentityFile, File);
  144. }
  145. }
  146. void
  147. UtilityConfig::LoadConfig() {
  148. if (Verbose()) {
  149. cout << "Using configuration file " << GetConfigFileName() << ".\n";
  150. }
  151. // Load the data.
  152. try {
  153. CFGData.initializeFromFile(GetConfigFileName().c_str());
  154. } catch(...) {
  155. string Temp;
  156. Temp = "Error reading configuration file " + GetConfigFileName();
  157. Temp += ".";
  158. throw runtime_error(Temp);
  159. }
  160. if ( (CFGData.paths_workspace_path.length() == 0) ||
  161. (CFGData.paths_rulebase_path.length() == 0) ||
  162. (CFGData.paths_log_path.length() == 0) ||
  163. (CFGData.update_script_call.length() == 0) ||
  164. (CFGData.node_identity.length() == 0) ) {
  165. string Temp;
  166. Temp = "The configuration file " + GetConfigFileName();
  167. Temp += " did not have the necessary specification of one or more paths:\n";
  168. Temp += "\n Workspace path: " + CFGData.paths_workspace_path;
  169. Temp += "\n Rulebase path: " + CFGData.paths_rulebase_path;
  170. Temp += "\n Log path: " + CFGData.paths_log_path;
  171. Temp += "\n Update script: " + CFGData.update_script_call;
  172. Temp += "\n Identity file: " + CFGData.node_identity;
  173. throw runtime_error(Temp);
  174. }
  175. }
  176. string
  177. UtilityConfig::GetPlatformContents(void) {
  178. return CFGData.PlatformElementContents;
  179. }
  180. string
  181. UtilityConfig::GetConfigFileName(void) {
  182. return ConfigFileName;
  183. }
  184. void
  185. UtilityConfig::SetConfigFileName(string Name) {
  186. ConfigFileName = Name;
  187. }
  188. string
  189. UtilityConfig::GetWorkspacePath(void) {
  190. return CFGData.paths_workspace_path;
  191. }
  192. string
  193. UtilityConfig::GetRulebasePath(void) {
  194. return CFGData.paths_rulebase_path;
  195. }
  196. string
  197. UtilityConfig::GetLogPath(void) {
  198. return CFGData.paths_log_path;
  199. }
  200. string
  201. UtilityConfig::GetIdentityFileName(void) {
  202. return CFGData.node_identity;
  203. }
  204. string
  205. UtilityConfig::GetRulebaseScriptName(void) {
  206. return CFGData.update_script_call;
  207. }
  208. string
  209. UtilityConfig::GetIgnoreListFileName(void) {
  210. return GetWorkspacePath() + "GBUdbIgnoreList.txt";
  211. }
  212. string
  213. UtilityConfig::GetRulebaseFileName(void) {
  214. std::string Name;
  215. Name = GetRulebasePath();
  216. Name += LicenseId + ".snf";
  217. return Name;
  218. }
  219. string
  220. UtilityConfig::GetOperatingSystemType(void) {
  221. return OperatingSystemType;
  222. }
  223. void
  224. UtilityConfig::LoadInfo(){
  225. if ("OpenBSD" == OperatingSystemType) {
  226. PostfixMainCfPath = "/usr/local/etc/postfix/main.cf";
  227. PostfixMasterCfPath = "/usr/local/etc/postfix/master.cf";
  228. } else if ("FreeBSD" == OperatingSystemType) {
  229. PostfixMainCfPath = "/etc/postfix/main.cf";
  230. PostfixMasterCfPath = "/etc/postfix/master.cf";
  231. } else if ("Ubuntu" == OperatingSystemType) {
  232. PostfixMainCfPath = "/etc/postfix/main.cf";
  233. PostfixMasterCfPath = "/etc/postfix/master.cf";
  234. } else if ("RedHat" == OperatingSystemType) {
  235. PostfixMainCfPath = "/etc/postfix/main.cf";
  236. PostfixMasterCfPath = "/etc/postfix/master.cf";
  237. } else if ("Suse" == OperatingSystemType) {
  238. PostfixMainCfPath = "/etc/postfix/main.cf";
  239. PostfixMasterCfPath = "/etc/postfix/master.cf";
  240. } else {
  241. ostringstream Temp;
  242. Temp << "Internal error in UtilityConfig::LoadInfo: Invalid value of OperatingSystemType: "
  243. << OperatingSystemType;
  244. throw runtime_error(Temp.str());
  245. }
  246. }
  247. void
  248. UtilityConfig::UpdateIgnoreListFile() {
  249. string IgnoreListFile = GetIgnoreListFileName();
  250. if (!FileExists(IgnoreListFile)) {
  251. Copy(SampleIgnoreListFile, IgnoreListFile);
  252. }
  253. SetMode(IgnoreListFile, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); // Set permissions.
  254. SetOwnerGroup(IgnoreListFile); // Set to sniffer user.
  255. }
  256. void
  257. UtilityConfig::UpdateLogDir() {
  258. string LogDir = GetLogPath();
  259. if (!FileExists(LogDir)) {
  260. MkDir(LogDir);
  261. }
  262. SetMode(LogDir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
  263. SetOwnerGroup(LogDir);
  264. }
  265. bool
  266. UtilityConfig::UpdateCredentialsSpecified() {
  267. return ( (LicenseId.length() > 0) && (Authentication.length() > 0) );
  268. }
  269. void
  270. UtilityConfig::CreateUpdateRulebaseScript() {
  271. std::string File = GetRulebaseScriptName();
  272. if (!FileExists(File)) {
  273. Copy(SampleRulebaseScriptFile, File); // Copy if !Explain().
  274. }
  275. if (UpdateCredentialsSpecified()) {
  276. UpdateRulebaseScriptCredentials();
  277. }
  278. SetMode(File, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); // Set permissions.
  279. }
  280. void
  281. UtilityConfig::UpdateRulebaseScriptCredentials() {
  282. std::string File = GetRulebaseScriptName();
  283. if (Verbose()) {
  284. cout << "Update authentication and license ID in the rulebase download script file " << File << "--\n";
  285. }
  286. ifstream Input;
  287. Input.open(File.c_str()); // Read the contents.
  288. if (!Input) {
  289. string Temp;
  290. Temp = "Error opening rulebase download script file " + File;
  291. Temp += " for reading: ";
  292. Temp += strerror(errno);
  293. throw runtime_error(Temp);
  294. }
  295. string Content;
  296. string Line;
  297. bool FoundLicense = false;
  298. bool FoundAuth = false;
  299. while (getline(Input, Line)) {
  300. if (CheckForString(Line, LicenseSearchString)) { // Check for license line.
  301. if (FoundLicense) { // Second license line found?
  302. string Temp;
  303. Temp = "Rulebase sownload script file " + File;
  304. Temp += " has the wrong format: Found two lines beginning with " + LicenseSearchString;
  305. throw runtime_error(Temp);
  306. }
  307. if (Verbose()) {
  308. cout << " Modify line: '" << Line << "'...\n";
  309. }
  310. FoundLicense = true;
  311. Line = LicenseSearchString + LicenseId; // Add license line.
  312. Line += " # Added by SNFSetup";
  313. }
  314. if (CheckForString(Line, AuthSearchString)) { // Check for authentication line.
  315. if (FoundAuth) { // Second authentication line found?
  316. string Temp;
  317. Temp = "Rulebase download script file " + File;
  318. Temp += " has the wrong format: Found two lines beginning with " + AuthSearchString;
  319. throw runtime_error(Temp);
  320. }
  321. if (Verbose()) {
  322. cout << " Modify line: '" << Line << "'...\n";
  323. }
  324. FoundAuth = true;
  325. Line = AuthSearchString + Authentication; // Add authentication line.
  326. Line += " # Added by SNFSetup";
  327. }
  328. Content += Line + "\n";
  329. }
  330. if (!FoundLicense || !FoundAuth) {
  331. string Temp;
  332. Temp = "Rulebase download script file " + File;
  333. Temp += " has the wrong format: Missing required line beginning with '" + LicenseSearchString;
  334. Temp += "' or '" + AuthSearchString;
  335. Temp += "'";
  336. throw runtime_error(Temp);
  337. }
  338. if (!Input.eof()) { // Should be at end-of-file.
  339. string Temp;
  340. Temp = "Error reading the rulebase download script file " + File;
  341. Temp += ": ";
  342. Temp += strerror(errno);
  343. throw runtime_error(Temp);
  344. }
  345. Input.close();
  346. if (Input.bad()) {
  347. string Temp;
  348. Temp = "Error closing the rulebase download script file " + File;
  349. Temp += " after reading: ";
  350. Temp += strerror(errno);
  351. throw runtime_error(Temp);
  352. }
  353. if (!Explain()) {
  354. ofstream Output; // Write the updated contents.
  355. Output.open(File.c_str(), ios::trunc);
  356. if (!Output) {
  357. string Temp;
  358. Temp = "Error opening rulebase download script file " + File;
  359. Temp += " for writing: ";
  360. Temp += strerror(errno);
  361. throw runtime_error(Temp);
  362. }
  363. Output << Content;
  364. if (!Output) {
  365. string Temp;
  366. Temp = "Error writing the rulebase download script file " + File;
  367. Temp += ": ";
  368. Temp += strerror(errno);
  369. throw runtime_error(Temp);
  370. }
  371. Output.close();
  372. if (!Output) {
  373. string Temp;
  374. Temp = "Error closing the rulebase download script file " + File;
  375. Temp += " after writing: ";
  376. Temp += strerror(errno);
  377. throw runtime_error(Temp);
  378. }
  379. }
  380. OutputVerboseEnd();
  381. }
  382. void
  383. UtilityConfig::DownloadRulebase() {
  384. if (!UpdateCredentialsSpecified()) {
  385. return;
  386. }
  387. if (Verbose()) {
  388. std::cout << "Downloading the rulebase...";
  389. }
  390. std::string Command;
  391. Command = RulebaseDownloadCommand;
  392. std::string::size_type ScriptIndex = Command.find(ScriptNameKey);
  393. if (ScriptIndex != std::string::npos) { // Insert script full path?
  394. Command.replace(ScriptIndex, ScriptNameKey.length(), GetRulebaseScriptName());
  395. }
  396. std::string::size_type SnifferPathIndex = Command.find(SnifferPathKey);
  397. if (SnifferPathIndex != std::string::npos) { // Insert rulebase location?
  398. Command.replace(SnifferPathIndex, SnifferPathKey.length(), GetRulebasePath());
  399. }
  400. if (!Explain()) {
  401. if (std::system(Command.c_str()) != 0) {
  402. string Temp;
  403. Temp = "Error running the command '" + Command;
  404. Temp += "'.";
  405. throw runtime_error(Temp);
  406. }
  407. }
  408. OutputVerboseEnd();
  409. }
  410. void
  411. UtilityConfig::UpdateIdentityFile() {
  412. std::string File = GetIdentityFileName();
  413. if (UpdateCredentialsSpecified()) {
  414. ofstream Output;
  415. if (Verbose()) {
  416. cout << "Create identity file " << File << "...";
  417. }
  418. if (!Explain()) {
  419. Output.open(File.c_str());
  420. if (!Output) {
  421. string Temp;
  422. Temp = "Error opening identity file " + File;
  423. Temp += ": ";
  424. Temp += strerror(errno);
  425. throw runtime_error(Temp);
  426. }
  427. Output << "<!-- License file created by SNFIdentity-->\n"
  428. << "<snf>\n"
  429. << " <identity licenseid='" << LicenseId << "' authentication='"
  430. << Authentication << "'/>\n"
  431. << "</snf>\n";
  432. if (!Output) {
  433. string Temp;
  434. Temp = "Error writing identity file " + File;
  435. Temp += ": ";
  436. Temp += strerror(errno);
  437. throw runtime_error(Temp);
  438. }
  439. Output.close();
  440. if (!Output) {
  441. string Temp;
  442. Temp = "Error closing identity file " + File;
  443. Temp += ": ";
  444. Temp += strerror(errno);
  445. throw runtime_error(Temp);
  446. }
  447. }
  448. OutputVerboseEnd();
  449. }
  450. SetOwnerGroup(File); // Set the user and group.
  451. SetMode(File, S_IRUSR); // Set to readonly by owner.
  452. }
  453. bool
  454. UtilityConfig::ProcessCommandLineItem(std::string OneInput) {
  455. bool ValidCommand = true;
  456. std::string TempString;
  457. if (OneInput == VerboseKey) {
  458. SetVerbose(true);
  459. } else if (OneInput == ExplainKey) {
  460. SetExplain(true);
  461. } else if (OneInput == HelpKey) {
  462. SetHelp(true);
  463. } else if (OneInput == ConfigFileKey) {
  464. SetConfigFileName(OneInput.substr(ConfigFileKey.length()));
  465. } else if (0 == OneInput.find(LicenseIdKey)) {
  466. TempString = Trim(OneInput.substr(LicenseIdKey.length())); // Copy only if not null after trimming.
  467. if (!TempString.empty()) {
  468. LicenseId = TempString;
  469. LicenseIdIsSpecified = true;
  470. } else {
  471. ValidCommand = false;
  472. }
  473. } else if (0 == OneInput.find(AuthenticationKey)) {
  474. Authentication = Trim(OneInput.substr(AuthenticationKey.length()));
  475. AuthenticationIsSpecified = true;
  476. } else {
  477. ValidCommand = false;
  478. }
  479. return ValidCommand;
  480. }
  481. bool
  482. UtilityConfig::CommandLineIsOkay() {
  483. return (AuthenticationIsSpecified == LicenseIdIsSpecified);
  484. }
  485. std::string
  486. UtilityConfig::HelpCommandLine() {
  487. std::string Help;
  488. Help = "[" + ConfigFileKey + "snf-config-file] ";
  489. Help += "[" + LicenseIdKey + "licenseid " + AuthenticationKey + "authentication] ";
  490. Help += "[ " + VerboseKey + " " + ExplainKey + " ]";
  491. return Help;
  492. }
  493. std::string
  494. UtilityConfig::HelpDescription() {
  495. std::string Desc;
  496. Desc = " -config=snf-config-file Specifies the configuration file\n";
  497. Desc += " -id=licenseid Specifies the license ID\n";
  498. Desc += " -auth=authentication Specifies the Authentication\n";
  499. Desc += " -v Provide verbose output\n";
  500. Desc += " -explain Provide an explaination of the actions\n";
  501. Desc += " without executing any commands\n";
  502. return Desc;
  503. }