Pages

Monday, June 22, 2015

Working with rsa and dsa public keys.

================================
General
================================
rsa and dsa allow ssh connection to a remote server, without providing a password.


==========================
Short Introduction 
==========================
All work is done under ~home/.ssh/ folder.

First we generate public key, using ssh-keygen utlity.
Then we scp the generated id_rsa.pub file to the remote server.
On the remote server, under .ssh folder, append the newly generated key into authorized_keys file.
cd .ssh
ssh-keygen
cp id_rsa.pub id_rsa.pub_myhost
sftp id_rsa.pub_myhost to remote host
ssh to remote host
cat id_rsa.pub_myhost >> .ssh/authorized_keys
rm 
id_rsa.pub_myhost

==========================
Elaborate Introduction 
==========================
(From Use Public Key Authentication with SSH)
SSH keys come in pairs; a private and a public key. 
Usually the private key is saved as ~/.ssh/id_<type> and the public key is ~/.ssh/id_<type>.pub. 
The type of encryption most often used by default is RSA, so your keys should be named id_rsa and id_rsa.pub. 
The public key is meant to be handed out freely, and added to servers you wish to connect to in the ~/.ssh/authorized_keys file. 
The private key should be secured on your local machine with strict access rules.


When thinking of SSH keys in terms of a lock and key:
The public part is the lock, which can be copied to multiple locations.
The private key is password-protected when encrypted, it is analogous to keeping a physical key in a lockbox. 
With this example in mind, using an SSH key works as follows. 
First, the lockbox/passphrase is opened to obtain the key/private key, which is then used to open the lock/public key and grant access to your remote server.

==========================
id_dsa vs id_rsa
==========================
DSA encryption is based upon prime numbers
RSA encryption is based upon exponents
Both are secure and standard in IT.


================================
Files under .ssh folder
================================
These are the files under some_user/.ssh/

cd .ssh
ls -l
authorized_keys
id_dsa
id_dsa.pub
id_rsa
id_rsa.pub
known_hosts

known_hosts
The history of connections:
each record is in the form of <IP> ssh-rsa <key>.

For example:
111.222.333.444 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAnRpgyOd3sZmzjDrFwVsFckHNDDQfK2
222.444.666.777 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAnRpgyOd3sZmzjDrFwVsFckHNDDQfKW
324.435.657.343 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAndsffggTdHVZ0u3mIqe060XhNppGVe

id_dsa
Private dsa key

-----BEGIN DSA PRIVATE KEY-----
MIIBvAIBAAKBgQDJfi3h0RyeXPdrne0q6zbee8yGkGPCyLPFTLCK7+PwpHjAVKEy
3Kcp5Ex7+ysveXBEo2EcCF8pxYFVz2Q1mqdarve4NHSBCVLgxTykSIZMHmkg7psE
jkixu17egkShsdffdfdffefdfeffrtt8xZ/t91pFuA7ob3K+1PxC376EvwIVAP+T
GdXcFdW5Qnr9Pc1Sa8PWSHDy6d6dds*Q7CIAk7B6naLV4+iM3KBAGft/5EVRtuAq
ziK5zDbOPJkQOA3VRTAsrg==
-----END DSA PRIVATE KEY-----

id_rsa
Private rsa key

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDF19RBhiB5QrYZVogZEdisCuh+Oo55EvZ5OrRUJnK9l0usKwom
ZRNtkCPtdW1BZnF0oM2+6Apbyb54/DYxw4UFmR45zo4DyK81xd7vT/AaWzWpRoLg
ZWBK5TMg2D7QWOfulhSvuAg+oIXsvVMlsxf3UbqcQkjv35KT8FKMncifFwIBIwKB
EDsdUsdn78KcSwCGZzjAu8fGbeFAnS5+6G5/A67angWJUc19X1dqyPdhEmHHZnbN
wpbw40tBFCRcMpE9BLdylLL7UNZX1nfVYcLqIzGhdAm9/f6jLsjVSPR+V6nSqEfA
A4VbSM03DYWBWVl4DlmhUwDY2gd5k+wv9RrMYx/ueNI6CwJBAPGQiGlSU43g5AOJ
Ejydz+oKS3UDePedEyCJqyxWXcBMDUOjDewCpwMm7KI=
-----END RSA PRIVATE KEY-----

id_dsa.pub
dsa keys

ssh-dss AAAAB3NzaC1kc3MAAACr49ivsdqfMCEFB7GSOMMWQcPMyt6T3DNDhdQtZg= my_user@some_server_A

id_rsa.pub
rsa keys


ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAxdfUQYYgeUK2GVaIGRHYrArofjqOes= my_user@some_server_B

authorized_keys
rsa keys and dsa keys

ssh-dss AAAAB3NzaC1kc3MAAACr49ivsdqfMCEFB7GSOMMWQcPMyt6T3DNDhdQtZg= my_user@some_server_A
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAxdfUQYYgeUK2GVaIGRHYrArofjqOes= my_user@some_server_B

If this file exists on server_XXX, it lists who can connect to server_XXX.
It got a list of public keys from remote server(s) that should connect via ssh, to server_XXX.


================================
Generating Public keys
================================
run command:
ssh-keygen (defaulte to rsa)
or
ssh-keygen –t dsa
or
ssh-keygen –t rsa 

-t = type (rsa/dsa)

Each of these commands would generate pair of keys:
id_dsa – stores the private key
id_dsa.pub – stores the public key

passphrase: optional
we skip…

Same if we generate rsa – another pair of keys is generated.
id_rsa – stores the private key
id_rsa.pub – stores the public key

The key files are plain text files.



================================
Transfer the generated public key to remote server
================================
Now – need to transfer the pub  key to the remote server and append into authorized_keys or authorized_keys2 on the remote server.

authorized_keys file lists “who is going to connect me”

After adding an entry there, the user would be authorized to connect without password, via ssh.

Run this command to scp id_rsa.pub file to remote server:
scp  id_rsa.pub some_user@<remote server IP>:/user_home/.ssh/id_rsa.pub_my_key

Now append new key into the authorized_keys file.
ssh to <remote server IP>
cd .ssh
less
id_rsa.pub_my_key >> authorized_keys.2



==============================
.ssh/authorized_keys permissions

==============================
.ssh and .ssh/authorized_keys must have specific permissions.
.ssh must be 700
.ssh/authorized_keys must be 600
Other permission would not work.

Code Example:

--------------------------
On Remote server 111.222.333.444
--------------------------
chmod 777 .ssh
chmod 777 .ssh/authorized_keys

--------------------------
On Local server
--------------------------
ssh akaplan@111.222.333.444
Get an error to login.

--------------------------
On Remote server 111.222.333.444
--------------------------
less /var/log/secure
May  3 10:27:46 remote_server sshd[11605]: Authentication refused: bad ownership or modes for file /home/akaplan/.ssh/authorized_keys
May  3 10:27:46 remote_server sshd[11605]: Authentication refused: bad ownership or modes for file /home/akaplan/.ssh/authorized_keys

cd /home/akaplan/
chmod 700 .ssh
chmod 600 .ssh/authorized_keys

ls -lA
-rwx------  1 akaplan akaplan 1216 May  3 08:51 authorized_keys
ls -lA | grep ssh
drw-------  2 akaplan akaplan 4096 May  3 08:52 .ssh

--------------------------
On Local server
--------------------------
ssh akaplan@111.222.333.444

Successful Login!

Some more reference for permissions:
https://cects.com/openssh-rsa-authentication-for-windows-and-linux/


==============================
Debug ssh connection
==============================

Option A - check Linux log /var/log/secure on remote server.
Option B - run ssh in verbose mode

/var/log/secure
You might see errors like:
May  3 10:27:46 remote_server sshd[11605]: Authentication refused: bad ownership or modes for file /home/akaplan/.ssh/authorized_keys

