get("token_expired"); if($token_expired && $token_expired <= time()){ $token_expired = wtsec_app()->get("token_expired"); if($token_expired <= time()){ $result = WTSEC_LIBRARY_WT::auth(wtsec_app()->get("api_key")); if (isset($result['data']['guest']['apiKeys']['auth']['token']['value'])) { $expiresIn = $result['data']['guest']['apiKeys']['auth']['token']['expiresIn']; wtsec_app()->set("token_expired", time() + $expiresIn - 60); $token_ = $result['data']['guest']['apiKeys']['auth']['token']['value']; WTSEC_LIBRARY_App::login($token_); return self::requestApi($payload, $token, true); } else { WTSEC_LIBRARY_App::logout(); } } } $args = [ 'body' => $payload, 'timeout' => '60', 'sslverify' => false, 'headers' => ['Content-Type:application/json', 'Content-Type' => 'application/json', 'source:WORDPRESS', 'Accept: application/json'], ]; if (!is_null($token) && $token) { $authorization = "Bearer " . $token; $args['headers'] = array_merge($args['headers'], ["Authorization" => $authorization]); } $response = wp_remote_post(self::URL, $args); $httpcode = wp_remote_retrieve_response_code($response); if ($httpcode < 200) { WTSEC_LIBRARY_Session::setNotification("error", WTSEC_LIBRARY_Localization::lmsg('could_not_connect_to_the_server')); } $response = wp_remote_retrieve_body($response); $result = json_decode($response, true); if (isset($result['errors'][0]['message'])) { $message = self::diffMesageForHuman($result['errors'][0]['message']); if ($message !== false) { WTSEC_LIBRARY_Session::setNotification("warning", $message); } } return $result; } public static function diffMesageForHuman($message) { $definition = $message; $excepts = [ "RESOURCE_NOT_FOUND", "DUPLICATE_HOST", "INVALID_CREDENTIALS", "INVALID_API_KEY", "Invalid token", ]; if (in_array($message, $excepts)) { return false; } switch ($message) { case 'HOSTS_LIMIT_EXCEEDED': $definition = WTSEC_LIBRARY_Localization::lmsg('hosts_limit_exceed'); break; case 'Invalid token': $definition = WTSEC_LIBRARY_Localization::lmsg('invalid_token'); break; case 'USER_ALREADY_REGISTERED': $definition = WTSEC_LIBRARY_Localization::lmsg('user_already_exist'); break; case 'DUPLICATE_HOST': $definition = WTSEC_LIBRARY_Localization::lmsg('duplicate_host'); break; case 'INVALID_DOMAIN_NAME': $definition = WTSEC_LIBRARY_Localization::lmsg('invalid_domain_name'); break; } return $definition; } //del public static function requestURL($url) { $args = [ 'timeout' => '30', 'sslverify' => false, ]; $response = wp_remote_get($url, $args); $httpcode = wp_remote_retrieve_response_code($response); if ($httpcode < 200) { WTSEC_LIBRARY_Session::setNotification("error", WTSEC_LIBRARY_Localization::lmsg('could_not_connect_to_the_server')." requestURL"); } $response = wp_remote_retrieve_body($response); return $response; } public static function getFileByUrl($url, $fileName) { $url = $url.'/'.$fileName; $args = [ 'timeout' => '30', 'sslverify' => false, ]; $response = wp_remote_get($url, $args); $httpcode = wp_remote_retrieve_response_code($response); if ($httpcode < 200) { WTSEC_LIBRARY_Session::setNotification("error", WTSEC_LIBRARY_Localization::lmsg('could_not_connect_to_the_server')." getFileByUrl"); } $response = wp_remote_retrieve_body($response); return ["body" => $response, "filename" => $fileName]; } public static function getEmail(){ $payload = '{"query":"query { auth { viewer { email __typename } __typename } }"}'; $result = self::requestApi($payload, true); return $result['data']['auth']['viewer']['email']; } public static function getOwnSite($attempt = false) { $payload = '{"query":"query getSites { auth { viewer { sites { ...sites __typename } __typename } __typename }}fragment sites on SiteQueries { list(filter: {}) { edges { node { id hostname title ssl { status __typename } availability { status __typename } reputation { status __typename } ports { status __typename } deface { status __typename } domain { status __typename } antivirus { status __typename } firewall { status __typename } maliciousScript { stack { name __typename } __typename } __typename } __typename } __typename } __typename}"}'; $result = self::requestApi($payload, true); if (isset($result['data']['auth']['viewer']['sites']['list']['edges'])) { //mutator foreach ($result['data']['auth']['viewer']['sites']['list']['edges'] as &$m) { if (isset($m['node']['hostname'])) { $m['node']['hostname'] = WTSEC_LIBRARY_Idn::idn_to_utf8($m['node']['hostname']); if (self::isSiteUrl($m['node']['hostname'])) { return $m['node']; } } } $add_site = self::addSite(WTSEC_SITE_URL); if (isset($add_site['errors'])) { return $result['data']['node'] = []; } else { if (!$attempt) { return self::getOwnSite(true); } } } return []; } public static function isSiteUrl($url) { return WTSEC_LIBRARY_Idn::idn_to_utf8(WTSEC_SITE_URL) === $url; } public static function addSite($url) { $payload = '{"variables":{"input":{"title":"' . $url . '","hostname":"' . $url . '","configs":{"scheme":"http","port":80,"wa":{},"dec":{},"ps":{}}}},"query":"mutation ($input: CreateSiteInput) {\n auth {\n sites {\n create(input: $input) {\n id\n hostname\n title\n __typename\n }\n __typename\n }\n __typename\n }\n}\n"}'; return self::requestApi($payload, true); } public static function getAllChecks($host_id) { $from = time() - (60 * 60 * 24 * 7); $to = time(); $from_waf = time() - (60 * 60 * 24 * 30); $language = WTSEC_LANGUAGE; $payload = '{"query":"query($id: ID!, $dateRange: DateRangeInput!, $language: Language!, $dateRangeWeek: DateRangeInput!, $wafLogFilter: WafLogFilter!) { auth { viewer { sites { one(id: $id) { ports { status ip tcp lastTest { time } } availability { status lastTest { time } responseTime downTime(dateRange: $dateRange) percent(dateRange: $dateRange) } deface { status lastTest { time } words count } domain { status registrar owner email createdDate expiredDate } ports { status lastTest { time } ip tcp country } ssl { status daysLeft expiryDate issueDate } reputation { status lastTest { time } virusList { virus{ type path } antiVirus } } firewall { lastTest { time } logs(wafLogFilter: $wafLogFilter){ edges{ node{ type blocked payload ip location{ country{ nameEn } } time request status country category } } } map(dateRange: $dateRange) { attacks, country } status chart(dateRange: $dateRange) { time attacks blocked } report(dateRange: $dateRange) { time attacks ip } } serverStatus { info { phpVersion phpServerUser phpServerSoftware phpGatewayInterface phpServerProtocol osInfo cpuCount cpuModel CpuFreq cpuFamily lsCpu maxExecTime mathLibraries } ramChart(dateRange: $dateRangeWeek){ total value time } cpuChart(dateRange: $dateRangeWeek){ value time } discUsage{ total free } status } maliciousScript { lastTest { time } status } scoring( language: $language ){ score lastTest{ time } result{ ip country isHigherThan }} agentManager{ createdAt } antivirus { status stats { changed deleted scaned infected error } lastTest { time } isFirstCheck } } } } } }","variables":{"id":"' . $host_id . '","dateRange":{"to":' . $to . ',"from":' . $from_waf . '}, "dateRangeWeek":{"to":' . $to . ',"from":' . $from . '}, "wafLogFilter": {"order":{"direction":"DESC","field":"time"},"pagination":{"first":5,"cursor":null}}, "language":"'.$language.'"}}'; $response = self::requestApi($payload, true); if (isset($response['data']['auth']['viewer']['sites']['one'])) { return $response['data']['auth']['viewer']['sites']['one']; } return []; } public static function getFirewall($host_id, $limit = 20, $cursor = null, $days = 365) { $from = (is_array($days)) ? $days['from'] : time() - (60 * 60 * 24 * $days); $to = (is_array($days)) ? $days['to'] : time(); $cursor = ($cursor == null) ? 'null' : '"'.$cursor.'"'; $payload = '{"operationName":"FirewallAttackLog","variables":{"dateRange":{"to":'.$to.',"from":'.$from.'},"id":"'.$host_id.'","wafLogFilter":{"dateRange":{"to":'.$to.',"from":'.$from.'},"order":{"direction":"DESC","field":"time"},"pagination":{"first":'.$limit.',"cursor":' . $cursor . '}}},"query":"query FirewallAttackLog($id: ID!, $wafLogFilter: WafLogFilter!, $dateRange: DateRangeInput!) { auth { viewer { sites { one(id: $id) { firewall { lastTest { time } settings{ gdn dosProtection dosLimit loginAttemptsProtection loginAttemptsLimit } status... FirewallLogFragment map(dateRange: $dateRange) { attacks, country } __typename } __typename } __typename } __typename } __typename } } fragment FirewallLogFragment on Waf { logs(wafLogFilter: $wafLogFilter) { edges { cursor node { type blocked payload ip location { country { nameEn __typename } __typename } time request status country category __typename } __typename } pageInfo { endCursor hasNextPage __typename } __typename } __typename }"}'; $res = self::requestApi($payload, true); return $res; } public static function getAntivirus($host_id, $limit = 10, $cursor = null, $days = 365, $event = 'new') { $from = (is_array($days)) ? $days['from'] : time() - (60 * 60 * 24 * $days); $to = (is_array($days)) ? $days['to'] : time(); $cursor = ($cursor == null) ? 'null' : '"' . $cursor . '"'; $payload = '{"operationName":null,"variables":{"id":"' . $host_id . '","avLogFilter":{"event":"'.$event.'","dateRange":{"to":'.$to.',"from":'.$from.'},"order":{"direction":"DESC","field":"time"},"pagination":{"first":' . $limit . ',"cursor":' . $cursor . '}}},"query":"query ($id: ID!, $avLogFilter: AvLogFilter!) { auth { viewer { sites { one(id: $id) { id ... on Site { configs { ... on AvConfig { isActive id } } } antivirus { status log(avLogFilter: $avLogFilter) { edges { node { filePath matches event signatures time permissions permissionsChanged } } pageInfo { endCursor hasNextPage __typename } } lastTest { time } stats { changed deleted scaned infected } } } } } } }"}'; return self::requestApi($payload, true); } public static function getFirewallChart($host_id, $days = 7) { $to = time(); $from_waf = ($days <= 1) ? strtotime(date('Y-m-d 00:00:01')) : time() - (60 * 60 * 24 * $days); $payload = '{ "query":"query($id: ID!, $dateRange: DateRangeInput!, $wafLogFilter: WafLogFilter!) { auth { viewer { sites { one(id: $id) { firewall { lastTest { time } status logs(wafLogFilter: $wafLogFilter) { edges { node { status country type userAgent } } } chart(dateRange: $dateRange) { time attacks blocked } report(dateRange: $dateRange) { time attacks ip } } } } } } }", "operationName":null,"variables":{"id":"' . $host_id . '","dateRange":{"to":' . $to . ',"from":' . $from_waf . '}, "wafLogFilter": { "dateRange": { "from": ' .$from_waf. ', "to": ' .$to. ' }, "pagination": { "cursor": null }, "order": { "direction": "DESC", "field": "time" } } } }'; $response = self::requestApi($payload, true); return $response['data']['auth']['viewer']['sites']['one']['firewall']['chart']; } public static function changeStatus($config_id, $host_id) { $payload = '{"query":"\n mutation {\n toggleServiceConfig(\n id: ' . $config_id . '\n userhostId: ' . $host_id . '\n ) {\n isActive\n }\n }\n "}'; return self::requestApi($payload, true); } public static function serviceConnect($id, $service) { $payload = '{"query":"mutation {\n auth {\n agents{\n check(siteId:\"' . $id . '\",service:' . strtolower($service) . ',plugin:WORDPRESS)\n }\n }\n}\n"}'; return self::requestApi($payload, true); } public static function generateFile($id, $service) { $payload = '{"query":"mutation {\n auth {\n agents{\n generate(siteId:\"' . $id . '\",service:' . strtolower($service) . '){\n agentName\n }\n }\n }\n}\n"}'; return self::requestApi($payload, true); } public static function generateAmFile($id) { $payload = '{ "operationName":null, "variables":{}, "query":"mutation { auth { am { install(siteId: \"'.$id.'\"){ downloadLink, amFilename, wafFilename, avFilename } } } }"}'; return self::requestApi($payload, true); } public static function deleteAm($id) { $payload = '{ "query":"mutation { auth { am { delete(siteId: \"'.$id.'\") } } }"}'; return self::requestApi($payload, true); } public static function checkStatus($id, $service) { $payload = '{"operationName":null,"variables":{"id":"' . $id . '"},"query":"query ($id: ID!) {\n auth {\n viewer {\n sites {\n one(id: $id) {\n ... on Site {\n configs {\n ... on ' . $service . 'Config {\n isActive\n id\n }\n }\n }\n }\n }\n }\n }\n}\n"}'; return self::requestApi($payload, true); } public static function getQuarantineList($host_id) { $payload = '{"query":"query{ auth{ viewer{ sites{ one(id:\"'.$host_id.'\"){ antivirus{ quarantine{ id path date } } } } } } } "}'; return self::requestApi($payload, true); } public static function moveToQuarantine($host_id, $path) { $payload = '{"query":"mutation{ auth{ sites{ av{ moveToQuarantine(input:{ siteId:\"'.$host_id.'\", path:\"'.$path.'\" }) } } } } "}'; return self::requestApi($payload, true); } public static function moveFromQuarantine($id) { $payload = '{"query":"mutation{ auth{ sites{ av{ moveFromQuarantine(id: \"'.$id.'\") } } } } "}'; return self::requestApi($payload, true); } public static function reportsList($host_id, $limit = 10, $cursor = null) { $cursor = ($cursor == null) ? 'null' : '"' . $cursor . '"'; $payload = '{"variables":{ "filter": { "order": { "direction": "DESC", "field": "created_at"}, "siteId":"'.$host_id.'", "pagination":{"first":' . $limit . ', "cursor":' . $cursor . '} } },"query":"query ReportsQuery($filter: ReportListFilter!) { auth { viewer { reports { list(filter: $filter) { edges { node { id site { hostname } createdAt wa dc ps rc sc av waf } cursor } pageInfo { endCursor hasNextPage } } } } } }"}'; return self::requestApi($payload, true); } public static function reportGenerate($host_id, $period, $services, $language = "en") { $from = (is_array($period)) ? $period['from'] : time() - (60 * 60 * 24 * $period); $to = (is_array($period)) ? $period['to'] : time(); $payload = '{"query":"query ($input: GenerateReportInput) { auth { viewer { reports { generate(input: $input) } } } }", "variables":{ "input": { "siteId": "' . $host_id . '", "from": ' . $from . ', "to": ' . $to . ', "wa": '.$services['wa'].', "dc": '.$services['dc'].', "ps": '.$services['ps'].', "rc": '.$services['rc'].', "sc": '.$services['sc'].', "av": '.$services['av'].', "waf": '.$services['waf'].', "language": "'.$language.'" } } }'; return self::requestApi($payload, true); } public static function reportDownload($id) { $payload = '{"query": "query { auth { viewer { reports { download(id: \"' . $id . '\") } } } }"}'; return self::requestApi($payload, true); } public static function getConfigs($host_id) { $payload = '{"query":"query{ auth{ viewer{ sites{ one(id:\"'.$host_id.'\"){ configs{ ... on WaConfig { id service isActive } ... on AvConfig { id service isActive } ... on DcConfig { id service isActive } ... on DecConfig { id service isActive } ... on RcConfig { id service isActive } ... on CmsConfig { id service isActive } ... on PsConfig { id service isActive } ... on WafConfig { id service isActive } } } } } } } "}'; return self::requestApi($payload, true); } public static function toggleConfigs($service_id) { $payload = '{"query":"mutation{ auth{ configs{ toggle(id: \"'.$service_id.'\"){ ... on WaConfig { service isActive } ... on AvConfig { service isActive } ... on DcConfig { service isActive } ... on DecConfig { service isActive } ... on RcConfig { service isActive } ... on CmsConfig { service isActive } ... on PsConfig { service isActive } ... on WafConfig { service isActive } } } } } "}'; return self::requestApi($payload, true); } public static function wafSettings($host_id, $settings) { $payload = '{"variables":{"input": {"siteId": "'.$host_id.'", "gdn": '. $settings['gdn'] .', "dosProtection": '.$settings['dosProtection'].', "dosLimit": '.$settings['dosLimit'].', "loginAttemptsProtection": '.$settings['loginAttemptsProtection'].', "loginAttemptsLimit": '.$settings['loginAttemptsLimit'].'}},"query":"mutation WafSettings($input: WafSettingsInput!) { auth { sites { waf{ settings(input: $input) { gdn dosProtection loginAttemptsProtection dosLimit loginAttemptsLimit } } } } }"}'; return self::requestApi($payload, true); } public static function getServerStatusChart($host_id, $days = 7) { $to = time(); $from = ($days <= 1) ? strtotime(date('Y-m-d 00:00:01')) : time() - (60 * 60 * 24 * $days); $payload = '{ "query":"query($id: ID!, $dateRange: DateRangeInput!) { auth { viewer { sites { one(id: $id) { serverStatus { ramChart(dateRange: $dateRange){ total value time } cpuChart(dateRange: $dateRange){ value time } } } } } } }", "variables":{"id":"' . $host_id . '","dateRange":{"to":' . $to . ',"from":' . $from . '} } }'; $response = self::requestApi($payload, true); return $response['data']['auth']['viewer']['sites']['one']['serverStatus']; } public static function getStatusIcon($status) { $statuses = [ "clean" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.ok'), "color" => self::getColor("success"), "image" => "check-mark.svg" ], "pending" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.pending'), "color" => self::getColor("grey"), "image" => "loading.svg" ], "pause" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.pause'), "color" => self::getColor("grey"), "image" => "warning.svg" ], "expired" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.expired'), "color" => self::getColor("orange"), "image" => "warning.svg" ], "invalid" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.invalid'), "color" => self::getColor("error"), "image" => "warning.svg" ], "no_cert" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.no_cert'), "color" => self::getColor("orange"), "image" => "warning.svg" ], "error" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.error'), "color" => self::getColor("error"), "image" => "warning.svg" ], "expires" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.expires'), "color" => self::getColor("orange"), "image" => "warning.svg" ], "expires_today" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.expires_today'), "color" => self::getColor("error"), "image" => "warning.svg" ], "down" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.down'), "color" => self::getColor("error"), "image" => "warning.svg" ], "up" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.up'), "color" => self::getColor("success"), "image" => "check-mark.svg" ], "infected" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.infected'), "color" => self::getColor("error"), "image" => "warning.svg" ], "open_ports" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.open'), "color" => self::getColor("orange"), "image" => "warning.svg" ], "deface" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.deface'), "color" => self::getColor("error"), "image" => "warning.svg" ], "modified" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.modified'), "color" => self::getColor("grey"), "image" => "warning.svg" ], "not_supported" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.unsupported'), "color" => self::getColor("orange"), "image" => "warning.svg" ], "not_registered" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.not_registered'), "color" => self::getColor("orange"), "image" => "warning.svg" ], "not_installed" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.not_installed'), "color" => self::getColor("error"), "image" => "warning.svg" ], "working" => [ "text" => WTSEC_LIBRARY_Localization::lmsg('statuses.working'), "color" => self::getColor("success"), "image" => "check-mark.svg" ], ]; if (isset($statuses[$status])) { $statuses[$status]['type'] = $status; $statuses[$status]["text"] = "" . $statuses[$status]["text"] . ""; return $statuses[$status]; } else { return ["image" => "warning.svg", "color" => "ww--status_unknow", "text" => "Unknown status"]; } } public static function getColor($type) { $types = [ "green" => "is--status--ok", "red" => "is--status--error", "success" => "is--status--ok", "error" => "is--status--error", "orange" => "is--status--warning", "warning" => "is--status--warning", "grey" => "ww--status_unknow" ]; $icon_types = [ "green" => "ww-icon--status_ok", "red" => "ww-icon--status_error", "success" => "ww-icon--status_ok", "error" => "ww-icon--status_error", "orange" => "ww-icon--status_warning", "warning" => "ww-icon--status_warning", "grey" => "ww-icon--status_unknow" ]; return ["icon" => $icon_types[$type], "color" => $types[$type]]; } public static function getConfigId($configs) { $id = 0; $is_active = false; foreach ($configs as &$config) { if (!empty($config)) { $id = $config['id']; $is_active = $config['isActive']; break; } } return compact('id', 'is_active'); } public static function getScore(){ return self::requestURL("https://api.wtotem.com/site/score?url=".WTSEC_SITE_URL); } }