Figer's Technology Consulting | December 2014

Simple Login Page Background Image using CSS



<script>
$('body').css('background-image', 'url(../images/glassbackground.png)');
$('body').css('background-repeat', 'no-repeat');
$('body').css('background-size', '100% 200%');
$('body').css('background-origin', 'content-box');
</script>

ADB over wifi



These easy commands from Terminal on a Mac

To find the IP address of the device: run ./adb shell and then netcfg.


1.) adb tcpip 5555

2.) adb connect 192.168.1.102:5555


Disconnect USB and proceed with wireless debugging.


To switch back to USB when done

3.) adb -s 192.168.1.102:5555 usb 

Google Glass Hello World GDK app in Eclipse



Pre-requisites: Eclipse IDE, Android SDK, Google Glass

You need to run the application directly on the Glass device, there is no emulator (make sure you enable debugging on Glass)


In this tutorial, we will learn how to write a simple “Hello,World!” program for Google Glass using the GDK.


Step 1: Create Android project for Glass


Create a new Android application project called HelloGlass with package name com.app.glass and choose the Target platform as Glass Development Kit Preview for Android 4.4


Step 2: Creating cards


As per the Glass design patterns, developers can either create static cards or Live cards. In this case I will choose to create a static card since I would only be displaying a message to the user. The Card class creates well-formed cards given a set of properties.


A Card has the following properties:


1. Main body text

2. Left-aligned footer

3. One or more images that are displayed as a mosaic on the background of the card or on the left side of the card.


Step 3: Voice Invocation model


Voice commands play an important role in user interaction with Glass allowing hands-free and quick actions. Any Glass application that you develop needs to be invoked using a voice command. Developers can also add their own voice commands. However, please make sure you read the voice command checklist before you proceed.


Step 4: Putting it all together


Let’s start by creating our Hello,World application. Create a new Activity class called HelloWorldActivity and add the following code!


HelloWorldActivity.java


package com.app.glass;


import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import com.google.android.glass.app.Card;


public class HelloWorldActivity extends Activity {


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);


Card myCard = new Card(this);

myCard.setText("Hello, World!");

myCard.setFootnote("First Glassware for Glass");

View cardView = myCard.getView();

// Display the card we just created

setContentView(cardView);

}


}

Next, we need to create a Service class that will recognize the voice command.


HelloGlass.java


package com.app.glass;


import android.app.Service;

import android.content.Intent;

import android.os.IBinder;


public class HelloGlass extends Service {


@Override

public IBinder onBind(Intent intent) {

// TODO Auto-generated method stub

return null;

}


public int onStartCommand(Intent intent, int flags, int startId) {


Intent i = new Intent(this, HelloWorldActivity.class);

i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(i);

return START_STICKY;

}


}

In order to launch the Glassware from the “ok,glass” menu we need to add the following service in the AndroidManifest.xml file!


AndroidManifest.xml

<!--?xml version="1.0" encoding="utf-8"?-->

package="com.app.glass"

android:versionCode="1"

android:versionName="1.0" &gt;


&lt;uses-sdk

android:minSdkVersion="8"

android:targetSdkVersion="19" /&gt;


<!-- Don't use themes -->

&lt;application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name" &gt;

&lt;activity

android:name="com.app.glass.HelloWorldActivity"

android:label="@string/app_name"

android:enabled="true"&gt;


&lt;service

android:name="com.app.glass.HelloGlass"

android:enabled="true"

android:exported="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name" &gt;


<!-- Voice command found in res/xml/voice_trigger_start -->

&lt;meta-data

android:name="com.google.android.glass.VoiceTrigger"

android:resource="@xml/voice_trigger_start" /&gt;


res/xml/voice_trigger_start.xml


<!--?xml version="1.0" encoding="utf-8"?-->

<!-- The string used to start the application from the "Okay, Glass" menu -->


res/values/strings.xml


<!--?xml version="1.0" encoding="utf-8"?-->


HelloGlass

Settings

hello glass

Save Money! Schedule backups on free SQL Server Express