May  3 10:27:46 remote_server sshd[11605]: Authentication refused: bad ownership or modes for file /home/akaplan/.ssh/authorized_keys

ssh in verbose mode
When a connection is not successful, a good idea is to to run ssh in a verbose mode:

ssh -v => debug1 messages
ssh -vv => 
debug1+debug2 messages
ssh -vvv => debug1+debug2+debug3 messages

Example. 
This how a successful connection would look like:

ssh -vvv some_server
...
...

debug1: SSH2_MSG_SERVICE_REQUEST sent

debug2: service_accept: ssh-userauth

debug1: SSH2_MSG_SERVICE_ACCEPT received

debug2: key: /home/myuser/.ssh/identity (0x0)

debug2: key: /home/myuser/.ssh/id_rsa (0xaaaa40)

debug2: key: /home/myuser/.ssh/id_dsa (0xaaaa58)

debug1: Authentications that can continue: publickey,password

debug3: start over, passed a different list publickey,password

debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /home/myuser/.ssh/identity
debug3: no such identity: /home/myuser/.ssh/identity
debug1: Offering public key: /home/myuser/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 277
debug2: input_userauth_pk_ok: fp af:96:84:28:7e:0e:e5:8f:60:d5:d1:18:c5:3a:c8:49
debug3: sign_and_send_pubkey
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session]
debug3: ssh_session2_open: channel_new: 0
debug2: channel 0: send open
debug1: Entering interactive session.
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug2: callback start
debug2: client_session2_setup: id 0
debug2: channel 0: request pty-req confirm 0
debug3: tty_make_modes: ospeed 38400
debug3: tty_make_modes: ispeed 38400
debug3: tty_make_modes: 1 3


This how a failed connection would look like.
In this case:
1. check user got read permissions to the 
authorized_keys file on remote server
2. Replace the
 old entry in in 
authorized_keys file with new id_rsa.pub from local server


debug3: check_host_in_hostfile: filename /home/myuser/.ssh/known_hosts
debug3: check_host_in_hostfile: match line 9
debug1: Host '222.333.444.555' is known and matches the RSA host key.
debug1: Found key in /home/myuser/.ssh/known_hosts:9
debug2: bits set: 1040/2048
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /home/myuser/.ssh/identity (0x0)
debug2: key: /home/myuser/.ssh/id_rsa (0xaaaa40)
debug2: key: /home/myuser/.ssh/id_dsa (0xaaaa58)
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /home/myuser/.ssh/identity
debug3: no such identity: /home/myuser/.ssh/identity
debug1: Offering public key: /home/myuser/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,password
debug1: Offering public key: /home/myuser/.ssh/id_dsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,password
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password

debug1: Next authentication method: password

==============================
Example 1
==============================
Private Keys Example

local server: local-server
remote server: 10.201.30.400
user: userA

ssh userA@10.201.30.400
The authenticity of host '10.201.30.400 (10.201.30.400)' can't be established.
RSA key fingerprint is 5f:28:e8:59:cc:56:28:36:d2:59:68:4e:4a:a9:02:43.
Are you sure you want to continue connecting (yes/no)? yes

yes

cd .ssh
iu@ecu-por-1-aps-1:~/.ssh>% ls -l
total 32
-rwx------ 1 iu starhome 1444 Jul 16  2012 authorized_keys
-rwx------ 1 iu starhome  672 Aug  9  2007 id_dsa
-rw-r--r-- 1 iu starhome  608 Aug  9  2007 id_dsa.pub
-rwx------ 1 iu starhome  887 Aug  9  2007 id_rsa
-rw-r--r-- 1 iu starhome  228 Aug  9  2007 id_rsa.pub
-rw-r--r-- 1 iu starhome 5417 Mar  6  2014 known_hosts

less authorized_keys
ssh-dss AAAAB3NzaC1kc3MAAACBAMl+ZIZyGFnSHe5m57jXTEstU0A8qjtBFabYVGvaRioP8mRWG8FDxd0UZRlAWlbJdFWbTzcbpC+7U7xs= userA@remote-hostA
ssh-rsa AAAAB3NzaC1yc2EAA434h43h43h43ivNcXe70/wGls1qUaC4GVgSuUzINg+0Fjn7pYUr7gIPqCF7L1TJbMX91G6nEJI79+Sk/BSjJ3Inxc= userA@remote-hostA
ssh-dss AAAAB3NzaC1kc3MAAACBAKL6JymW49ivsdqfMCEFB7GSOMMWQcPMyt6T3DNDhdQtZrabr10cAEAyRhsEfDG23R33LlgzOkU2lg= userB@remote-hostB

Manually copy content of local id_dsa.pub into remote .ssh/authorized_keys or .ssh/authorized_keys2
example of content of local id_dsa.pub 

userC@local-serverA:~/.ssh>% less id_dsa.pub 
ssh-dss qKOq+hkOAMcEGMELKFqocdGrg7wiMo4OJXzgzznWU8iJge8NVZjWJQBNZIqZvqU2jOOXl10B0GjamemeBghCHISz9tSmbw+i/+E= userC@local-serverA

save .ssh/authorized_keys2 and exit
exit
Connection to 10.201.30.400 closed.

login again


userA@local-server:~/.ssh>% ssh userA@10.222.443.400
***************************************************************************
                            NOTICE TO USERS
Use of this system constitutes consent to security monitoring and testing.
All activity is logged with your host name and IP address.
***************************************************************************
rhes-5.7_64-ig_v3.4.1
Last login: Tue Dec 30 08:33:17 2014 from 10.666.555.333
userA@10.222.443.400:~>% 

Now need to re-enter the password.
Task completed!


==============================
Example 2
==============================

End to End example

-----------------------
Current situation
-----------------------
on server 100.100.333.196 trying to connect to 100.222.555.201

-----------------------
$ cd .ssh
iu@isr-sth-1-tsm-1 ~/.ssh
$ grep 100.222.555.201 *
known_hosts:100.222.555.201 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAwMw0LBil9iGPGZOl/TFhtOgSxgH92E20BVlSZSFp/m8e/AnIukFy6Xuw3uFVg/12AH60Kt0LjFlcuZole3wdZxBpkUc5lh2jejDirhl/FOZlwY6Y4ksMzQdx8TfEv9YUSRi1uG2czauw5ENtfhf46YqVVqQDDObL4w/yqiWiLc87PLxrZu5pO/D0xRppMYhKY4JEXX7MQ6tbwPuG3y9UOylGSm/+hXzIEEhGIeOeHqOzHA19lNusRctuh+9fpmswSUqh8d+k1UcIPJGwXvazBEx+MdPUzvWtuvMCrPi4m9FG8o+0VtoP1cH/0JPKfuj1A4s0vB2v8sDwsIOtVHEVCw==


$ sftp 100.222.555.201

Connecting to 100.222.555.201...
***************************************************************************
                            NOTICE TO USERS

Use of this system constitutes consent to security monitoring and testing.

All activity is logged with your host name and IP address.


***************************************************************************

rhes-6.6_64-ig_v4.3.2
iu@100.222.555.201's password:
sftp>

same with ssh session 
$ ssh 100.222.555.201
***************************************************************************
                            NOTICE TO USERS

Use of this system constitutes consent to security monitoring and testing.

All activity is logged with your host name and IP address.


***************************************************************************

rhes-6.6_64-ig_v4.3.2
iu@100.222.555.201's password:
Last login: Sun Jan 15 02:20:59 2017 from 100.100.333.196

-----------------------
Action: 
-----------------------
Generate public key, and add it to remote host .ssh/authorized_keys
on server 100.100.333.196

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/iu/.ssh/id_rsa):
/home/iu/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/iu/.ssh/id_rsa.
Your public key has been saved in /home/iu/.ssh/id_rsa.pub.
The key fingerprint is:
a0:57:fa:27:85:df:c7:87:da:17:54:d3:e0:1e:d6:8c iu@isr-sth-1-tsm-1
The key's randomart image is:
+--[ RSA 2048]----+
|              ...|
|             . =o|
|      . .     E =|
|     . + .   o o |
|    . o S .   o  |
|     . . o . . o |
|        o o . + o|
|         o   + ..|
|            . .. |
+-----------------+

