Figer's Technology Consulting |

9 Simple Steps to debug Android Chrome from desktop Chrome Dev Tools

From your Android Device:


1.) go into settings, then about this device, tap on build 7 times


2.) go into new developer settings, enable USB debugging


3.) connect to your laptop with USB


4.) open Desktop Chrome browser


5.) enter chrome://inspect/#devices in the URL


6.) check discover USB devices


7.) navigate to the page to debug on Android


8.) once on the page in Android click Inspect in Desktop Chrome browser for that Android page.


9.)Now you are in your default Chrome Desktop Dev tools, happy coding!!!

Checklist to secure Jquery / Ajax / JSON to WEBAPI Web Service or similar endpoints

Security is a goal that spans every tier and layer. To ensure a comprehensive security solution, best practices must span these tiers and layers as well. This section contains a summary of best practices that should be applied to the Web tier. They are categorized loosely by layer. Not all of them pertain specifically to the patterns outlined in this chapter, but they do pertain to securing the Web tier and therefore should be used in conjunction with the Web tier security patterns.


It is important to remember that deficiencies in one layer may invalidate all the other efforts in the other layers. An attacker only needs one hole to compromise the application. You can harden the operating system, construct a DMZ, use SSL, and audit every transaction, but if an attacker can guess an administrator’s passwords, these efforts were in vain. Take care to review all of the following best practices to ensure a cohesive security approach.


<strong>Infrastructure</strong>


Put Web Servers in a DMZ. Secure the Internet-facing Web server host in a DMZ (Demilitarized Zone) using an exterior firewall. It is always a recommended option to use DMZ bastion hosts or switched connections to target Web servers. This will prevent attackers who have compromised the Web server from penetrating deeper into the application.


Use Stateful Firewalls. Use a stateful firewall inspection to keep track of all Web-tier transmissions and protocol sessions. Make sure it blocks all unrequested protocol transmissions.


Drop Non-HTTP Packets. Make sure your firewall is configured to drop connections except for HTTP and HTTP over SSL. This will help prevent Denial of Service (DoS) attacks and disallow malicious packets intended for back-end systems.


Minimize and Harden the Web Server Operating System. Make sure the operating system that is running the Web and application server is hardened and does not run any unsolicited services that may provide an opening for an attacker to compromise.


Secure Administrative Communications. Make sure all administration tasks on the server are done using encrypted communication. Disable remote administration of Web and application servers using system-level and root administrator access. All remote administration needs to be carried out using secure-shell connections from trusted machines and disallow administrator access from untrusted machines.


Disallow Untrusted Services. Disable telnet, remote login services, and FTP connections to the server machines. These are commonly attacked services and represent a strong security risk.


Check Web Server User Permissions. Make sure the running Web and application servers’ configurations and their user privileges have no rights to access or to modify system files.


Disable CGI. Unless required, disable running CGI applications in the Web server or application server and accessing /cgi-bin directories. This is another common source of attacks.


Enforce Strong Passwords. Change all default passwords and use robust password mechanisms to avoid password-related vulnerabilities such as sniffing and replay attacks. For all application-level administrators, use password ageing, account locking, and password-complexity verification. Using one-time password mechanisms, dynamic passwords that use challenge-response schemes, smart card- and certificate-based authentication, and multifactor authentication are reliable practices.


Audit Administration Operations. Limit all Web administration access to the system to very few users. Monitor their account validity, log all their administration operations using encryption mechanisms, and make sure that system log files are written to a different machine that is secure from the rest of the network.


Check Third-Party IPs. All third-party supporting applications that are required to coexist with the Web and application servers have to be tested for their usage of IP and port addresses. Those applications must follow the maintained rules of the DMZ.


Monitor Web Server Communications. Monitor all transmissions and Web-server requests and responses for suspicious activity and misuse. Use watchdog macros or daemons to monitor and trap these activities. When detection of such abuses occurs, make sure you check the integrity of the application afterward and notify the system security administrator.


Setup IDS. Use intrusion detection systems to detect suspicious acts, abuses, and unsolicited system uses. Alert security administrators for such activities.


