RaspberryPi swapping between WLAN client and AccessPoint - raspberry-pi3

I am currently trying to configure the Wifi of a RaspberryPI 3 A+.
I followed this guide: here to make the Raspberry a WiFi Accesspoint.
now i have a small Flask webserver running. With that i want to deactivate the AP and instead connect the Raspberry to a wifi.
But that does not work.
So I acctivate the AP via:
def setAP(ssid, pw):
os.system('sudo systemctl stop dnsmasq')
os.system('sudo systemctl stop hostapd')
if not os.path.isfile('/etc/dhcpcd.conf.orig'):
os.system('sudo mv /etc/dhcpcd.conf /etc/dhcpcd.conf.orig')
with open('/etc/dhcpcd.conf', "a+") as f:
dat = f.read()
if " static ip_address" not in dat:
f.write("interface wlan0\n static ip_address=192.168.4.1/24\n nohook wpa_supplicant")
os.system('sudo service dhcpcd restart')
if not os.path.isfile('/etc/dnsmasq.conf.orig'):
os.system('sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig')
with open('/etc/dnsmasq.conf', 'w') as f:
f.write("interface=wlan0\n")
f.write("dhcp-range = 192.168.4.2,192.168.4.20,255.255.255.0,24h\n")
os.system('sudo service dnsmasq restart')
with open('/etc/hostapd/hostapd.conf', "w") as f:
f.write("interface=wlan0\n")
f.write("driver=nl80211\n")
f.write("ssid={:}\n".format(ssid))
f.write("hw_mode=g\n")
f.write("channel=7\n")
f.write("wmm_enabled=0\n")
f.write("macaddr_acl=0\n")
f.write("auth_algs=1\n")
f.write("ignore_broadcast_ssid=0\n")
f.write("wpa=2\n")
f.write("wpa_passphrase={:}\n".format(pw))
f.write("wpa_key_mgmt=WPA-PSK\n")
f.write("wpa_pairwise=TKIP\n")
f.write("rsn_pairwise=CCMP\n")
with open('/etc/default/hostapd', "w") as f:
f.write('DAEMON_CONF="/etc/hostapd/hostapd.conf"')
os.system('sudo systemctl unmask hostapd')
os.system('sudo systemctl enable hostapd')
os.system('sudo systemctl start hostapd')
Then Ill try to reverse that via:
def setClient(ssid, pw, dhcp=True, ip=""):
os.system('sudo systemctl stop dnsmasq')
os.system('sudo systemctl stop hostapd')
if os.path.isfile('/etc/dhcpcd.conf.orig'):
os.system('sudo mv /etc/dhcpcd.conf.orig /etc/dhcpcd.conf')
os.system('sudo service dhcpcd restart')
if os.path.isfile('/etc/dnsmasq.conf.orig'):
print('configure dhcp')
os.system('sudo mv /etc/dnsmasq.conf.orig /etc/dnsmasq.conf')
with open('/etc/default/hostapd', "w") as f:
f.write(' ')
if not os.path.isfile('/etc/wpa_supplicant/wpa_supplicant.conf.orig'):
os.system('sudo mv /etc/wpa_supplicant/wpa_supplicant.conf /etc/wpa_supplicant/wpa_supplicant.conf.orig')
And connect to a Wifi:
os.system('sudo mv /etc/wpa_supplicant/wpa_supplicant.conf /etc/wpa_supplicant/wpa_supplicant.conf.orig')
with open('/etc/wpa_supplicant/wpa_supplicant.conf', 'w+') as f:
f.write('ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n')
f.write('update_config=1\n')
f.write('country=DE\n\n')
f.write('network={\n')
f.write('\tssid="{:}"\n'.format(ssid))
f.write('\tpsk="{:}"\n'.format(pw))
f.write('}')
os.system('sudo wpa_cli -i wlan0 reconfigure')
and here I get the Error:
Failed to connect to non-global ctrl_ifname: wlan0 error: No such file or directory
also now I cant connect to a Wifi with the grafical interface or raspi-config. It tells me "no Wireless interface found".
with ifconfig i still see the wlan0 - but it hast some random? ip address.
And the AP is still active.
someone knows what i am doing wrong?
or some tips how to do it better?