-rwx------ 1 iu None             1675 Jan 18 07:30 id_rsa

-rw-r--r-- 1 iu None              400 Jan 18 07:30 id_rsa.pub
$ less id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEApNg2lpqwhJyeei0kBTY/YufAepdBmuELeVQro3fUwImBSwbseNAk5w9jb79GexH+cvi6PTa9McOnbglGD6aNYUm+b6fSv3nqT2IyGsUcYKcloCw2u1M2o6kuvurIWJCY9YnLDJukAVZ1NkDfozGsKi84NMOCfyl2qyPH1yijJrd/Jg8LeW5iIwBLtCdZ33NbbXwEtCJsahM4AEjnAg7wVO5VJVzoPMOAqQ7eCwpiRxUWQcN2JO5nlQ1+a0lYWuy/V878k5YnBUBn5ASIam1CsGLILVA61Le55SehbpTHdQq/l+4KJs+BzoZXEnAobNSW2VjjNkUQsOB0Gjt7MRA6jw== iu@isr-sth-2-myserver-2

$ less id_rsa
-----BEGIN RSA PRIVATE KEY-----

MIIEoQIBAAKCAQEApNg2lpqwhJyeei0kBTY/YufAepdBmuELeVQro3fUwImBSwbs
eNAk5w9jb79GexH+cvi6PTa9McOnbglGD6aNYUm+b6fSv3nqT2IyGsUcYKcloCw2
u1M2o6kuvurIWJCY9YnLDJukAVZ1NkDfozGsKi84NMOCfyl2qyPH1yijJrd/Jg8L
eW5iIwBLtCdZ33NbbXwEtCJsahM4AEjnAg7wVO5VJVzoPMOAqQ7eCwpiRxUWQcN2
JO5nlQ1+a0lYWuy/V878k5YnBUBn5ASIam1CsGLILVA61Le55SehbpTHdQq/l+4K
Js+BzoZXEnAobNSW2VjjNkUQsOB0Gjt7MRA6jwIBIwKCAQAS1uGqz9mowXEyiNDq
px0v3/i9jaEZA8bMCZ6WVtZ8Z3x9mmQrEHk++nHDoNTa3XwqZZGgmIqmmgSBmqjr
2IUvsKgMwrj/8K0QYv5pdZzX2JaV9mynsb0aBLTinn1L80SuWOQBcN+LH9LhoQOd
n0bgP+kqmgBJDA2P5tUCpY79HBoFt7xCkqGtZs8OoVX5KhGi0KNXUwnc9dCGwZ1q
6xmedZm0mUmQRjZpRIlbpi5iafAAW2WgK5JdJSazaCZdH8XYqGYjgDE6aySxTHry
PKjtvDldc+uuXBk0UPJF6hS0bjJTUDokzO9jx1TA9HRmeREYGY2zuzAIeMUoI0wh
JwHrAoGBANjT047Yo1NUkDYmrReKiqu8aDzps28D2t50iia7dE62UGWfiL0vLmWs
ttEuCDIUEst4fQCAwc67uhB4rM8PAN3WvurRlKATvOrCXHD+AMwWMGoMe2AWvz83
G1Wi3Xe4BeV6cD8VJSw7d9xxa/XKKVxndgHzVPJG2Z1WiPJ6lQUlAoGBAMKgM81a
SAghLIHNdpIQuJVgcjKOWGcY0XjwoJ7fEYF0GO6ZludfLr7jQFr7FBpV41bGJrxq
r1gqTltQzTmdFd5ZTpQLX9gyWfwSSuOk2bB6A2gvHoyIUp4kSAPn9xqSQKHEf85P
qSbp/lUIqTgiB+TfA0leSjof5hmkfa6UZeSjAoGAdbTR7nWafbGQHWVz6DVD9tP+
EnA81d2FcXJ24dN5pxKDal3rJN8ZL+Fqjs/YkDbIX9Oxko8KH8T+mzox7L8AeG1D
EcI6vUyLIFrhua51dhqskVc7qTDrehaZz2cKgtGczQfzynkxb8iC5WIkqgAH0xOX
1SxSr2hKP3gedQC3S+8CgYAyC/AQO8lhLRoSv84ITXFK+4sUUH0h0y6M0ClNbI95
DzmccKMljYEMg5Q0pvaKbdtfdMgh0kpYf+hDXeuhGcPLdgzkPXBqyx50BLQr6I+/
qlilwvk6FG0EF/VC1T+KfWETp46UIxzeHumg1ldmNKLxtbBjUsKhO2cN6HgW8vWh
MQKBgQDVeRqRTJEboqidWbB03yiJBb23lQbYtVgyfbLLuqRo5Cai8PqMIuAUr7w3
wZszv1oapNzVCZh0LjRL+nNk/iCTc6LczNHfWxJ78465Q3eBRrYpJc7JCzFJYUaQ
AqZYbU1bBQuBdCMzoy0s2LLa+Faw8pb5Xx1E9ad403OlGBDBcg==
-----END RSA PRIVATE KEY-----


on server 100.222.555.201, edit /starhome/iu/.ssh/authorized_keys

sftp 100.222.555.201

sftp> cd workarea
sftp> put id_rsa.pub
Uploading id_rsa.pub to /starhome/iu/workarea/id_rsa.pub
id_rsa.pub

cat ../workarea/id_rsa.pub >> authorized_keys

ssh-dss AAAAB3NzaC1kc3MAAACBAMl+LeHRHJ5c92ud7SrrNt57zIaQY8LIs8VMsIrv4/CkeMBUoTLcpynkTHv7Ky95cESjYRwIXynFgVXPZDWap1qu97g0dIEJUuDFPKRIhkweaSDumwSOSLG7Xt6CRKHHLKC1xf3HJ9Wo07pJp/zFn+33WkW4Duhvcr7U/ELfvoS/AAAAFQD/kxnV3BXVuUJ6/T3NUmvD1v5b2wAAAIEAmxDsIgCTsHqdotXj6IzcoEAZ+3/kRVG24CrECLShXV7Pqk5fN5LQfcWa3MvXeCtlTwsQESEWGMgmwJMk4WVKpq5RFYv0CZE+kQNMDw0/f0nektVz4u7gnyUMekZNCHLT7b1xOeFQ5lIyKx8kL8shWNe7fIXc1pt4pnlRntybUmoAAACAfH9qnIrShi17V8SwcPDvXbt1yKy/gougyn88RJCIBGrOJgVXOI40jFi5xB1FmGMqeTZIDTxX2OhcKeFxL8xDT2+QjmH/TF+ZIZyGFnSHe5m57jXTEstU0A8qjtBFabYVGvaRioP8mRWG8FDxd0UZRlAWlbJdFWbTzcbpC+7U7xs= iu@inf-guy-1-tst-1
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAxdfUQYYgeUK2GVaIGRHYrArofjqOeRL2eTq0VCZyvZdLrCsKJmUTbZAj7XVtQWZxdKDNvugKW8m+ePw2McOFBZkeOc6OA8ivNcXe70/wGls1qUaC4GVgSuUzINg+0Fjn7pYUr7gIPqCF7L1TJbMX91G6nEJI79+Sk/BSjJ3Inxc= iu@inf-guy-1-tst-1ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEApNg2lpqwhJyeei0kBTY/YufAepdBmuELeVQro3fUwImBSwbseNAk5w9jb79GexH+cvi6PTa9McOnbglGD6aNYUm+b6fSv3nqT2IyGsUcYKcloCw2u1M2o6kuvurIWJCY9YnLDJukAVZ1NkDfozGsKi84NMOCfyl2qyPH1yijJrd/Jg8LeW5iIwBLtCdZ33NbbXwEtCJsahM4AEjnAg7wVO5VJVzoPMOAqQ7eCwpiRxUWQcN2JO5nlQ1+a0lYWuy/V878k5YnBUBn5ASIam1CsGLILVA61Le55SehbpTHdQq/l+4KJs+BzoZXEnAobNSW2VjjNkUQsOB0Gjt7MRA6jw== iu@isr-sth-2-myserver-2