Deny Outbound Traffic to Web Server. Disallow all application requests to the IP addresses of the Web servers running in the DMZ.


Distrust Servers in the DMZ. Do not store any user or application-generated information in the DMZ. Store all sensitive information behind the DMZ interior firewall with the expectation that servers running in the DMZ will eventually be compromised. The exception would be a Honeypot, which is a server created specifically to lure attackers into what appears to be the real application. Their activities are then logged and analyzed to help stave off future attacks.


<strong>Communication</strong>


Secure the Pipe. For all security-sensitive Web applications and Web-based online transactions, make sure the session and data exchanged between the server and client remain confidential and tamper-proof during transit. SSL/TLS is the de facto technology for securing communication on the wire. It allows Web-based applications to communicate over a secure communication channel. Using SSL communication with digital certificates offers confidentiality and integrity of data transmitted between the Web applications and client authentication.


Segregate by Sensitivity. Make sure that Web applications that contain sensitive information and Web applications that do not contain sensitive information run on different machines and different Web-server instances.


Enforce Strong Encryption. For applications that use classified or financial data, make sure that the Web server does not accept weak encryption. Disable or delete weak encryption cipher suites from the Web server and enforce adequate key lengths.


Don’t Flip Back to HTTP from HTTPS. After switching to SSL communication, make sure the application no longer accepts non-SSL requests until logging out from the SSL session. In the event that the client is sending a non-SSL request, the application must enforce reauthentication of that user over a new SSL session and then stop listening to non-SSL requests. Verifying SSL requests can be implemented using various Connection filter mechanisms.


Capture Bad Requests. Log and monitor all fake SSL and non-SSL requests using filters. For all such unsolicited requests, redirect the user to an authentication page to provide valid login credentials.


Use Certificates for Server-to-Server Communications. To support server-to-server or nonbrowser-based client communications that host secure transactions, always suggest using mutual or client certificate-based authentication over SSL. In this case, the server will authenticate the client using the client’s X.509 certificate, a public-key certificate that conforms to a standard that is defined by X.509 Public Key Infrastructure (PKI). This provides a more reliable form of authentication than standard password-based approaches.


Check Mutual Authentication. Verify that mutual authentication is configured and running properly by examining debug messages. To generate debug messages from SSL mutual authentication, pass the system property javax.net.debug=ssl,handshake to the application, which will provide information on whether or not mutual authentication is working.


Check Certification Expiration. While authenticating a client using mutual authentication, be sure to check for certificate expiration or revocation.


User SSL Accelerators. Using hardware-based SSL accelerators enhances secure communication performance because it offloads the cryptographic processing load from the Web server.


Use SGC When Possible. Consider using Server Gated Cryptography (SGC) mechanisms when possible to ensure the highest level of security for Web applications regardless of browser clients or versions.


Check Export Policies. Before installing SSL server certificates, make sure that you understand and are in accordance with your country’s export policies regarding encryption products containing cryptographic technology. Some countries and organizations may ban or require special licenses for using encryption technologies.


<strong>Application</strong>


Disallow Direct Access. Make sure that the application resides on a server accessed via reverse-proxy or Network Address Translation (NAT)-based IP addresses. Then rewrite the URLs of Web applications. This protects the application from direct access from unsolicited users.


Encrypt Application-Specific Properties. Make sure that all application-specific properties stored on local disks that are exposed to physical access are encrypted or digested using encryption or secure hash mechanisms. Decrypt these entries and verify them before use in the application. This will protect unauthorized access or modification of application-specific parameters.


Restrict Application Administrator Privileges. Do not create an application administrator user account (that is, admin or root) with explicit administration access and privileges. If someone steals the administrator’s password and abuses the application with malicious motives, it is hard to find out who really abused the application. Use the security Principal of the user and assign role-based access by assigning users to the administrator role. This helps in identifying the tasks carried out by the associated Principal with an administrator role.


Validate Request Data. Verify and validate all user requests and responses and inbound and outbound data exchanged with the application. Apply constraints and verify the input data so that the data does not cause any undesirable side effects on the application.


