Showing posts with label Oracle. Show all posts
Showing posts with label Oracle. Show all posts

Thursday, February 28, 2019

How to perform Instance Actions (Instance Stop/Start) using REST API on Oracle Cloud Infrastructure Compute Instances

Hello,

Using REST API to interact with Oracle Cloud Infrastructure is highly desirable for programmatic access to OCI resources from your applications.

For performing instance actions such as STOP, START, RESET and others as mentioned in OCI API documentation [1], you need to pass the parameters as follows rather than via json file. Somehow, I am unable to pass the parameters using json file.

You could create an empty json file as follows and use it on the REST API Call.
 
Load oci-curl function:
# . ./oci-curl

 Create an empty JSON file as we need to use POST method:

# touch empty.json

Syntax:
#oci-curl iaas.us-ashburn-1.oraclecloud.com post ./empty.json "/20160918/instances/?instanceId=&action=STOP"


Refer OCI REST API documentation [2] for more details how to generate signature and authorization strings for accessing API.
 
A copy of the oci-curl script is provided below. You need to update the following parameters in the script though:
local tenancyId="ocid1.tenancy.oc1..aaaaaaaaoumXXXnhkrc72dn6wjs27gq";
local authUserId="ocid1.user.oc1..aaaaaaaa6dmk7XXXhfshe6cacmpt2tjmq";
local keyFingerprint="b3:8f:55:XX:XX:XX:XX:86:a9:be:d4";
local privateKeyPath="/Users/muyself/.oci/oci_api_key.pem";

I am passing the parameters to the rest endpoint after "?". Multiple parameters can be passed using "&".

In the above example, I am passing the 2 required parameters "instanceId" and "action" after ? Separated using &.


Example:
#oci-curl iaas.us-ashburn-1.oraclecloud.com post ./empty.json "/20160918/instances/ocid1.instance.oc1.iad.abuwcljtttj6sgpah77XXXXXXXXXwde5fhdy6apfu5mk7svvgigxq?instanceId=ocid1.instance.oc1.iad.abuwcljtttj6sgpah77XXXXXXXXXwsvvgigxq&action=STOP"

 

Here is the oci-curl script:

# Version: 1.0.2
# Usage:
# oci-curl <host> <method> [file-to-send-as-body] <request-target> [extra-curl-args]
#
# ex:
# oci-curl iaas.us-ashburn-1.oraclecloud.com get "/20160918/instances?compartmentId=some-compartment-ocid"
# oci-curl iaas.us-ashburn-1.oraclecloud.com post ./request.json "/20160918/vcns"
# oci-curl iaas.eu-frankfurt-1.oraclecloud.com post ./empty.json "/20160918/instances/ocid1.instance.oc1.eu-frankfurt-1.antheljt2nxxxxxud53gpggoryh2k?instanceId&action=START"

function oci-curl {
# TODO: update these values to your own
local tenancyId="ocid1.tenancy.oc1..aaaaaaaaouminldguXXXX6snhkrc72dn6wjs27gq";
local authUserId="ocid1.user.oc1..aaaaaaaadmkXXXXXXX2imyg23khy4vuuv6a5aytjmq";
local keyFingerprint="b3:8f:55:5e:xx:xx:xx:xx4:86:a9:be:d4";
local privateKeyPath="/Users/myself/.oci/oci_api_key.pem";

local alg=rsa-sha256
local sigVersion="1"
local now="$(LC_ALL=C \date -u "+%a, %d %h %Y %H:%M:%S GMT")"
local host=$1
local method=$2
local extra_args
local keyId="$tenancyId/$authUserId/$keyFingerprint"

case $method in

"get" | "GET")
local target=$3
extra_args=("${@: 4}")
local curl_method="GET";
local request_method="get";
;;

"delete" | "DELETE")
local target=$3
extra_args=("${@: 4}")
local curl_method="DELETE";
local request_method="delete";
;;