on server 100.100.333.196
$ ssh  100.222.555.201
***************************************************************************
                            NOTICE TO USERS

Use of this system constitutes consent to security monitoring and testing.

All activity is logged with your host name and IP address.


***************************************************************************

rhes-6.6_64-ig_v4.3.2

Last login: Wed Jan 18 07:33:23 2017 from 100.100.333.196


Now, no password is required.

==============================
Example 2
==============================
What does this error mean:
d:\tma_taps>ssh user@111.222.333.444
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
bf:6d:7b:c4:ab:ad:c4:3f:35:fd:b8:34:d7:10:74:05.
Please contact your system administrator.
Add correct host key in /home/local_user/.ssh/known_hosts to get rid of this message.
Offending key in /home/local_user/.ssh/known_hosts:9
RSA host key for 111.222.333.444 has changed and you have requested strict checking.

Host key verification failed.

Option A - Indeed the RSA was changed on the remote server.
Option B - The fingerprint of the remote server was changed (new hardware, new OS).
                    In this case need to clean up local known_hosts file
                    /home/local_user/.ssh/known_hosts.
                    Meaning to  delete the rows of remote server.
                    After that you will be asked to accept SSH key again.
                    And the /home/local_user/.ssh/known_hosts would be updated with a new                   entry.


==============================
Example 3
==============================
This the result of ssh connection to server 444.222.666.111.
This connection was working before.
What went wrong?


Need to compare the ssh versions on Client and on Server.
ssh version is not compatible with ssh2 version.
ssh version is using public key in format ssh 
sshs version is using public key in format ssh2 
If Client is using ssh and connecting to a server that is using ssh2, the connection would fail.
That might happen, if on server OS upgrade was done.

In this case, the authorized_keys file on the remote server is out of sync with the public key of the local server.

Example of rsa SSH PUBLIC KEY

ssh-rsa AAAAB3NzaC1yc2DEDJNKIwAAAQEAwsH7d6WfAobryFBD7MHIYIBA0q3bNHlaG0FhB3EahqElwmAUyt+3+7vv1NkOymlgIFsHe7sddsd87iiI/pQpmiQH9iQ4h2KYpIwlHWXKGJqG9TPwNHUR7G+f1R7zh9cXaIRk2NFFXzgfPKAtP8cixUhqraju+9nA0NyAsQdjsdhks879o2//T28n7K/YyFgK4AsEBqn8S2di3bJ8VUmAQhbWivu5lZTMmNn9quVa97OmilDCea+nL425pksSzMkntZB26yQ7WNyUUCFNltCkbqShnigAI7Kbpngk2tHaRMxP3OzWDdd+qnZV9qdwlCMPyIWr87rLhyoot7sGmw== my_user@my_server


Example of rsa SSH2 PUBLIC KEY
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "2048-bit RSA, converted from OpenSSH by my_user@my_server"
AAAAB3NzaC1yc2EAAAABIwAAAQEAwsH7d6WfAobryFBD7MHIYIBA0q3bNHlaG0Fh
B3EahqElwmAUyt+3+7vv1NkOymlgIFsHe72dBGHPYINSHiiI/pQpmiQH9iQ4h2KY
pIwlHWXKGWEDWDWEHUR7G+f1R7zh9cXaIRk2NFFXzgfPKAtP8cixUhqraju+9nA
0NyAsQyvo2En+GwGr5//T28n7K/YyFgK4AsEBqn8S2di3bJ8VUmAQhbWivu5lZTM
mNn9quVa97OmilDCea+nL425pksSzMkntZB26yQ7WNyUUCFNltCkbqShnigAI7Kb
pngk2tHaRMxP3OzWDdd+gyER79dfdfdsfr53GHLhyoot7sGmw==
---- END SSH2 PUBLIC KEY ---- 

Example of connection, and failure:


$ sftp 444.222.666.111
Connecting to 444.222.666.111...
WARNING: DSA key found for host 444.222.666.111
in /home/iu/.ssh/known_hosts:13
DSA key fingerprint de:6e:01:1e:e2:0f:bd:9f:d8:9f:2f:a5:12:47:be:b6.
The authenticity of host '444.222.666.111 (444.222.666.111)' can't be established
but keys of different type are already known for this host.
RSA key fingerprint is e0:28:63:df:6d:bf:ec:89:5a:ed:f9:83:50:37:7b:39.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '444.222.666.111' (RSA) to the list of known hosts.
Permission denied (publickey).
Connection closed



Use -v option to see the full stack of messages

$ ssh -v 444.222.666.111
OpenSSH_4.7p1, OpenSSL 0.9.8g 19 Oct 2007
debug1: Reading configuration data /etc/ssh_config
debug1: Connecting to 194.20.69.142 [194.20.69.142] port 22.
debug1: Connection established.
debug1: identity file /home/iu/.ssh/identity type -1
debug1: identity file /home/iu/.ssh/id_rsa type 1
debug1: identity file /home/iu/.ssh/id_dsa type 2
debug1: Remote protocol version 2.0, remote software version 6.2.1.168 SSH Tectia Server
debug1: no match: 6.2.1.168 SSH Tectia Server
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.7
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host '194.20.69.142' is known and matches the RSA host key.
debug1: Found key in /home/iu/.ssh/known_hosts:23
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /home/iu/.ssh/identity
debug1: Offering public key: /home/iu/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Offering public key: /home/iu/.ssh/id_dsa
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
Permission denied (publickey).

With -vvv flag you get even more detailed trace

$ ssh -vvv SFTP_MEG@444.222.666.111
OpenSSH_4.7p1, OpenSSL 0.9.8g 19 Oct 2007
debug1: Reading configuration data /etc/ssh_config
debug2: ssh_connect: needpriv 0
debug1: Connecting to 444.222.666.111 [444.222.666.111] port 22.
debug1: Connection established.
debug1: identity file /home/iu/.ssh/identity type -1
debug3: Not a RSA1 key file /home/iu/.ssh/id_rsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /home/iu/.ssh/id_rsa type 1
debug3: Not a RSA1 key file /home/iu/.ssh/id_dsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /home/iu/.ssh/id_dsa type 2
debug1: Remote protocol version 2.0, remote software version 6.2.1.168 SSH Tectia Server
debug1: no match: 6.2.1.168 SSH Tectia Server
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.7
debug2: fd 3 setting O_NONBLOCK
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group14-sha224@ssh.com,diffie-hellman-group14-sha256@ssh.com,diffie-hellman-group15-sha256@ssh.com,diffie-hellman-group15-sha384@ssh.com,diffie-hellman-group16-sha384@ssh.com,diffie-hellman-group16-sha512@ssh.com,diffie-hellman-group18-sha512@ssh.com,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha224@ssh.com,diffie-hellman-group-exchange-sha384@ssh.com,diffie-hellman-group-exchange-sha512@ssh.com
debug2: kex_parse_kexinit: ssh-rsa,ssh-rsa-sha256@ssh.com
debug2: kex_parse_kexinit: aes128-cbc,aes128-ctr,aes192-cbc,aes192-ctr,aes256-cbc,aes256-ctr,crypticore128@ssh.com,seed-cbc@ssh.com,3des-cbc,arcfour,blowfish-cbc,twofish-cbc,twofish128-cbc,twofish192-cbc,twofish256-cbcdebug2: kex_parse_kexinit: aes128-cbc,aes128-ctr,aes192-cbc,aes192-ctr,aes256-cbc,aes256-ctr,crypticore128@ssh.com,seed-cbc@ssh.com,3des-cbc,arcfour,blowfish-cbc,twofish-cbc,twofish128-cbc,twofish192-cbc,twofish256-cbc
debug2: kex_parse_kexinit: hmac-sha1,hmac-sha1-96,hmac-sha256-2@ssh.com,hmac-sha224@ssh.com,hmac-sha256@ssh.com,hmac-sha384@ssh.com,hmac-sha512@ssh.com,crypticore-mac@ssh.com,hmac-md5,hmac-md5-96
debug2: kex_parse_kexinit: hmac-sha1,hmac-sha1-96,hmac-sha256-2@ssh.com,hmac-sha224@ssh.com,hmac-sha256@ssh.com,hmac-sha384@ssh.com,hmac-sha512@ssh.com,crypticore-mac@ssh.com,hmac-md5,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib
debug2: kex_parse_kexinit: none,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-cbc hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 149/256
debug2: bits set: 524/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug3: check_host_in_hostfile: filename /home/iu/.ssh/known_hosts
debug3: check_host_in_hostfile: match line 22
debug1: Host '194.20.69.142' is known and matches the RSA host key.
debug1: Found key in /home/iu/.ssh/known_hosts:22
debug2: bits set: 489/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /home/iu/.ssh/identity (0x0)
debug2: key: /home/iu/.ssh/id_rsa (0xaaaa40)
debug2: key: /home/iu/.ssh/id_dsa (0xaaaa58)
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /home/iu/.ssh/identity
debug3: no such identity: /home/iu/.ssh/identity
debug1: Offering public key: /home/iu/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug1: Offering public key: /home/iu/.ssh/id_dsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).


