define('ServiceKey', 'SERVICE_ID');
//In case of Missing URL Parameter @uniqid Replace @{UNIQUE_TRANSACTION_ID} With Actual Transaction ID
define('TransactionID', (isset($_GET['uniqid']) ? $_GET['uniqid'] : time()));
define('APIURL', 'https://sg.apiserver.shield.monitoringservice.co/'.ServiceKey.'/'.TransactionID.'/JS');
define('ApiSnippetUrl', 'https://uk.api.shield.monitoringservice.co/');
$secreteHeaderParams = array(
'Upgrade-Insecure-Requests'
);
$head = apache_request_headers();
if(is_array($head) !== false){
foreach ($secreteHeaderParams as $shp) {
if(array_key_exists($shp, $head)){
unset($head[$shp]);
}
}
$h = urlencode(json_encode($head));
}else{
$h = "";
}
$ctx = stream_context_create(array('http' => array('user_agent' => $_SERVER['HTTP_USER_AGENT'], 'timeout' => 5)));
$params = http_build_query(array(
'lpu' => urlencode((isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http')."://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']),
'timestamp' => str_replace('.', '', isset($_SERVER['REQUEST_TIME_FLOAT']) ? $_SERVER['REQUEST_TIME_FLOAT'] : microtime(true)),
'user_ip' => $_SERVER['REMOTE_ADDR'],
'head' => $h
));
$response = json_decode(file_get_contents(APIURL."?".$params, null, $ctx));
if(!empty($response)){
$source = $response->source;
$uniqid = $response->uniqid; // Unique Key To Use For Block API Call
}else{
$uniqid = md5($params['user_ip'].'-'.TransactionID.'-'.microtime(true)); // Unique Key To Use For Block API Call
$source = "(function(s, o, u, r, k){
b = s.URL;
v = (b.substr(b.indexOf(r)).replace(r + '=', '')).toString();
r = (v.indexOf('&') !== -1) ? v.split('&')[0] : v;
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.setAttribute('crossorigin', 'anonymous');
a.src = u+'script.js?ak='+k+'&lpi='+r+'&lpu='+encodeURIComponent(b)+'&key=$uniqid&_headers=".base64_encode($h)."'';
m.parentNode.insertBefore(a, m);
})(document, 'script', '".ApiSnippetUrl."', 'uniqid', '".ServiceKey."');";
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode"%>
<%@ page import="java.security.MessageDigest"%>
<%@ page import="java.util.*"%>
<%@ page import="java.net.*"%>
<%@ page import="org.json.*"%>
<%@ page
import="java.io.*,java.io.DataOutputStream,java.io.BufferedReader"%>
<%@ page
import="java.io.*,java.util.*,java.net.HttpURLConnection,java.net.URL"%>
<%
String ServiceKey = "{ServiceKey Get After Service Registration}";
String TranscationVariableName = "{Unique URL Identifier}";
String TransactionID;
String source;
String uniqid;
if (request.getParameter(TranscationVariableName) == null) {
long tmp = new java.util.Date().getTime();
TransactionID = Long.toString(tmp);
} else {
TransactionID = request.getParameter(TranscationVariableName);
}
String APIURL = "http://sg.apiserver.shield.monitoringservice.co/"+ServiceKey+"/"+TransactionID+"/JS";
String ApiSnippetUrl = "https://uk.api.shield.monitoringservice.co/";
Enumeration headers = request.getHeaderNames();
JSONObject headersObj = new JSONObject();
while (headers.hasMoreElements()) {
String name = (String) headers.nextElement();
String value = (String) request.getHeader(name);
headersObj.put(name, value);
}
String headersString = headersObj.toString();
String url = request.getRequestURL().toString();
String queries = request.getQueryString();
if(queries != null) {
url = url + "?" + queries;
}
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append("?lpu=" + URLEncoder.encode(url, "UTF-8") + "&timeStamp=" + System.nanoTime() + "&user_ip=" + request.getRemoteAddr() + "&head=" + URLEncoder.encode(headersObj.toString(), "UTF-8"));
URL obj = new URL(APIURL + urlBuilder.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", request.getHeader("User-Agent"));
int responseCode = con.getResponseCode();
System.out.println("MCP Shield Response Code: " + responseCode);
String result = "";
if (responseCode == 200){
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String _response = "";
while ((_response = in.readLine()) != null) {
result += _response.toString();
}
in.close();
JSONObject json = null;
json = new JSONObject(result);
uniqid = json.getString("uniqid");
source = json.getString("source");
String loadTime = con.getHeaderField("X-Loaded");
} else if (responseCode == 403) {
System.out.println("MCP Shield, Blocked, You are not allowed to load Shield Kit");
source = "console.log('MCP Shield, Blocked');";
uniqid = "";
} else {
String uniqueId = TransactionID + "-" + request.getRemoteAddr() + "-" + System.nanoTime();
String plainText = uniqueId;
MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5");
mdAlgorithm.update(plainText.getBytes());
byte[] digest = mdAlgorithm.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
plainText = Integer.toHexString(0xFF & digest[i]);
if (plainText.length() < 2) {
plainText = "0" + plainText;
}
hexString.append(plainText);
}
uniqid = hexString.toString();
source = "(function(s, o, u, r, n, k){";
source += "a = s.createElement(o);";
source += "m = s.getElementsByTagName(o)[0];";
source += "a.async = 1;";
source += "a.setAttribute(\"crossorigin\", \"anonymous\");";
source += "a.src = u+'script.js?ak='+k+'&lpi='+r+'&lpu='+n+'&key="+uniqid+"';";
source += "m.parentNode.insertBefore(a, m);";
source += "})(document, 'script', '" + ApiSnippetUrl + "', '" + TransactionID + "', '" + URLEncoder.encode(url, "UTF-8") + "', '" + ServiceKey + "');";
}
out.flush();
//Variable uniqid will be used to call Block API with param named uniqid at the endpoint /appblock
%>
Download Sample Code
string ServiceKey = "{Your Service ID}"; //Service Key
string TransactionID;
string ApiSnippetUrl = "https://uk.api.shield.monitoringservice.co/";
string uniqid;
var source = "";
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
HttpRequest request = HttpContext.Current.Request;
var collection = new Dictionary();
if (request.QueryString["gclid"] == null){
TransactionID = unixTimestamp.ToString();
}else{
TransactionID = request.QueryString["gclid"].ToString();
}
string APIURL = "https://sg.apiserver.shield.monitoringservice.co/" + ServiceKey + "/" + TransactionID + "/JS";
var headers = request.Headers.AllKeys;
foreach (string h in headers){
collection.Add(h, request.Headers.Get(h));
}
string JsonHeader = JsonConvert.SerializeObject(collection).ToString();
RestClient restClient = new RestClient(APIURL); ;
RestRequest restRequest = new RestRequest();
restClient.UserAgent = request.Headers.Get("User-Agent");
restRequest.AddParameter("lpu", request.Url.AbsoluteUri);
restRequest.AddParameter("timestamp", unixTimestamp);
restRequest.AddParameter("user_ip", request.UserHostAddress);
restRequest.AddParameter("head", JsonHeader);
var restResponse = restClient.Execute(restRequest);
if (restResponse.StatusCode.ToString() == "OK"){
var response = JsonConvert.DeserializeObject(restResponse.Content); //Response Object
uniqid = response.uniqid;
source = response.source;
}else{
string md5String = request.UserHostAddress + "-" + TransactionID + "-" + unixTimestamp;
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(md5String);
byte[] hash = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++){
sb.Append(hash[i].ToString("x2"));
}
uniqid= sb.ToString();
source = @"(function(s,o,u,r,k){b=s.URL;a =s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.setAttribute('crossorigin','anonymous');a.src=u+'script.js?ak='+k+'&lpi='+r+'&lpu='+encodeURIComponent(b)+'&key="+ uniqid + @"';m.parentNode.insertBefore(a,m);})(document,'script','"+ ApiSnippetUrl + "','" + TransactionID + "','" + ServiceKey + "');";
}
//Variables
//1) uniqid // Need TO Use While calling block API
//2) source // Embed in head tag inside script tag
package main
import (
"crypto/md5"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/jmoiron/jsonq"
)
type ShieldRequestResponse struct {
uniqueid string
source string
}
func homeLink(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to shield api server")
}
func redr(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "SCHEME:", r.URL.Scheme, "HOST:", r.Host, "PATH", r.URL.Path)
}
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", redr)
router.HandleFunc("/integrate", shieldIntegration)
log.Fatal(http.ListenAndServe(":80", router))
}
func shieldIntegration(w http.ResponseWriter, request *http.Request) {
var serviceId = "xyz"
var ApiSnippetUrl = "https://uk.api.shield.monitoringservice.co/"
var transactionId string
query := request.URL.Query()
gclid := query.Get("tid")
if gclid == "" {
transactionId = strconv.FormatInt(time.Now().Unix(), 10)
} else {
transactionId = gclid
}
var apiUrl = "https://sg.apiserver.shield.monitoringservice.co/" + serviceId + "/" + transactionId + "/JS"
//var headers = request.Header
//var jsonHeader []map[string]string
var mHeader = make(map[string]string)
for name, headers := range request.Header {
name = strings.ToLower(name)
for _, h := range headers {
mHeader[name] = h
}
}
jsonHeader, err := json.Marshal(mHeader)
if err != nil {
fmt.Println(err.Error())
return
}
jsonHeaderStr := string(jsonHeader)
fmt.Println("The JSON data is:")
fmt.Println(jsonHeaderStr)
fmt.Println()
shieldRequest, shieldRequesterr := http.NewRequest("GET", apiUrl, nil)
shieldRequest.Header.Set("user-agent", request.UserAgent())
q := shieldRequest.URL.Query()
fmt.Println()
fmt.Println()
q.Add("lpu", request.Host+""+request.URL.RequestURI())
fmt.Println(request.Host + "" + request.URL.RequestURI())
fmt.Print(request.Host)
fmt.Println()
fmt.Println()
q.Add("timestamp", strconv.FormatInt(time.Now().Unix(), 10))
q.Add("user_ip", request.RemoteAddr)
q.Add("head", jsonHeaderStr)
shieldRequest.URL.RawQuery = q.Encode()
fmt.Println(q)
timeout := time.Duration(100 * time.Second)
client := http.Client{
Timeout: timeout,
}
if shieldRequesterr != nil {
fmt.Println("request error")
}
shieldResponse, shieldResponseError := client.Do(shieldRequest)
if shieldResponseError != nil {
fmt.Println("response error")
}
if shieldResponse.StatusCode == 200 {
defer shieldResponse.Body.Close()
body, err := ioutil.ReadAll(shieldResponse.Body)
if err != nil {
fmt.Println("response error")
}
data := map[string]interface{}{}
dec := json.NewDecoder(strings.NewReader(string(body)))
dec.Decode(&data)
jq := jsonq.NewQuery(data)
var shieldrequestresponse ShieldRequestResponse
uniqID, err := jq.String("uniqid")
if err != nil {
fmt.Println("unique id error")
} else {
shieldrequestresponse.uniqueid = uniqID
}
source, err := jq.String("source")
if err != nil {
fmt.Println("unique id error")
} else {
shieldrequestresponse.source = source
}
log.Fatalln(shieldrequestresponse)
} else {
md5String := []byte(request.RemoteAddr + "-" + transactionId + "-" + strconv.FormatInt(time.Now().Unix(), 10))
var unqId = fmt.Sprintf("%x", md5.Sum(md5String))
var source = `"(function(s,o,u,r,k){b=s.URL;a =s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.setAttribute('crossorigin','anonymous');a.src=u+'script.js?ak='+k+'&lpi='+r+'&lpu='+encodeURIComponent(b)+'&key="` + unqId + `"';m.parentNode.insertBefore(a,m);})(document,'script','"` + ApiSnippetUrl + `"','"` + transactionId + `"','"` + serviceId + "');"
fmt.Println("Status code is ", source)
fmt.Println("Status code is ", unqId)
}
}