Validate Form Fields. Ensure that any alteration, insertion, and removal of HTML form fields by the originating browser are detected, logged, and result in an error message.


Use HTTP POST. Use HTTP POST rather than HTTP GET and avoid using HTTP GET requests while generating HTML forms. HTTP GET requests reveal URL-appended information, allowing sensitive information to be revealed in the URL string.


Track Sessions. Identify the originating user and the host destination making the application request in the sessionid. Verify that all subsequent requests are received from that same user’s host origin until the user logs out. This protects application sessions from hijacking and spoofing.


Obfuscate Code. Obfuscate all application-related classes to avoid code misuse. This protects the code from being easily reverse engineered. This should be done for stand-alone Java clients, helper classes, precompiled JSPs, and application JAR files.


Audit All Relevant Security Tasks. Securely log, audit, and timestamp all relevant application-level events. Audit events should include login attempts and failures, logouts, disconnects, timeouts, administration tasks, user requests and responses, exceptions, database connections, and so forth. Redirect the log data to a file or database repository residing in another machine. Logging and auditing help to track and identify users with malicious intentions.


Audit All Relevant Business Tasks. Create audit trails for all identified user-level sessions and actions with timestamps and store them in a different log file with unique line identifiers. This helps in achieving non-repudiation in both business and technical aspects of the application.


Destroy HTTP Sessions on Logout. Once a user logs out or exits a security-sensitive application resource, invalidate the HTTP Session and remove all state within the session. Leaving stale sessions on the server often leads to security breaches involving session hijacking, client-side Trojan horses, and eavesdropping on subsequent sessions.


Set Session Timeouts. Use HTTP session timeouts for all user sessions after a period of inactivity. Redirect the user back to the login page for re-authentication to enable the stored HTTP session state.

Issue connecting to Amazon AWS MS SQL server instance remotely

add an exception to the server's Windows Firewall for TCP 1433 (or whatever port you use)


enable TCP as a client connection protocol for the SQL Server instance by opening up "SQL server configuration manager"


open management studio, right click on the instance, click properties, then click connections along the left side, check allow remote connections)


Change Server Authentication to SQL Server and Windows Authentication. By default, SQL Server 2008 Express allows only Windows Authentication mode so you can connect to the SQL Server with current user log-on credential. If you want to specify user for connect to the SQL Server, you have to change Server Authentication to SQL Server and Windows Authentication.


My issue was something was already running on port 1433, so I changed to port 1435 in "SQL server configuration manager" under "SQL server network configuration", then protocols for my instance, right click on TCP/IP, then go all the way to the bottom on under allIP change the bottom value, leave dynamic blank.


How you connect to SQL on a different port from with-in management studio:

ip,port (127.0.0.1,6283 -add a comma between the ip and port, no spaces)


How I discovered what was using which port

netstat - na for list of all open ports

netstat -ano for a list of all open ports with their process ID, then open task manager to see what process is on that port

Amazon Web Services - EC2 - Upgrade RAM on a windows instance

Stop the instance, modify the instance type from T1.mcro or whatever it's currently set as to something with more RAM, then bring the instance back up.

Symetrical Triple DES encryption in Java and decryption in VB.NET

Java Code
---------------



package JavaTripleDES;



import java.security.spec.KeySpec;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESedeKeySpec;



import org.apache.commons.codec.binary.Base64; <strong>//This needs to be downloaded and added to eclipse as an external library</strong>





public class DESEncryption {



private static final String UNICODE_FORMAT = "UTF8";

public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";

private final KeySpec myKeySpec;

private final SecretKeyFactory mySecretKeyFactory;

private final Cipher cipher;

private final byte[] keyAsBytes;

private final String myEncryptionKey;

private final String myEncryptionScheme;

private final SecretKey key;



public DESEncryption() throws Exception {

myEncryptionKey = "hisIsSecretEncryptionKey";

myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;

keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);

myKeySpec = new DESedeKeySpec(keyAsBytes);

mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);

cipher = Cipher.getInstance(myEncryptionScheme);