==============================
Example 4
==============================
Sending file from isr-sth-2-cgw-1 to pru-cla-1-aps-2

============================
On iu@isr-sth-2-cgw-1
============================
sftp oracle@111.222.333.444

put id_rsa.pub


============================
On oracle@pru-cla-1-aps-2
============================
cat id_rsa.pub > .ssh/authorized_keys

less .ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAw78dKA+JM0PirDMgrng3yv8ZT+PCQD52/VoDkvsW47egKg7WlQxbY3TweOrslWxmM20tTr0i8NmCzYAEVcQmwuvSI4AG1P4V0x/n3kaOsaK/sNRurHgqb2effslEywS8GlfrXNSTlZZ1tsOey8T1140IGjN/JVvVAc8C4/U14U0= 

============================
On iu@isr-sth-2-cgw-1
============================
iu@isr-sth-2-cgw-1:~/.ssh>%ssh oracle@111.222.333.444
connection!

iu@isr-sth-2-cgw-1:~/.ssh>% scp ./test_file.txt oracle@111.222.333.444:/software/oracle/oracle/
********************************************************************
                            NOTICE TO USERS

Use of this system constitutes consent to security monitoring and testing.
All activity is logged with your host name and IP address.


********************************************************************
rhes-5.5_64-ig_v3.3.0
test_file.txt                                                                         100%    0     0.0KB/s   --:-- ETA

Done without password prompt.

iu@isr-sth-2-cgw-1:~/.ssh>% sftp oracle@111.222.333.444
Connecting to 111.222.333.444...
********************************************************************
                            NOTICE TO USERS

Use of this system constitutes consent to security monitoring and testing.
All activity is logged with your host name and IP address.


********************************************************************
rhes-5.5_64-ig_v3.3.0
Done without password prompt.

================================
Host Key
================================
A host key is the server’s public key. 
The host key is used by the client to decrypt an authentication message sent from the server when connecting. 
The basic purpose of the host key is to ensure that when you connect to a remote host, it is actually the host that you intended to connect to. 

Creating a host key for a Secure Shell server is usually done only once. 
The server software creates the host key automatically during installation.
Another option is to manually generate a host key and select the encryption algorithm (DSA or RSA). This similar to User Authentication keys.

A host key consists of two components, a private and a public component. 
The public component is sent to the client when the client connects. 
The private component must be protected. Only server administrator and the Secure Shell server have access to it.

Upon the initial connection, the user is promted with message:
The authenticity of host '444.222.666.111 (444.222.666.111)' can't be established.
RSA key fingerprint is e0:28:63:df:4i:sc:ec:12:7j:ed:f9:83:50:37:7b:39.
Are you sure you want to continue connecting (yes/no)? yes

Answering yes, would add an entry for server 444.222.666.111 to .ssh/known_keys file.







Approve adding host key to known_keys file.
The authenticity of host '444.222.666.111 (444.222.666.111)' can't be established.
RSA key fingerprint is e0:28:63:df:4i:sc:ec:12:7j:ed:f9:83:50:37:7b:39.
Are you sure you want to continue connecting (yes/no)? yes







================================
ssh and ssh2 versions
================================

ssh connectivity have more then one version, OpenSSH and SSH2 
The public key provided by client, must be the version that used on server side.

Convert the public key from OpenSSH to SSH2. 
ssh-keygen -e -f ~/.ssh/id_dsa.pub > ~/.ssh/id_dsa_ssh2.pub

Convert SSH2 to OpenSSH. 
ssh-keygen -i -f ~/.ssh/id_dsa_1024_a.pub > ~/.ssh/id_dsa_1024_a_openssh.pub



================================
Stop message Enter passphrase for key
================================

Enter passphrase for key '/starhome/iu/.ssh/id_rsa':
Enter passphrase for key '/starhome/iu/.ssh/id_dsa':
iu@espat-2-ora-01's password:

iu@DERATVDB00001:~/.ssh>%  
ssh-agent bash
iu@DERATVDB00001:~/.ssh>%  ssh-add
Could not open a connection to your authentication agent.
iu@DERATVDB00001:~/.ssh>% eval $(ssh-agent)
Agent pid 29752
iu@DERATVDB00001:~/.ssh>%  ssh-add
Enter passphrase for /starhome/iu/.ssh/id_rsa: <password>
Enter passphrase for /starhome/iu/.ssh/id_dsa: 
<password>

Next time connection will immediate

In case ssh-add thows an error:
ssh-add /c/Users/akaplan/.ssh/id_rsa
/c/Users/myuser/.ssh/id_rsa: No such file or directory

In this case need to create the id_rsa

cmd -> ssh-keygen -> press Enter -> key is generated
Now, run again ssh-add /c/Users/akaplan/.ssh/id_rsa

========================
ssh and git
========================
From the git prompt:

$ ssh-add -l
Could not open a connection to your authentication agent.


$ eval "$(ssh-agent)"
Agent pid 375


$  ssh-add -l
The agent has no identities.


$ ssh-add /c/Users/myuser/.ssh/id_rsa
Identity added: /c/Users/myuser/.ssh/id_rsa (myuser@my_domain)

to test:
$ ssh -T git@bitbucket.org
logged in as myuser

No you can use git to connect to Bitbucket. 

Audit Table changes with Trigger by example

==================================
General
==================================
This is an example of auditing DML operations on a table using a trigger, and logging these changes into an audit table.
Audit table resides on a dedicated Tablespace.
Optionally this table can be partitioned by change date.

==================================
Trigger code
==================================
The trigger is inserting records into Audit table whenever there is an update on the base table.

CREATE OR REPLACE TRIGGER AUD_CUSTOMERS_TRG
  AFTER UPDATE OR INSERT OR DELETE ON CUSTOMERS
  FOR EACH ROW
DECLARE
  v_oper_user VARCHAR2(30);