"head" | "HEAD")
local target=$3
extra_args=("--head" "${@: 4}")
local curl_method="HEAD";
local request_method="head";
;;

"post" | "POST")
local body=$3
local target=$4
extra_args=("${@: 5}")
local curl_method="POST";
local request_method="post";
local content_sha256="$(openssl dgst -binary -sha256 < $body | openssl enc -e -base64)";
local content_type="application/json";
local content_length="$(wc -c < $body | xargs)";
;;

"put" | "PUT")
local body=$3
local target=$4
extra_args=("${@: 5}")
local curl_method="PUT"
local request_method="put"
local content_sha256="$(openssl dgst -binary -sha256 < $body | openssl enc -e -base64)";
local content_type="application/json";
local content_length="$(wc -c < $body | xargs)";
;;

*) echo "invalid method"; return;;
esac

# This line will url encode all special characters in the request target except "/", "?", "=", and "&", since those characters are used
# in the request target to indicate path and query string structure. If you need to encode any of "/", "?", "=", or "&", such as when
# used as part of a path value or query string key or value, you will need to do that yourself in the request target you pass in.
local escaped_target="$(echo $( rawurlencode "$target" ))"

local request_target="(request-target): $request_method $escaped_target"
local date_header="date: $now"
local host_header="host: $host"
local content_sha256_header="x-content-sha256: $content_sha256"
local content_type_header="content-type: $content_type"
local content_length_header="content-length: $content_length"
local signing_string="$request_target\n$date_header\n$host_header"
local headers="(request-target) date host"
local curl_header_args
curl_header_args=(-H "$date_header")
local body_arg
body_arg=()

if [ "$curl_method" = "PUT" -o "$curl_method" = "POST" ]; then
signing_string="$signing_string\n$content_sha256_header\n$content_type_header\n$content_length_header"
headers=$headers" x-content-sha256 content-type content-length"
curl_header_args=("${curl_header_args[@]}" -H "$content_sha256_header" -H "$content_type_header" -H "$content_length_header")
body_arg=(--data-binary @${body})
fi

local sig=$(printf '%b' "$signing_string" | \
openssl dgst -sha256 -sign $privateKeyPath | \
openssl enc -e -base64 | tr -d '\n')

curl "${extra_args[@]}" "${body_arg[@]}" -X $curl_method -sS https://${host}${escaped_target} "${curl_header_args[@]}" \
-H "Authorization: Signature version=\"$sigVersion\",keyId=\"$keyId\",algorithm=\"$alg\",headers=\"${headers}\",signature=\"$sig\""
}

# url encode all special characters except "/", "?", "=", and "&"
function rawurlencode {
local string="${1}"
local strlen=${#string}
local encoded=""
local pos c o

for (( pos=0 ; pos<strlen ; pos++ )); do
c=${string:$pos:1}
case "$c" in
[-_.~a-zA-Z0-9] | "/" | "?" | "=" | "&" ) o="${c}" ;;
* ) printf -v o '%%%02x' "'$c"
esac
encoded+="${o}"
done

echo "${encoded}"
}
 
You may copy the oci-curl script and load it to the shell. After that you should be able to use REST API methods.    
 
This is an example of how to use REST API.
 

Sunday, September 30, 2018

Set up Secure VNC server in RHEL /OEL / CentOS using SSH tunnel

Hello Guys,

Its been long time since I posted something here. I am trying to make time to write something and make this blog more active.

Lets see how to setup secure VNC server using SSH tunnel in RHEL/OEL/CentOS based Oracle Cloud OCI instances.

As you know, VNC protocol is unencrypted. Even though the log in process has some encryption, it is possible to sniff VNC traffic and collect sensitive infomration. You can fully secure a VNC session by tunnelling it via a SSH tunnel. Another advantage of tunnelling VNC via SSH is that you do not need to open VNC ports – TCP 590X on your Subnet’s Security List. The existing rule for SSH traffic will do fine.