key = mySecretKeyFactory.generateSecret(myKeySpec);

}



/**

* Method To Encrypt The String

*/

public String encrypt(String unencryptedString) {

String encryptedString = null;

try {

cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);

byte[] encryptedText = cipher.doFinal(plainText);

encryptedString = new String(Base64.encodeBase64(encryptedText));

} catch (Exception e) {

e.printStackTrace();

}

return encryptedString;

}



/**

* Method To Decrypt An Encrypted String

*/

public String decrypt(String encryptedString) {

String decryptedText = null;

try {

cipher.init(Cipher.DECRYPT_MODE, key);

byte[] encryptedText = Base64.decodeBase64(encryptedString);

byte[] plainText = cipher.doFinal(encryptedText);

decryptedText = bytes2String(plainText);

} catch (Exception e) {

e.printStackTrace();

}

return decryptedText;

}



/**

* Returns String From An Array Of Bytes

*/

private static String bytes2String(byte[] bytes) {

StringBuilder stringBuffer = new StringBuilder();

for (int i = 0; i &lt; bytes.length; i++) {

stringBuffer.append((char) bytes[i]);

}

return stringBuffer.toString();

}



/**

* Testing the DES Encryption And Decryption Technique

*/

public static void main(String args[]) throws Exception {

DESEncryption myEncryptor = new DESEncryption();



String stringToEncrypt = "12345678&amp;First&amp;Last&amp;M&amp;Lake%20Park";

String encrypted = myEncryptor.encrypt(stringToEncrypt);

String decrypted = myEncryptor.decrypt(encrypted);



System.out.println("String To Encrypt: " + stringToEncrypt);

System.out.println("Encrypted Value  : " + encrypted);

System.out.println("Decrypted Value  : " + decrypted);

}

}

-------------------

VB.NET Code
--------------------

Imports System.IO

Imports System.Text

Imports System.Security.Cryptography



Public Class Form1



Private Shared ReadOnly encryptionKey As String = "ThisIsSecretEncryptionKe" <strong>//Key Length matters which is why the trailing 'y' is missing</strong>

Public Sub New()

InitializeComponent() //This is added automatically

Dim strTestValueFromJava As String = "6JtWysSeMxc1L6I0wRJi9EOakFWfOo/+uM8K0PnwhEAYenfxZ1Yw9w=="

Dim dencryptedData As String = Decrypt(strShouldBe, False)

End Sub



Public Shared Function Decrypt(cipherString As String, useHashing As Boolean) As String

Dim keyArray As Byte()

Dim toEncryptArray As Byte() = Convert.FromBase64String(cipherString.Replace(" "c, "+"c))



If useHashing Then

' If hashing was used get the hash code with regards to your key

Dim hashmd5 As New MD5CryptoServiceProvider()

keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(encryptionKey))

hashmd5.Clear()

Else

' If hashing was not implemented get the byte code of the key

keyArray = UTF8Encoding.UTF8.GetBytes(encryptionKey)

End If



' Set the secret key for the tripleDES algorithm

Dim tdes As New TripleDESCryptoServiceProvider()

tdes.Key = keyArray

tdes.Mode = CipherMode.ECB

tdes.Padding = PaddingMode.PKCS7



Dim cTransform As ICryptoTransform = tdes.CreateDecryptor()

Dim resultArray As Byte() = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length)

tdes.Clear()



' Return the Clear decrypted TEXT

Return UTF8Encoding.UTF8.GetString(resultArray)

End Function

End Class

C# Web API Forms Authentication using JQuery Ajax calls from HTML5 app

------------------

Enable Forms Authentication

-------------------

add to web.config

<system.web>

<authentication mode="Forms" />


LogonModel.cs

--------------

namespace DeliveryApp.Models

{

using System;

using System.Collections.Generic;


public class LogOnModel

{

public string Username { get; set; }

public string Password { get; set; }

}

}


AccountController.cs

--------------------

using System.Web.Http;

using System.Web.Security;

using DeliveryApp.Models;

using System.Web;

using System.Security.Principal;

using System.Web.Helpers;