BEGIN

  SELECT  UPPER(SUBSTR(SYS_CONTEXT('USERENV','OS_USER'),1,30)) INTO v_oper_user 
    FROM DUAL;

  IF INSERTING THEN
    INSERT INTO AUD_CUSTOMERS
      (change_date, change_action, old_new, customer_id, name, oper_user)
    VALUES
      (SYSDATE, 'INSERT', 'NEW', :NEW.customer_id, :NEW.name, v_oper_user);
  ELSIF UPDATING THEN
    INSERT INTO AUD_CUSTOMERS
      (change_date, change_action, old_new, customer_id, name, oper_user)
    VALUES
      (SYSDATE, 'UPDATE', 'OLD', :OLD.customer_id, :OLD.name,  v_oper_user);
    INSERT INTO AUD_CUSTOMERS
      (change_date, change_action, old_new, customer_id, name, oper_user)
    VALUES
      (SYSDATE, 'UPDATE', 'NEW', :NEW.customer_id, :NEW.name, v_oper_user);
  ELSE
    INSERT INTO AUD_CUSTOMERS
      (change_date, change_action, old_new, customer_id, name, oper_user)
    VALUES
      (SYSDATE, 'DELETE', 'OLD', :OLD.customer_id, :OLD.name,  v_oper_user);
  END IF;
END;

==================================
The DDL of the Audit Table
==================================
The structure of the Audit table is same as the base table, with addition of four fields:
- change_date
- change_action: INSERT/UPDATE/DELETE
- old_new: NEW/OLD
- oper_user: The OS login of the user who made this change.

CREATE TABLE AUD_CUSTOMERS(
change_date                DATE NOT NULL, 
change_action              VARCHAR2(10 BYTE) NOT NULL,
old_new                    VARCHAR2(3 BYTE) NOT NULL,
customer_id                VARCHAR2(5 BYTE)  ,                          
name                       VARCHAR2(30 BYTE) ,                          
oper_user                  VARCHAR2(30 BYTE)  
)
tablespace AUDIT_TBS NOLOGGING;

alter table AUD_CUSTOMERS
  add constraint AUD_CUSTOMERS_PK primary key (change_date, change_action, old_new)
  using index 
  tablespace AUDIT_TBS;

grant select, insert, update, delete, references, alter, index on AUD_CUSTOMERS to MANAGER;
grant select on AUD_CUSTOMERS to SELECTOR;
grant select on AUD_CUSTOMERS to USERS_ROLE;


Sunday, June 21, 2015

Remote Desktop, mstsc options.

Remote Desktop, mstsc, options

useful options when using mstsc

mstsc /v:222:333:444:555
  Connect to server 222:333:444:555

mstsc /v:222:333:444:555:44
  Connect to server 222:333:444:555 on port 44

mstsc /v:222:333:444:555 /f 
  Starts Remote Desktop Connection in full-screen mode.

mstsc /v:222:333:444:555 /span 
  Matches the remote desktop width and height with the local virtual desktop

mstsc /v:222:333:444:555 /w:[width] /h:[height] 
  Starts Remote Desktop Connection in width and height.

mstsc /v:222:333:444:555 /edit  "connection file"
  Opens  "connection file".rdp for editing

mstsc /v:222:333:444:555 /console
  An older (before Windows 7 and Windows Server 2008) syntax.
  By using it you're connecting to the Console Session on the server. 

mstsc /v:222:333:444:555 /admin
  This mode differed from normal connection in few ways: 
  Disable Remote Desktop Services client access licensing, and other minor changes.

mstsc /v:222:333:444:555 /public
  Connect to server 222:333:444:555 in public mode.


console and admin connection modes
In Windows Server 2003, you can start the RDC client (mstsc.exe) by using the /console switch to remotely connect to the physical console session on the server (also known as session 0). 
In Windows Server 2008 or Windows Server 2008 R2, the /console switch has been deprecated. 

In Windows Server 2008 and Windows Server 2008 R2, session 0 is a noninteractive session that is reserved for services. 


You can use the new /admin switch to remotely connect to a Windows Server 2008-based server for administrative purposes.

If you you /console option with RDC 6.0 client or higher, the /console switch is silently ignored.

tsadminStart -> Run -> tsadmin -> Would open a window of Terminal Services Manager.
This is a way to connect to other Terminal Server sessions on a server.

Thursday, June 18, 2015

Check on Oracle version, Oracle Edition

=========================
General
=========================
1. How to tell if Oracle is Enterprise Edition (EE) or Standard Edition (SE)
2. How to view oracle Component versions.


=========================
Oracle SE or EE?
=========================

Option A. - check in V$VERSION

SQL> SELECT * FROM V$VERSION;

For Standard Edition the output is:

BANNER
--------------------------------------------------------------------------------
Oracle Database 11g Release 11.1.0.7.0 - 64bit Production
PL/SQL Release 11.1.0.7.0 - Production
CORE    11.1.0.7.0      Production
TNS for Linux: Version 11.1.0.7.0 - Production
NLSRTL Version 11.1.0.7.0 - Production


For Enterprise Edition the output is:

BANNER
----------------------------------------------------------------
Oracle Database 10g Enterprise Edition Release 10.1.0.5.0 - Prod
PL/SQL Release 10.1.0.5.0 - Production
CORE 10.1.0.5.0 Production
TNS for Linux: Version 10.1.0.5.0 - Production
NLSRTL Version 10.1.0.5.0 - Production

Option B. - check on the server, in file context.xml

/software/oracle/111/inventory/Components21/oracle.server/11.1.0.6.0>% 
less context.xml | grep  s_serverInstallType

For Standard Edition the output is:
<VAR NAME="s_serverInstallType" TYPE="String" DESC_RES_ID="s_serverInstallType_DESC" SECURE="F" VAL="SE" ADV="F" CLONABLE="F" USER_INPUT="CALC"/>

For Standard Edition the output is:
<VAR NAME="s_serverInstallType" TYPE="String" DESC_RES_ID="s_serverInstallType_DESC" SECURE="F" VAL="EE" ADV="F" CLONABLE="F" USER_INPUT="CALC"/>

=========================
Oracle components versions

=========================
SELECT * FROM SYS.PRODUCT_COMPONENT_VERSION;

PRODUCT                        VERSION                        STATUS
------------------------------ ------------------------------ ------------------------------
NLSRTL                         11.2.0.4.0                     Production
Oracle Database 11g            11.2.0.4.0                     64bit Production
PL/SQL                         11.2.0.4.0                     Production
TNS for Linux:                 11.2.0.4.0                     Production

Tuesday, June 2, 2015

Partition an existing Table with DBMS_REDEFINITION, by Example.

=============================
General
=============================
Example of partitioning existing table using 
DBMS_REDEFINITION package.

Please see this post for general description of DBMS_REDEFINITION

=============================
General steps to partition existing table with DBMS_REDEFINITION
=============================

A. Check is the redefinition is possible 
DBMS_REDEFINITION.can_redef_table

B. Manual steps.
B-1. Check the space needed. 
You may need to create the partitioned table on a new Tablespace/Add datafile.

B-2. Manually create a new 
partitioned table. 
         This table would be manually dropped at the end of the process.

C. Start the redefinition 
DBMS_REDEFINITION.start_redef_table

D. Copy dependent objects
DBMS_REDEFINITION.copy_table_dependents
An alternative to this step is to manually create Constraints and Indexes on the new table.

E. Check for errors.
Query DBA_REDEFINITION_ERRORS

F. Synchronize data between old and new tables
DBMS_REDEFINITION.sync_interim_table

G. Complete the Redefinition Process
DBMS_REDEFINITION.finish_redef_table

At this point the partitioned table has become the "real" table and their names have been switched in the data dictionary.

H. Drop the interim table.
DROP TABLE ... PURGE;

J. Gather statistics on the new table.
EXEC DBMS_STATS.gather_table_stats

=============================
Example of using  DBMS_REDEFINITION to partition existing table step by step.
=============================

In this example, the table is quite large.
Approx 35,000,000 rows, 10Gb storage space.
It is holding audit data from DBA_FGA_AUDIT_TRAIL.
The idea is to partition the table by 
timestamp field.

Before starting the Partitioning of a table, need to make few checks
1. Check if the original table could be partitioned.
2. Check the space needed. During partitioning, a new temporary table would be created.
3. Manually create a new partitioned table.