Related

SNMPd opens "random" UDP port besides 161 and 162 to the outside

I would like to use snmp to monitor my localhost and have installed the corresponding package on Ubuntu 18.03 with apt install snmp. Without having changed the default configuration, I have launched the daemon with systemctl start snmpd. After launching the daemon the output of lsof -i -n | grep snmpd is as follows:
snmpd 14668 Debian-snmp 12u IPv4 13252990 0t0 UDP 127.0.0.1:snmp
snmpd 14668 Debian-snmp 13u IPv4 13252988 0t0 UDP *:41898
I am wondering about the second line of the output as the port has been opened to the outside. Restarting the daemon changes the open port to another (randomized?) high port number. I have been looking up this behaviour a couple of hours and wasn´t able to find any explanation.
Can anybody explain to me whats going on here or how to disable/remove the open port?
Configuration
AgentAdress is configured as follows:
# /etc/snmp/snmpd.conf
# Listen for connections from the local system only
agentAddress udp:127.0.0.1:161
The daemon has been launched with following options:
# /etc/default/snmp
# snmpd options (use syslog, close stdin/out/err).
SNMPDOPTS='-Lsd -Lf /dev/null -u Debian-snmp -g Debian-snmp -I -smux,mteTrigger,mteTriggerConf -p /run/snmpd.pid'
Output of ps aux | grep snmpd
/usr/sbin/snmpd -Lsd -Lf /dev/null -u Debian-snmp -g Debian-snmp -I -smux mteTrigger mteTriggerConf -f
So, if anybody comes across the same question: The UDP port has been opened by snmp-traps. In order to avoid this behavior, I had to comment out following line in the snmpd.conf:
/etc/snmp/snmpd.conf
# ACTIVE MONITORING
# send SNMPv1 traps
# !comment this line out!
# trapsink localhost public
Read this link for further information: https://sourceforge.net/p/net-snmp/mailman/message/29219475/

Firebase DB program works when logged in but not on boot using raspberry pi

I am creating an IOT device with raspberry pi and using firebase admin sdk to communicate over the web. The code works exavtly how I want it to... Until I try adding it into local.rc for using it headlessly.
I'm unable to copy the error as it is only being thrown on boot. Here is a picture.
https://drive.google.com/open?id=0B9zzhouEyyN_RmttYVVOZXE0d2JXNWtTZHBjTlZYRTZkdy1N
From what I can read it has to do with an authority problem from where the program is being run. This is my rc.local:
# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
printf "My IP address is %s\n" "$_IP"
fi
#My line
sudo sh /home/pi/superscript.sh
exit 0
the supercript is
sudo python home/pi/servo.py & sudo python home/pi/buttonCheck.py&
I've tried with and without sudo.
Thanks for any help.
I switched my process from running in rc.local to being a service in systemd, thanks to Kamil Cuk. Here is a link to the documentation for using systemd service method.
Though I am not experiencing any crashing, but putting Restart=Always will restart it after crash if applicable.
This is what it looks like.
[Unit]
Description=Room controller
After=multi-user.target
[Service]
Type=idle
ExecStart=/usr/bin/python /home/pi/servoController.py & /usr/bin/python /home/pi/buttonListener.py
Restart=always
[Install]
WantedBy=multi-user.target

How to reach docker container `localhost` from Mac?