namespace DeliveryApp.Controllers

{

public class AccountController : ApiController

{

public bool Post(LogOnModel UserAccount)

{

if (UserAccount != null)

{

//Change this to hit the SQL server to get the accounts and validate

if (UserAccount.Username == "test" && UserAccount.Password == "test12")

{

FormsAuthentication.SetAuthCookie(UserAccount.Username, false);

return true;

}

}


return false;

}

}

}


Javascript ajax function to login - once logged in, it creates cookie that all other ajax calls auto send with the request.

<strong>Must be over SSL to be secure</strong>

---------------------------------


function login() {


var user = $('#user').val();

var pass = $('#pass').val();


$.ajax({

type: 'Post',

url: webapiURL + '/Api/Account',

data: { Username: user, Password: pass },

dataType: 'json',

success: function(data) {


//Login Success

window.location = "index.html";

},

error: function(msg) {

alert("Error Logging in - " + msg.responsetext);

}

});

}


Finally place  [Authorize] directly above every web api controller function except for the Login one. This will restrict access unless the user has authenticated.

CSS rounded image corners

Simple CSS styling to add to any image to add rounded corners


style="border: 2px solid black;border-radius: 30px;-moz-border-radius: 30px;-khtml-border-radius: 30px;-webkit-border-radius: 30px;"

C# eventhandler passing variables from Usercontrol to parent page

In this example I'm passing a telerik radgrid collection to the parent page from the child usercontrol when the user selects a row.


-----------------------------

User Controls (.ascx)

-----------------------------


public partial class NPISearch : System.Web.UI.UserControl 

//This is just the standard class section when a user control is created</em>


{

<strong>public delegate void ReturnNPISearchEvent (Telerik.Web.UI.GridDataItemCollection e); //You need to add this line</strong>


Page_Load() { 

//Standard Page_load event

protected void grdNPI_SelectedIndexChanged(object sender, EventArgs e) 

//Here is the function that raises the event to the parent page

{

//Null check makes sure the main page is attached to the event

if (this.ReturnNPISearch != null)

this.ReturnNPISearch(grdNPI.MasterTableView.Items);

}


}


-----------------------------------

Parent page (.aspx)

---------------------------------


protected void Page_Load(object sender, EventArgs e) //Add the line below in Page_Load()

{

NPISearch1.ReturnNPISearch += new      MCRASunshine.Account.NPISearch.ReturnNPISearchEvent(MyEventHandlerFunction_ReturnNPISearch);

}


//This is the function that is called when the usercontrol event is fired

public void MyEventHandlerFunction_ReturnNPISearch(Telerik.Web.UI.GridDataItemCollection e)


{

this.divSearch.Visible = false;

this.divAddInfo.Visible = true;

txtInfoNPI.Enabled = false;


//set values in textboxes

foreach (Telerik.Web.UI.GridDataItem dataItem in e)

{

if (dataItem.Selected == true)

{

this.txtInfoFirstName.Text = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(dataItem.Cells[4].Text.ToLower().Trim('"'));

this.txtInfoLastName.Text = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(dataItem.Cells[3].Text.ToLower().Trim('"'));

this.txtInfoNPI.Text = dataItem.Cells[5].Text.Trim('"');

jQuery dynamically set html select dropdownlist item

This was not obvious at all to me, but you have to invoke the select elements .Change() event to see the selected item actually reflected on the page, seems foolish, but the code is simple:


$("#SelectItem").val("SetThisValue");

$('#SelectItem').change();

Enable Access-Control-Allow-Origin in IIS6 &amp; IIS7 for webapi calls

To allow your newly created webapi web service calls to be accessed from ajax post calls from another website you need to enable this setting in either IIS6 or IIS7 IIS6
  1. Open Internet Information Service (IIS) Manager
  2. Right click the site you want to enable CORS for and go to Properties
  3. Change to the HTTP Headers tab
  4. In the Custom HTTP headers section, click Add
  5. Enter Access-Control-Allow-Origin as the header name
  6. Enter * as the header value
  7. Click Ok twice


IIS7 - Add this to your web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>