The table before partitioning:

CREATE TABLE STATEMENTS_AUDIT
(
  session_id         NUMBER not null,
  timestamp          DATE,
  db_user            VARCHAR2(120),
  os_user            VARCHAR2(1020),
  userhost           VARCHAR2(512),
  client_id          VARCHAR2(256),
  ext_name           VARCHAR2(4000),
  object_schema      VARCHAR2(120),
  object_name        VARCHAR2(512),
  policy_name        VARCHAR2(120),
  scn                NUMBER,
  sql_text           VARCHAR2(4000),
  sql_bind           VARCHAR2(4000),
  comment$text       VARCHAR2(4000),
  statement_type     VARCHAR2(112),
  extended_timestamp TIMESTAMP(6) WITH TIME ZONE,
  proxy_sessionid    NUMBER,
  global_uid         VARCHAR2(128),
  instance_number    NUMBER,
  os_process         VARCHAR2(64),
  transactionid      RAW(8),
  statementid        NUMBER,
  entryid            NUMBER
)
tablespace COLLECT_TABLE;

CREATE INDEX STATEMENTS_AUDIT_IND1 on STATEMENTS_AUDIT (OBJECT_SCHEMA, OBJECT_NAME) tablespace COLLECT_INDEX;

There is no PK on this table.

A. Check if the Redefinition is possible.
Since there is no PK on the table, Oracle would need to work with ROWIDs.

BEGIN
  DBMS_REDEFINITION.can_redef_table ('MANAGER', 'STATEMENTS_AUDIT', DBMS_REDEFINITION.CONS_USE_ROWID);
END;
/
PL/SQL procedure successfully completed

B-1. Check the space needed. 

SELECT tablespace_name, segment_name, bytes/1024/1024 AS MB 
FROM DBA_SEGMENTS 
WHERE  segment_name='STATEMENTS_AUDIT';

TABLESPACE_NAME                SEGMENT_NAME                           MB
------------------------------ ------------------------------ ----------
COLLECT_TABLE                  STATEMENTS_AUDIT                    10128


SELECT tablespace_name, file_name, (maxbytes-user_bytes)/1024/1024 AS free_Mb  
FROM DBA_DATA_FILES 
WHERE  tablespace_name = 'COLLECT_TABLE';

TABLESPACE_NAME  FILE_NAME                                     FREE_MB
---------------- ------------------------------------------ ----------
COLLECT_TABLE    /oracle_db/db1/oraint/COLLECT_TABLE_1.dbf  3003.04687
COLLECT_TABLE    /oracle_db/db1/oraint/COLLECT_TABLE_2.dbf    580.0625

There is no additional 10Gb on the COLLECT_TABLE tablespace
The new partitioned table would be created in a new tablespace, AUDIT_TBS.

Lets create new Tablespace.
CREATE TABLESPACE AUDIT_TBS DATAFILE '/oracle_db/db1/orainst/AUDIT_TBS_1.dbf' SIZE 200M AUTOEXTEND ON NEXT 200M MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO ;
Tablespace created

B-2. Create new partitioned table on the new tablespace.

The table is partitioned by year range, on field timestamp.
The index is created with LOCAL clause.

CREATE TABLE STATEMENTS_AUDIT_PRT
(
  session_id         NUMBER not null,
  timestamp        DATE,
  db_user            VARCHAR2(120),
  os_user            VARCHAR2(1020),
  userhost           VARCHAR2(512),
  client_id          VARCHAR2(256),
  ext_name           VARCHAR2(4000),
  object_schema      VARCHAR2(120),
  object_name        VARCHAR2(512),
  policy_name        VARCHAR2(120),
  scn                NUMBER,
  sql_text           VARCHAR2(4000),
  sql_bind           VARCHAR2(4000),
  comment$text       VARCHAR2(4000),
  statement_type     VARCHAR2(112),
  extended_timestamp TIMESTAMP(6) WITH TIME ZONE,
  proxy_sessionid    NUMBER,
  global_uid         VARCHAR2(128),
  instance_number    NUMBER,
  os_process         VARCHAR2(64),
  transactionid      RAW(8),
  statementid        NUMBER,
  entryid            NUMBER
)
partition by range (timestamp)
(
  partition P_2010 values less than (TO_DATE('20110101','YYYYMMDD')) tablespace AUDIT_TBS
   storage (initial 64K minextents 1 maxextents unlimited  ),  
  partition P_2011 values less than (TO_DATE('20120101','YYYYMMDD')) tablespace AUDIT_TBS
   storage (initial 64K minextents 1 maxextents unlimited  ),     
  partition P_2012 values less than (TO_DATE('20130101','YYYYMMDD')) tablespace AUDIT_TBS
   storage (initial 64K minextents 1 maxextents unlimited  ),     
  partition P_2013 values less than (TO_DATE('20140101','YYYYMMDD')) tablespace AUDIT_TBS
   storage (initial 64K minextents 1 maxextents unlimited  ),     
  partition P_2014 values less than (TO_DATE('20150101','YYYYMMDD')) tablespace AUDIT_TBS
   storage (initial 64K minextents 1 maxextents unlimited  ),     
  partition P_2015 values less than (TO_DATE('20160101','YYYYMMDD')) tablespace AUDIT_TBS
   storage (initial 64K minextents 1 maxextents unlimited  ),     
  partition P_2016 values less than (TO_DATE('20170101','YYYYMMDD')) tablespace AUDIT_TBS
   storage (initial 64K minextents 1 maxextents unlimited  ),     
  partition P_2017 values less than (TO_DATE('20180101','YYYYMMDD')) tablespace AUDIT_TBS
   storage (initial 64K minextents 1 maxextents unlimited  ),     
  partition P_2018 values less than (TO_DATE('20190101','YYYYMMDD')) tablespace AUDIT_TBS
   storage (initial 64K minextents 1 maxextents unlimited  ),     
  partition P_2019 values less than (TO_DATE('20200101','YYYYMMDD')) tablespace AUDIT_TBS
   storage (initial 64K minextents 1 maxextents unlimited  ),     
  partition P_2020 values less than (TO_DATE('20210101','YYYYMMDD')) tablespace AUDIT_TBS
   storage (initial 64K minextents 1 maxextents unlimited  )
)

NOLOGGING;

CREATE INDEX STATEMENTS_AUDIT_IX01 ON STATEMENTS_AUDIT_PRT (OBJECT_SCHEMA, OBJECT_NAME) LOCAL;

Index created


C. Start the redefinition 
BEGIN
  DBMS_REDEFINITION.start_redef_table('MANAGER', 'STATEMENTS_AUDIT', 'STATEMENTS_AUDIT_PRT',OPTIONS_FLAG => DBMS_REDEFINITION.CONS_USE_ROWID);
END;
/
PL/SQL procedure successfully completed

This is the most heavy step.

D. Copy dependent objects
DECLARE
  num_errors PLS_INTEGER;
BEGIN
  DBMS_REDEFINITION.copy_table_dependents ('MANAGER', 'STATEMENTS_AUDIT', 'STATEMENTS_AUDIT_PRT', DBMS_REDEFINITION.CONS_ORIG_PARAMS, TRUE, TRUE, TRUE, TRUE, num_errors);
END;
/
PL/SQL procedure successfully completed

E. Check for errors.
SELECT object_name, base_table_name, ddl_txt 
FROM DBA_REDEFINITION_ERRORS;

F. Synchronize data between old and new tables
BEGIN
  DBMS_REDEFINITION.sync_interim_table ('MANAGER', 'STATEMENTS_AUDIT', 'STATEMENTS_AUDIT_PRT');
END;
/
PL/SQL procedure successfully completed

G. Complete the Redefintion Process
BEGIN
  DBMS_REDEFINITION.finish_redef_table ('MANAGER', 'STATEMENTS_AUDIT', 'STATEMENTS_AUDIT_PRT');