Note this is different from How to expose a service running inside a docker container, bound to localhost, which can be addressed in multiple ways in Docker for Linux, say through --net host or even -v to bind my Linux-flavor client in etc. My problem is specific for Docker for Mac, so it's not as straightforward.
I have a TCP server binding to localhost:5005 running inside Docker for Mac. (For security reason, I must not bind to 0.0.0.0:5005.)
I have a TCP client sending request to this server from my Mac (not inside the docker container).
My question is, how do I make it work?
In Linux Docker, I would simply use --net=host so the server binds to my host lo interface, but it seems that Docker for Mac runs on a managed VM, so the host network behavior is different behavior.
To illustrate my point:
On MacBook
It simply would not work
[me#MacBook App]$ docker run -v `pwd`:/App -p 127.0.0.1:5005:5005 nitincypher/docker-ubuntu-python-pip /App/server.py
[me#MacBook App]$ ./client.py
Client received data:
On Linux
In comparison, it would be trivial to do on Linux by using host network mode. Since I'm using my Linux's lo interface as my container lo interface.
[me#Linux App]$ docker run -v `pwd`:/App --net=host nitincypher/docker-ubuntu-python-pip /App/server.py
Server Connection address: ('127.0.0.1', 52172)
Server received data: Hello, World!
[me#Linux App]$ ./client.py
Client received data: Hello, World!
My Simulated Server Code
Requirement: It MUST bind to localhost, and nothing else. So I cannot change it to 0.0.0.0.
#!/usr/bin/env python
import socket
TCP_IP = 'localhost'
TCP_PORT = 5005
BUFFER_SIZE = 20 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print 'Server Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "Server received data:", data
conn.send(data) # echo
conn.close()
My Simulated Client Code
Requirement: It MUST be ran on MacBook, since the real client is written in CPP and compiled to run only on MacBook.
#!/usr/bin/env python
import socket
TCP_IP = 'localhost'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print "Client received data:", data
Here's a working solution. The basic idea is to use SSH tunneling to do the port forwarding.
High Level Idea
You first need to build a docker image to support SSH access, because
ubuntu image doesn't have a sshd out of box, and also
you will need to know the password of root of your running container.
Then you will spin up your container as what you would normally do except that you are doing that based on the new image you created.
You create a SSH tunneling session from your MacBook, then you run your client on MacBook as you would normally do.
For reference, the command for SSH tunneling can be found here, the process of creating a sshd docker image is explained here, and how to ssh into docker container is explained here
Steps
Create a Docker file Dockerfile
#Use whatever image you are using on Docker Linux , say "FROM ubuntu:16.04"
FROM nitincypher/docker-ubuntu-python-pip
RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:screencast' | chpasswd
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's#session\s*required\s*pam_loginuid.so#session optional pam_loginuid.so#g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
Create a Docker Image from the Dockerfile
[me#MacBook App]$ docker build -t my_ssh_python .
Spin up your server container
[me#MacBook App]$ docker run -d -P -v `pwd`:/App --name myserver my_ssh_python
Start your server inside the container
[me#MacBook App]$ docker exec myserver /App/server.py
Create a SSH tunnel
[me#MacBook App]$ ssh root#`hostname` -p `docker port myserver 22 | awk -F ":" '{print $2}'` -L 8000:localhost:8000 -N
#Password is "screencast" as you built in Dockerfile
Note that
a. You have to use the IP address of your MacBook instead of your docker container's IP address.
b. You will use the port where the default container ssh port 22 is mapped to on host
c. In tunneling -L 8000:localhost:8000, you are saying forward anything from your MacBook 8000 (the first 8000) to Docker container's localhost at port 8000
Now you can use you client locally
[me#MacBook App]$ ./client.py
Client received data: Hello, World!
And on server side, you can see
Server Connection address: ('127.0.0.1', 55396)
Server received data: Hello, World!

KEXT not loadable even System Integrity Protection is disable in 10.11

Currently I'm developing a small KEXT that can block access to the USB storage. However when I can't load my KEXT using kextutil
Code Signing Failure: not code signed
I did turn off the SIP in 10.11
System Integrity Protection status: disabled.
Please help. I don't know what to do!
Thanks.
It was long research I have did for these simple steps and documentation and I am listing it here for someone like me.
Before following the procedure please disable SIP
start your Mac in recovery mode by shutting it down and starting it by pressing command+R button until apple logo comes up.
open terminal application and enter below command
csrutil disable
reboot
These are the important command for coping kext using root access to the location, changing its ownership to wheel, checking its dependancies of osbundlelibraries and checking if the kext is loadable or not.
sudo cp -R
sudo chown -R root:wheel
sudo kextlibs -xml //checks the osbundlelibrary files to be present in info plist
sudo kextutil -n -t // check the kext and logs if the kext loadable or not
sudo kextutil -n // check the kext and logs if the kext loadable or not
sudo kextutil // check the kext and logs if the kext loadable or not
sudo kextload // loads your kext if kernel doesn’t generate panic
sudo kextunload // unloads your kext
Important urls
https://people.sissa.it/~inno/pubs/skb-reduced.pdf
https://github.com/objective-see/LuLu
https://objective-see.com/blog/blog_0x0B.html
https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KEXTConcept/KEXTConceptIntro/introduction.html#//apple_ref/doc/uid/10000191-SW1
https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KernelProgramming/boundaries/boundaries.html
https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/NKEConceptual/intro/intro.html#//apple_ref/doc/uid/TP40001858-CH225-SW1
https://developer.apple.com/library/archive/documentation/DeviceDrivers/Conceptual/IOKitFundamentals/Features/Features.html#//apple_ref/doc/uid/TP0000012-TPXREF101
https://developer.apple.com/library/archive/documentation/DeviceDrivers/Conceptual/AccessingHardware/AH_Intro/AH_Intro.html#//apple_ref/doc/uid/TP30000376
https://developer.apple.com/library/archive/documentation/Networking/Conceptual/CFNetwork/Introduction/Introduction.html#//apple_ref/doc/uid/TP30001132
https://developer.apple.com/library/archive/documentation/DeviceDrivers/Conceptual/WritingDeviceDriver/Introduction/Intro.html#//apple_ref/doc/uid/TP30000694
https://developer.apple.com/library/archive/navigation/index.html#section=Technologies&topic=Kernel
https://developer.apple.com/library/archive/documentation/DeviceDrivers/Conceptual/NetworkDriver/2_IONetworkingFamily/IONetworkingFamily.html
http://dbmanagement.info/Books/MIX/OS_X_and_iOS_Kernel_Programming.pdf
https://www.fortinet.com/blog/threat-research/monitoring-macos--part-iii--monitoring-network-activities-using-.html
https://fortiguard.com/events/2270/learn-how-to-build-your-own-utility-to-monitor-malicious-behaviors-of-malware-on-macOS
https://github.com/slavaim/MacOSX-Network-Sockets-Filter
http://mirror.informatimago.com/next/developer.apple.com/documentation/Darwin/Conceptual/howto/kext_tutorials/hello_kext/hello_kext.html
https://www.blackhat.com/us-18/presenters/Yu-Wang.html
kernel control/event api usage
https://www.synack.com/2015/12/13/monitoring-process-creation-via-the-kernel-part-iii/
Best working model
https://github.com/LawlietRyuzakiCode/NKETest
http://hitcon.org/2013/download/[B1]%20Pedro_HiTCON%202013%20Presentation_v2.pdf
https://github.com/changpingc/kernet
IMP Packet Creation Source
enderunix Packet Creation Source
https://github.com/robbiehanson/CocoaAsyncSocket/tree/master/Examples/GCD
https://tools.ietf.org/html/rfc7230
https://developer.apple.com/documentation/security/certificate_key_and_trust_services?language=objc
http://openssl.cs.utah.edu/docs/apps/x509v3_config.html
https://docs.mitmproxy.org/stable/concepts-howmitmproxyworks/
http://technologeeks.com/course.jl?course=OSXRE
https://www.fastcompany.com/3042030/the-huge-web-security-loophole-that-most-people-dont-know-about-and-how-its-be
https://stackoverflow.com/questions/589622/how-does-a-root-ca-verify-a-signature
https://deliciousbrains.com/https-locally-without-browser-privacy-errors/
https://rednaga.io/2017/04/09/remote_kext_debugging/
http://www.robertopasini.com/index.php/2-uncategorised/628-osx-packaging-a-kernel-extension-for-distribution-and-installation
http://ddeville.me/2015/08/using-the-vmware-fusion-gdb-stub-for-kernel-debugging-with-lldb
https://objective-see.com/blog.html
https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KEXTConcept/KEXTConceptDebugger/debug_tutorial.html
https://forums.macrumors.com/threads/turn-off-verbose-bootup.1247361/
https://adimitrov.net/main/code/code/raw_packet.c
http://www.enderunix.org/docs/en/rawipspoof/
https://www.eit.lth.se/ppplab/IPHeader.htm#TOS,%20Type%20of%20Service
https://www.tenouk.com/download/pdf/Module39.pdf
https://developer.apple.com/library/archive/documentation/DeviceDrivers/Conceptual/IOKitFundamentals/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP0000018-BAJFFJAD
https://github.com/slavaim/MacOSX-Network-Sockets-Filter
https://www.blackhat.com/us-18/arsenal.html#learn-how-to-build-your-own-utility-to-monitor-malicious-behaviors-of-malware-on-macos
https://developer.apple.com/documentation/networkextension?language=objc
https://github.com/TrustRouter/TrustRouter/blob/master/client/kernelmode/MacOS/trustrouter/trustrouter.c
https://github.com/LawlietRyuzakiCode/NKETest/blob/master/TestFilter/TestFilter/TestFilter.c
https://objective-see.com/blog/blog_0x0B.html
http://www.ragingmenace.com/software/menumeters/
https://people.sissa.it/~inno/pubs/skb-reduced.pdf
http://haifux.org/lectures/122/FreeBSD_kernel_networking.pdf
http://www.zytrax.com/books/dns/ch15/
alternate packet forward and check
sudo lsof -iTCP -sTCP:LISTEN -n -P
netstat -a -n
sudo pfctl -s nat
sudo pfctl -F all -f /etc/pf.conf
echo "
rdr pass inet proto tcp from any to any port 80 -> 127.0.0.1 port 8080
rdr pass inet proto tcp from any to any port 443 -> 127.0.0.1 port 8443
" | sudo pfctl -ef -
nettop
sudo tcpdump -i en0 -p -vv -A ip and host 192.168.1.92
sudo tcpdump -i en0 -p -vv -A ip
sudo tcpdump -i en0 -p -vv -A ip and net 192.0.2.0/24

How to get ssh connection with docker container on OSX(boot2docker)

I use docker on OSX with boot2docker.
I want to get an Ssh connection from my terminal into a running container.
But I can't do this :(
I think it's because Docker is running in a virtual machine.
There are several things you must do to enable ssh'ing to a container running in a VM:
install and run sshd in your container (example). sshd is not there by default because containers typically run only one process, though they can run as many as you like.
EXPOSE a port as part of creating the image, typically 22, so that when you run the container, the daemon connects to the EXPOSE'd port inside the container and something can be exposed on the outside of the container.
When you run the container, you need to decide how to map that port. You can let Docker do it automatically or be explicit. I'd suggest being explicit: docker run -p 42222:22 ... which maps port 42222 on the VM to port 22 in the container.
Add a portmap to the VM to expose the port to your host. e.g. when your VM is not running, you can add a mapping like this: VBoxManage modifyvm "boot2docker-vm" --natpf1 "containerssh,tcp,,42222,,42222"
Then from your host, you should be able to ssh to port 42222 on the host to reach the container's ssh daemon.
Here's what happens when I perform the above steps:
$ VBoxManage modifyvm "boot2docker-vm" --natpf1 "containerssh,tcp,,42222,,42222"
$ ./boot2docker start
[2014-04-11 12:07:35] Starting boot2docker-vm...
[2014-04-11 12:07:55] Started.
$ docker run -d -p 42222:22 dhrp/sshd
Unable to find image 'dhrp/sshd' (tag: latest) locally
Pulling repository dhrp/sshd
2bbfe079a942: Download complete
c8a2228805bc: Download complete
8dbd9e392a96: Download complete
11d214c1b26a: Download complete
27cf78414709: Download complete
b750fe79269d: Download complete
cf7e766468fc: Download complete
082189640622: Download complete
fa822d12ee30: Download complete
1522e919ec9f: Download complete
fa594d99163a: Download complete
1bd442970c79: Download complete
0fda9de88c63: Download complete
86e22a5fdce6: Download complete
79d05cb13124: Download complete
ac72e4b531bc: Download complete
26e4b94e5a13b4bb924ef57548bb17ba03444ca003128092b5fbe344110f2e4c
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
26e4b94e5a13 dhrp/sshd:latest /usr/sbin/sshd -D 6 seconds ago Up 3 seconds 0.0.0.0:42222->22/tcp loving_einstein
$ ssh root#localhost -p 42222
The authenticity of host '[localhost]:42222 ([127.0.0.1]:42222)' can't be established.
RSA key fingerprint is ....
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[localhost]:42222' (RSA) to the list of known hosts.
root#localhost's password: screencast
Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.12.1-tinycore64 x86_64)
* Documentation: https://help.ubuntu.com/
The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.
root#26e4b94e5a13:~# exit
logout
So that shows ssh->localhost 42222->VM port 42222->container port 22.
Docker has added the docker exec command to Docker 1.3.0. You can connect to a running container using the following:
docker exec -it <container id> /bin/bash
That will connect to a bash prompt on the running container.
If you just want to get into the running container, you may consider using nsenter. Here is a simple bash script (suggested by Chris Jones) that you can use to enter into a docker container. Save it somewhere in your $PATH as docker-enter and chmod +x
#!/bin/bash
set-e
# Check for nsenter. If not found, install it
boot2docker ssh '[ -f /var/lib/boot2docker/nsenter ] || docker run --rm -v /var/lib/boot2docker/:/target jpetazzo/nsenter'
# Use bash if no command is specified
args=$#
if[[ $# = 1 ]]; then
args+=(/bin/bash)
fi
boot2docker ssh -t sudo /var/lib/boot2docker/docker-enter "${args[#]}"
Then you can run docker-enter 89af3d (or whatever configuration you want to enter)
A slightly modified variant of Michael's answer that just requires the container you want to enter be named (APPNAME):
boot2docker ssh '[ -f /var/lib/boot2docker/nsenter ] || docker run --rm -v /var/lib/boot2docker/:/target jpetazzo/nsenter'
boot2docker ssh -t sudo /var/lib/boot2docker/docker-enter $(docker ps | grep $APPNAME | awk '{ print $1 }')
I've tested this for an Ubuntu 16.04 image running on a host with the same OS, Docker 18.09.2, it should also work for boot2Docker with minor modifications.
Build the image.
Run it in background container (youruser may be root):
$ docker run -ditu <youruser> <imageId>
Attach to it with a shell:
$ docker exec -it <containerId> /bin/bash
Install the openssh-server (sudo only needed if youruser is not root, the command may differ for boot2Docker):
$ sudo apt-get install -y openssh-server
Run it:
$ sudo service ssh start
(The following step is optional, if youruser has a password, you can skip it and provide the password at each ssh connection).
Create a RSA key on the client host:
$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/youruser/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/youruser/.ssh/id_rsa.
Your public key has been saved in /home/youruser/.ssh/id_rsa.pub.
On the docker image, create a directory $HOME/.ssh:
$ cd
$ mkdir .ssh && cd .ssh
$ vi authorized_keys
Copy and paste the content of $HOME/.ssh/id_rsa.pub on the client machine to authorized_keys on the docker image and save the file.
(End of optional step).
Jot down your image's IP address:
$ cat /etc/hosts
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2 63448863ac39
^^^^^^^^^^ this
Now the connection from the client host should be effective:
$ ssh 172.17.0.2
Enter passphrase for key '/home/youruser/.ssh/id_rsa':
Welcome to Ubuntu 16.04.6 LTS (GNU/Linux 4.15.0-46-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
Last login: Fri Apr 5 09:50:30 2019 from 172.17.0.1
Of course you can apply the above procedure non-interactively in your Dockerfile.

Resources