When we're bootstrapping our startups we try to save money and we lean towards SQL Server Express (lacks SQL agent to schedule backups) because it's free until the idea is proven / funded and it justifies the enterprise edition. We of course still need to make sure our data is securely backed up be it onsite with a client or as an Amazon EC2 instance spun up in the cloud.


Here is how we solved this problem.

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


Add the exact line below and save it as SQLBackup.bat


"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.exe" -S localhost -i "D:\SQLBackup\SQLBackup.sql" &gt;&gt; log.txt


Add all the SQL below and save it as SQLBackup.sql (update server folder location D:\SQLBackup\ and database name SEA2014 as needed, this will create a backup for each day of the week by name and overwrite if the file exists so you'll get the last 7 days of backups). Make sure the folder location has security permission to be accessed, test running the .bat from the command prompt to test.


DECLARE @dest nvarchar(255)

SET @dest = N'D:\SQLBackup\SEA2014_' + CAST(DATEPART(weekday, GETDATE()) AS nvarchar(1)) + '.bak'

BACKUP DATABASE [SEA2014] TO DISK = @dest WITH NOFORMAT, NOINIT, NAME = N'SEA2014-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10

GO


DECLARE @dest nvarchar(255)

SET @dest = N'D:\SQLBackup\SEA2014_' + CAST(DATEPART(weekday, GETDATE()) AS nvarchar(1)) + '.bak'

declare @backupSetId as int

select @backupSetId = position from msdb..backupset where database_name=N'SEA2014' and backup_set_id=(select max(backup_set_id) from msdb..backupset where database_name=N'SEA2014' )

if @backupSetId is null begin raiserror(N'Verify failed. Backup information for database ''SEA2014'' not found.', 16, 1) end

RESTORE VERIFYONLY FROM DISK = @dest WITH FILE = @backupSetId, NOUNLOAD, NOREWIND

GO


Finally in Windows Task Scheduler call the .bat file on a weekly basis.

Code Google Glass using C# in Xamarin Studio

1.) Install Xamarin Studio 

 2.) Follow this YouTube Video to configure Xamarin Studio with Google Glass: http://www.youtube.com/watch?v=NyjB4QoX9fM 

 3.) In Xamarin Studio, click "Tools" -> "Open Android SDK Manager", make sure "API Level 19" is selected, then click "Install XX Packages" where XX equals the number of packages that will be installed. 

 4.) Update MainActivity.cs voice trigger lines to this:
[IntentFilter (new String[]{ "com.google.android.glass.action.VOICE_TRIGGER" })]
[MetaData ("com.google.android.glass.VoiceTrigger", Resource = "@xml/voicetriggerstart")]

5.) rename voicetrigger.xml under XML folder to VoiceTriggerStart.xml

6.) Modify app to your liking. 

 7.)Sideload the .APK to onto Glass: https://www.youtube.com/watch?v=TYJQhebDvRE

Poor Man's Single Sign-On between two systems

1.) Pass a new querystring variable we'll call "values" from one system to the other.


2.) This "Values" parameter will be symmetrically encrypted from one system and decrypted on the receiving system using 3DES with a common secret key. See my article on how I'm already doing this: http://www.figers.com/Blog/2014/02/28/symetrical-3des-encryption-in-java-and-decryption-in-vb-net/


3.) "values" will contain the UserID, other values you need and a randomly generated number in the form of today's date attached to 10 digit randomly generated number, it would look like 040320141234567890.


4.) When the system receiving the request decrypts "values" it checks the randomly generated number to see if it's been used before, if it has, it rejects the entire request. If it hasn't been used before it processes the sign-on request and adding the random number to the table for later verification.


5.) Since the URL can never be re-used we aren't concerned with browser history or sniffing over the wire at say a coffee shop.


5.) Each time the first system displays the link to jump to the second system or the link is clicked it generates a new random number in the link.


6.) Because the number is encrypted an attacker would need to know the secret key to even be able to guess a number to try (i.e. unless 3DES is cracked this is not possible).


Now we have secure Single Sign-On from one system to another.

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.