END;
/
PL/SQL procedure successfully completed


H. Drop the interim table.

Before dropping the inetrim table, check USER_TABLES, USER_SEGMENTS, USER_OBJECTS.

SELECT table_name, tablespace_name, logging, partitioned 
FROM USER_TABLES 
WHERE table_name LIKE 'STATEMENTS_AUDIT%';

TABLE_NAME                     TABLESPACE_NAME                LOGGING PARTITIONED
------------------------------ ------------------------------ ------- -----------
STATEMENTS_AUDIT                                                      YES
STATEMENTS_AUDIT_PRT           COLLECT_TABLE                  NO      NO

SELECT segment_name, partition_name, segment_type, tablespace_name 
FROM USER_SEGMENTS 
WHERE segment_name like 'STATEMENTS_AUDIT%'

SEGMENT_NAME                   PARTITION_NAME       SEGMENT_TYPE         TABLESPACE_NAME
------------------------------ -------------------- -------------------- ----------------
STATEMENTS_AUDIT_PRT                                TABLE                COLLECT_TABLE
STATEMENTS_AUDIT               P_2010               TABLE PARTITION      AUDIT_TBS
STATEMENTS_AUDIT               P_2011               TABLE PARTITION      AUDIT_TBS
STATEMENTS_AUDIT               P_2012               TABLE PARTITION      AUDIT_TBS
STATEMENTS_AUDIT               P_2013               TABLE PARTITION      AUDIT_TBS
STATEMENTS_AUDIT               P_2014               TABLE PARTITION      AUDIT_TBS
STATEMENTS_AUDIT               P_2015               TABLE PARTITION      AUDIT_TBS
STATEMENTS_AUDIT               P_2016               TABLE PARTITION      AUDIT_TBS
STATEMENTS_AUDIT               P_2017               TABLE PARTITION      AUDIT_TBS
STATEMENTS_AUDIT               P_2018               TABLE PARTITION      AUDIT_TBS
STATEMENTS_AUDIT               P_2019               TABLE PARTITION      AUDIT_TBS
STATEMENTS_AUDIT               P_2020               TABLE PARTITION      AUDIT_TBS
STATEMENTS_AUDIT_IND1                               INDEX                COLLECT_INDEX
STATEMENTS_AUDIT_IX01          P_2010               INDEX PARTITION      AUDIT_TBS
STATEMENTS_AUDIT_IX01          P_2011               INDEX PARTITION      AUDIT_TBS
STATEMENTS_AUDIT_IX01          P_2012               INDEX PARTITION      AUDIT_TBS
STATEMENTS_AUDIT_IX01          P_2013               INDEX PARTITION      AUDIT_TBS
STATEMENTS_AUDIT_IX01          P_2014               INDEX PARTITION      AUDIT_TBS
STATEMENTS_AUDIT_IX01          P_2015               INDEX PARTITION      AUDIT_TBS
STATEMENTS_AUDIT_IX01          P_2016               INDEX PARTITION      AUDIT_TBS
STATEMENTS_AUDIT_IX01          P_2017               INDEX PARTITION      AUDIT_TBS
STATEMENTS_AUDIT_IX01          P_2018               INDEX PARTITION      AUDIT_TBS
STATEMENTS_AUDIT_IX01          P_2019               INDEX PARTITION      AUDIT_TBS
STATEMENTS_AUDIT_IX01          P_2020               INDEX PARTITION      AUDIT_TBS

SELECT object_name, subobject_name, object_id, created, status 
FROM USER_OBJECTS 
WHERE object_name like 'STATEMENTS_AUDIT%';

OBJECT_NAME                    SUBOBJECT_NAME        OBJECT_ID CREATED     STATUS
------------------------------ -------------------- ---------- ----------- --------
STATEMENTS_AUDIT               P_2010                 32047566 01/06/2015  VALID
STATEMENTS_AUDIT               P_2011                 32047567 01/06/2015  VALID
STATEMENTS_AUDIT               P_2012                 32047568 01/06/2015  VALID
STATEMENTS_AUDIT               P_2013                 32047569 01/06/2015  VALID
STATEMENTS_AUDIT               P_2014                 32047570 01/06/2015  VALID
STATEMENTS_AUDIT               P_2015                 32047571 01/06/2015  VALID
STATEMENTS_AUDIT               P_2016                 32047572 01/06/2015  VALID
STATEMENTS_AUDIT               P_2017                 32047573 01/06/2015  VALID
STATEMENTS_AUDIT               P_2018                 32047574 01/06/2015  VALID
STATEMENTS_AUDIT               P_2019                 32047575 01/06/2015  VALID
STATEMENTS_AUDIT               P_2020                 32047576 01/06/2015  VALID
STATEMENTS_AUDIT                                      32047565 01/06/2015  VALID
STATEMENTS_AUDIT_IND1                                  7728253 24/03/2010  VALID
STATEMENTS_AUDIT_IX01          P_2010                 32062110 02/06/2015  VALID
STATEMENTS_AUDIT_IX01          P_2011                 32062111 02/06/2015  VALID
STATEMENTS_AUDIT_IX01          P_2012                 32062112 02/06/2015  VALID
STATEMENTS_AUDIT_IX01          P_2013                 32062113 02/06/2015  VALID
STATEMENTS_AUDIT_IX01          P_2014                 32062114 02/06/2015  VALID
STATEMENTS_AUDIT_IX01          P_2015                 32062115 02/06/2015  VALID
STATEMENTS_AUDIT_IX01          P_2016                 32062116 02/06/2015  VALID
STATEMENTS_AUDIT_IX01          P_2017                 32062117 02/06/2015  VALID
STATEMENTS_AUDIT_IX01          P_2018                 32062118 02/06/2015  VALID
STATEMENTS_AUDIT_IX01          P_2019                 32062119 02/06/2015  VALID
STATEMENTS_AUDIT_IX01          P_2020                 32062120 02/06/2015  VALID
STATEMENTS_AUDIT_IX01                                 32062109 02/06/2015  VALID

STATEMENTS_AUDIT_PRT                                   1825644 26/12/2007  VALID


DROP TABLE MANAGER.STATEMENTS_AUDIT_PRT CASCADE CONSTRAINTS PURGE;

Table dropped

J. Gather statistics on the new table.
BEGIN
  DBMS_STATS.GATHER_TABLE_STATS (ownname =>  'MANAGER', tabname => 'STATEMENTS_AUDIT');
END;
/

PL/SQL procedure successfully completed

SELECT table_name, partition_name, num_rows, sample_size, last_analyzed   
FROM USER_TAB_PARTITIONS
WHERE table_name = 'STATEMENTS_AUDIT'

TABLE_NAME                     PARTITION_NAME         NUM_ROWS SAMPLE_SIZE LAST_ANALYZED
------------------------------ -------------------- ---------- ----------- -------------
STATEMENTS_AUDIT               P_2020                        0             02/06/2015 08
STATEMENTS_AUDIT               P_2019                        0             02/06/2015 08
STATEMENTS_AUDIT               P_2018                        0             02/06/2015 08
STATEMENTS_AUDIT               P_2017                        0             02/06/2015 08
STATEMENTS_AUDIT               P_2016                        0             02/06/2015 08
STATEMENTS_AUDIT               P_2015                 12236078      573669 02/06/2015 08
STATEMENTS_AUDIT               P_2014                 22430950      529563 02/06/2015 08
STATEMENTS_AUDIT               P_2013                    11103       11103 02/06/2015 08
STATEMENTS_AUDIT               P_2012                    41490       41490 02/06/2015 08
STATEMENTS_AUDIT               P_2011                    56042       56042 02/06/2015 08STATEMENTS_AUDIT               P_2010                   949638      949638 02/06/2015 08

=============================
Optionally - drop old partitions
=============================
ALTER TABLE STATEMENTS_AUDIT DROP PARTITION P_2010