I expect you have desktop environment installed on the instance. By default, VNC is configured to use Xterm as the terminal emulator and twm as the window manager for the X Window System.



RHEL 7/ OEL 7/ CentOS 7 OCI Instances


1.     Install VNC server.

$ sudo yum -y install tigervnc-server pixman pixman-devel libXfont

2.     Setup vnc password for your user.

We are setting up VNC for the default user ‘opc’, if you want to set it up for another user, just change the steps accordingly.

Log in to the user opc and set up VNC password
$ su – opc
$ vncpasswd

3.     Add a VNC Service configuration file.
The VNC daemon configuration file is available in systemd directory below:

$ ls /lib/systemd/system | grep -i vncserver
vncserver@.service


Copy and setup the VNC configuration file.

Backup the configuration file:
$ sudo cp /lib/systemd/system/vncserver@.service  /etc/systemd/system/vncserver@:1.service




     Update/create configuration file as follows:
$ sudo cat /etc/systemd/system/vncserver@\:1.service | egrep -v "^#"


[Unit]
Description=Remote desktop service (VNC)
After=syslog.target network.target

[Service]
Type=forking

ExecStartPre=/bin/sh -c '/usr/bin/vncserver -kill %i > /dev/null 2>&1 || :'
ExecStart=/usr/sbin/runuser -l opc -c "/usr/bin/vncserver %i -geometry 1280x1024 -localhost"
PIDFile=/home/opc/.vnc/%H%i.pid
ExecStop=/bin/sh -c '/usr/bin/vncserver -kill %i > /dev/null 2>&1 || :'

[Install]
WantedBy=multi-user.target

Do remember to change the user name if you are setting VNC for a different user, here we are setting it up for user opc. Also, please note that the parameter “-localhost” makes VNC server to listen on loopback interface and accept connection from a tunnel only.



Make sure your VNC Xstartup file has the below contents:

$ cat /home/opc/.vnc/xstartup
#!/bin/sh
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
#exec /etc/X11/xinit/xinitrc
/bin/gnome-session &

Set permission:
$ chmod 755 /home/opc/.vnc/xstartup

You must reload the systemd system initialization program after setting up the VNC server.

$ systemctl daemon-reload


4.     Start VNC server.
You can now start your VNC server using:

$ sudo systemctl start vncserver@:1 


RHEL 6/ OEL 6/ CentOS 6 OCI Instances


The VNC configuration is different in previous versions on RHEL based systems. You may follow the below steps to set up a secure VNC server.

1.     Install VNC server packages
$ sudo yum install -y vnc-server xorg-x11-fonts-Type1

2.     Update VNC server parameters in /etc/sysconfig/vncservers as follows:
$ cat /etc/sysconfig/vncservers
      VNCSERVERS="1:opc"
      VNCSERVERARGS[1]="-geometry 640x480 -localhost"

3.     Set VNC password
Log in to the user opc and set up VNC password
$ su – opc
$ vncpasswd

4.     Start VNC server
# sudo service vncserver start



Setup your clients to connect to the VNC server.


We have set up the VNC server to be available only via a secure tunnel. As such, we need to create an SSH tunnel from the client to the server before you can access the VNC session.

1.     Setup SSH Tunnel on your client machine

On Mac OS/Linux based clients, you may set up an SSH tunnel as follows:

$ ssh -i /path/to/key -L 5901:localhost:5901 -N -f opc@IP


      On Windows clients, you may set up SSH tunnelling using Putty.
Start putty and under Connection -> SSH -> Tunnels add:
Source port: 5901
Destination: localhost:5901
Then click “Add” to create port forwarding.
And connect to your server at its IP address and port 22 via PuTTY.



 


 Don't forget to click "Add" after updating the forwarded port and destination.


  You may access your instance using VNC using any VNC client using localhost:5901 now.


-->



Hope this helps. Let me know if you have any questions.


Jay
 
-->
-->