HTTPS 를 위한 Private SSL

Web server certificates 과정

Securing a web site with a server certificate 단계

  1. 비밀키를 생성한다.
  2. 비밀키로 CSR certificate siging requests 을 생성한다.
  3. CSR 을 CA 로 사인한다.
  4. 사인한 CERT 를 받고 설치한다.

1. 비밀키를 생성한다.

rsa 를 사용해 4096크기 비밀키를 생성한다.

1
2
3
4
5
# cd /etc/ssl/private 
# openssl genrsa -out my_rsa.key 4096
Generating RSA private key, 4096 bit long modulus (2 primes)

# chmod 0600 private/my_rsa.key
1
# chmod 0600 private/my_rsa.key

Public Key 생성

1
명령: openssl rsa -in [private key 파일명] -pubout -out [파일명]
1
# openssl rsa -in my_rsa.key -pubout -out my_rsa.pub 

2. Create a CSR(certificate signing request) from this key,

인증서 발급을 위한 필요한 정보를 담고 있는 인증서 신청서를 작성한다.

1
명령어 : openssl req -new -key [private key 파일명] -out [파일명]

비밀키에서 CSR 파일 작성을 요청하면 아래 내용을 묻는다.

1
# openssl req -new -sha256 -key ./my_rsa.key -out ./my_rsa.csr 
1
# openssl req -new -key private.key -out private.csr

인증서 발급을 위한 필요한 정보를 담고 있는 인증서 신청 형식 데이터 이다.

  • Country Name (국가코드) KR
  • State or Province Name (시/도의 전체이름) Seoul
  • Locality Name (시/군/구 등의 이름) Songpa-gu
  • Organization (회사이름) XXXX
  • Organization Unit (부서명) Server
  • Common Name (SSL 인증서를 설치할 서버의 Full Domain) www.xxxx.com
      • Common Name 에는 인증서를 설치할 사이트의 도메인의 이름을 넣어야 한다. (ip, port, http, https 포함불가능)

4. CA 인증한 CRT 인증서 만들기

CSR 을 CA에서 인증해 CRT 파일을 생성한다. 여기서는 비밀키와 CSR 요청서를 바탕으로 CRT 인증서를 생성한다.

1
명령어 : openssl req -x509 -days [기간] -key [private key 파일명] -in [csr 파일명] -out [파일명] -days [기간]

x509 를 이용하고 365일 사용 가능한 crt 인증서를 생성한다.

1
openssl req -x509 -days 365 -key my_rsa.key -in my_rsa.csr -out my_rsa.crt -days 365

생성한 혹은 CA에서 받은 CRT 파일은 아래 같이 확인해 볼 수 있다.

1
openssl x509 -text -in yourdomain.crt -noout

5. CRT 파일을 PEM 파일로 변환한다.

1
openssl x509 -in mycommoncrt.crt -out mycommonpem.pem -outform PEM 

[Tip] 인증서 Config 파일 (test.conf)

위에서 만들다 보면 계속 같은 내용을 써야 한다. 그래서 그 부분을 파일로 만들어 놓고 csr, crt 생성할때 사용하면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[req]
default_bits = 2048
prompt = no
default_md = sha256
req_extensions = req_ext
distinguished_name = dn

[dn]
C=KR
ST=Seoul
L=Seoul
O=COMPANY
OU=DEV
emailAddress=test@test.com
CN = testmachine

[req_ext]
subjectAltName = @alt_names

[alt_names]
IP.1 = 111.111.111.111
DNS.1 = test.com

csr 을 생성한다.

1
openssl req -new -key private.key -out private.csr -config test.conf

csr, crt 파일을 생성한다.

1
openssl req -x509 -days 365 -key private.key -in private.csr -out mycommoncrt.crt -days 365 -config test.conf

그리고 이렇게 해서 인증서를 만들었을때 subjectAltName 이 안들어간다 . 그 부분이 필요할 경우에는 이렇게 명령어를 사용하면 된다.

1
openssl req -x509 -days 365 -key private.key -in private.csr -out mycommoncrt.crt -days 365 -config test.conf -extensions req_ext

openssl 팁 몇가지

CRT 파일 확인

openssl x509 -text -noout -in <인증서파일> : 인증서 내용을 볼수 있다.

Verifying Your Keys Match

1
2
3
openssl pkey -pubout -in .\private.key | openssl sha256
openssl req -pubkey -in .\request.csr -noout | openssl sha256
openssl x509 -pubkey -in .\certificate.crt -noout | openssl sha256

NGINX 웹 서버 TLS 암호화 추가

개인키와 TLS 인증서 crt 파일을 사용한다.

1
2
$ sudo mkdir /etc/nginx/tls/private
$ mv my_rsa.key my_rsa.crt /etc/nginx/tls/private
  1. 개인 키는 /etc/nginx/tls/private/my_rsa.key 파일에 저장됩니다.
  2. 개인 키 및 CSR(인증서 서명 요청) 생성 및 CA(인증 기관)에서 인증서 TLS 인증서는
    • /etc/nginx/tls/private/example.com.crt 파일에 저장됩니다.
1
2
3
4
5
6
7
server {
listen 443 ssl;
server_name www.thinkbee.kr;
root /home/qkboo/Home/www/thinkbee.kr/;
ssl_certificate /etc/nginx/tls/private/my_rsa.crt;
ssl_certificate_key /etc/nginx/tls/private/my_rsa.key;
}

참고

  1. Howto – Install a self signed web server certificate
  2. openssl quick reference guide
  3. Openssl로 SSL 을 위한 인증서 발급하기 (HTTPS),blog
  4. Nginx - HTTPS and Certificate SSL,blog
  5. NodeJS와 Nginx 웹 서버,blog

parted로 Partition, Format하기

새 디스크 / USB 저장장치를 리눅스 계열에서 사용하고자 할 때.

디스크 확인 lsblk

lsblk 명령은 디바이스 장치가 마운트 된 곳을 출력해 준다.

1
2
3
4
5
6
7
8
NAME                      MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
loop0 7:0 0 63.3M 1 loop /snap/core20/1828
loop1 7:1 0 91.8M 1 loop /snap/lxd/23991
sda 8:0 0 119.2G 0 disk
├─sda1 8:1 0 1M 0 part
├─sda2 8:2 0 1G 0 part /boot
└─sda3 8:3 0 118.2G 0 part
└─ubuntu--vg-ubuntu--lv 253:0 0 118.1G 0 lvm /

새 디스크 장치(SSD, HDD, USB 등) 를 붙이고 다시 확인하면 새로운 디스크는 sd[a-z] 형식으로 표현된다.

아래 sdb 는 현재 파티션이 1개 존재하는 상태이다.

1
2
3
4
5
6
7
8
9
10
11
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
loop0 7:0 0 63.3M 1 loop /snap/core20/1828
loop1 7:1 0 91.8M 1 loop /snap/lxd/23991
sda 8:0 0 119.2G 0 disk
├─sda1 8:1 0 1M 0 part
├─sda2 8:2 0 1G 0 part /boot
└─sda3 8:3 0 118.2G 0 part
└─ubuntu--vg-ubuntu--lv 253:0 0 118.1G 0 lvm /
sdb 8:16 0 931.5G 0 disk
└─sdb1 8:17 0 931.5G 0 part

[USB 장치]

USB 장치는 mmcblk[0-9] 형식으로 표시된다. 참고 Raspberry Pi:mmcblk

1
2
3
4
5
6
7
8
9
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 119.2G 0 disk
├─sda1 8:1 0 84.5G 0 part
└─sda6 8:6 0 28.9G 0 part /
mmcblk0 179:0 0 7.5G 0 disk
├─mmcblk0p2 179:2 0 6.8G 0 part /media/qkboo/ROOT
├─mmcblk0p3 179:3 0 486.1M 0 part
└─mmcblk0p1 179:1 0 200M 0 part /media/qkboo/EFI

parted 사용

파티션 및 포맷을 위해 마운트된 파티션을 언마운트 한다. parted 는 상호작용 프롬프트에서 사용하거나 단일 명령어로 사용할 수 있다.

parted 프롬프트 사용

[ext4 파티션 생성]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
sudo parted /dev/sdb
(parted) print
Number Start End Size File system Name Flags
1 0.00GB 32.0GB 32.0GB

(parted) mklabel gpt
Warning: The existing disk label on /dev/sda will be destroyed and all data on
this disk will be lost. Do you want to continue?
Yes/No? y

(parted) unit GB
(parted) mkpart primary 0 1000.0GB #디스크 크기 입력

(parted) print
Number Start End Size File system Name Flags
1 0.00GB 32.0GB 32.0GB primary lvm
(parted) quit

[fat32 파티션 생성]

USB 스토리지는 아래 같이 나타난다. 다음은 USB 파티션에 fat32 파일시스템을 프롬프트로 생성하고 있다.

1
2
3
4
5
sudo parted /dev/mmcblk0
(parted) mklabel msdos
(parted) mkpart primary fat32 1MiB 100%
(parted) set 1 boot on
(parted) quit

쉘에서 parted 명령 사용

parted 를 쉘 명령으로 사용해 단계별로 파티션을 생성할 수 있다.

1
2
3
sudo parted /dev/mmcblk0 rm 1
sudo parted /dev/mmcblk0 rm 2
sudo parted /dev/sdc mkpart primary ext3 4MiB 100%

Format, Mount & fstab

생성한 파티션에 시스템 지원 파일 시스템을 생성해야 한다. 해당 파일 시스템으로 파티션을 포맷한 후에 지정한 디렉토리에 마운트를 해서 사용하면 된다. 지속적인 사용을 위해서 /etc/fstab 에 파티션을 마운트 포인트로 등록하면 재시동 후에도 동일한 폴더에 마운트 된다.

mkfs

mkfs 명령은 파일 시스템에 따랴서 -t 옵션에 파일시스템을 지시하거나 mkfs.[FS] 형식을 명령을 바로 쓰기도 한다.

다음을 sdb1 파티션을 ext4 로 포맷하고 있다.

1
sudo mkfs -t ext4 /dev/sdb1

[USB vfat 파일시스템 생성]

1
sudo mkfs -V -t vfat /dev/mmcblk0p1

fstab 에 등록

/etc/fstab 에 새로 포맷한 디스크 경로를 추가 한다.

1
2
3
4
5
6
# HDD
/dev/sdb1 /Home2 ext4 defaults 0 1

# USB LV volume
/dev/vg_usb/dbvol /data ext4 defaults 0 1
/dev/vg_usb/workvol /home/pi/work ext4 defaults 0 1

참고

WSL2 잘 사용하기

WSL2 이용 Linux 사용시 쓸만한 팁

  1. wsl 사용 명령
  2. WSL 쉘 사용
  3. wsl 하위 시스템 디렉토리
  4. wsl 구성 파일
  5. wsl 외부 디스크 마운트 하기
  6. wsl 배포본 이름 변경하기

1. wsl 사용 명령

윈도우즈 하위 시스템 목록

1
2
3
4
5
# Linux용 Windows 하위 시스템의 목록
PS> wsl -l

# Linux용 Windows 하위 시스템의 상태를 표시
PS> wsl --status

wsl 재시작

혹은 윈도우 서비스를 재시작할 수 있다. Windows에서 PowerShell을 관리자 권한으로 열고 다음 명령을 실행하면 됩니다.

1
PS> Restart-Service LxssManager

wsl 종료

하위 시스템 배포본을 지정해 종료하려면 -t <Distro> 명령을 사용한다.

1
2
3
4
PS> wsl -l
Ubuntu-20.04(기본값)

PS> wsl -t Ubuntu-20.04

wsl shutdown

모든 하위 시스템을 종료 시키려면 --shutdown 명령을 사용한다. --shutdown 명령은 실행 중인 모든 배포과 WSL 2 경량 유틸리티 가상 머신을 즉시 종료한다.

1
PS> wsl --shutdown

Unregister

Window store 에서 설치한 배포본을 삭제해도 wsl 의 Distro 목록에는 남아 있다. 이것은 --unregistre 명령으로 제거할 수 있다.

1
2
3
4
PS> wsl -l --all
Linux용 Windows 하위 시스템 배포:
Ubuntu-20.04(기본값)
Ubuntu-22.04

--unregistre 명령으로 제거한 Distro 등록을 해제한다.

1
2
3
4
5
6
7
PS> wsl --unregister Ubuntu-22.04
등록 취소 중입니다.
작업을 완료했습니다.

PS> wsl -l
Linux용 Windows 하위 시스템 배포:
Ubuntu-20.04(기본값)

2. WSL 쉘 사용

--system : 현재 시스템의 distro의 셸을 시작한다.

1
2
3
4
5
PS> wsl --system
wslg [ /mnt/c/Users/daddy ]$ cd
wslg [ ~ ]$
wslg [ ~ ]$ exit
logout

--exec, -e: 시스템 distro의 명령을 현재 PowerShell에서 실행한다.

1
2
3
PS> wsl -e bash
()qkboo:/mnt/c/Users/daddy$ cd
()qkboo:~$

wsl IP 주소

1
wsl hostname -I

2. WSL 하위 시스템 디렉토리

윈도우즈와 하위 시스템의 디렉토리를 Host 의 프로그램 들에서 사용할 수 있다.

탐색기에서 직접 접근하기

윈도우즈에서 네트워크 경로로 WSL 하위 시스템 디렉토리를 접근할 수 있다.

1
\\wsl$\<Distribution>:

예를 들어 하위 시스템 이름이 Ubuntu-20.04 이고 계정이 qkboo 이라면 탐색기에서 qkboo 계정의 홈디렉토리를 이렇게 접그할 수 있다.

1
\\wsl$\Ubuntu-20.04\home\qkboo

아래는 윈도우즈 탐색기에서 wsl 홈디렉토리를 접근한 캡쳐 화면인다.

터미널에서 홈디렉토리 탐색기 열기

터미널에서 윈도우즈 탐색기를 직접 열 수 있다.

1
$ explorer.exe .

VisualStudio Code 에서 현재 디렉토리를 연다.

1
$ code.exe .

3. WSL 고급 설정 구성

배포본 구성 파일 wsl.conf 와 전역 구성 파일 .wslconfig 이 있다.

전역 구성 파일 .wslconfig

wslconfig 예제 파일

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Settings apply across all Linux distros running on WSL 2
[wsl2]

# Limits VM memory to use no more than 4 GB, this can be set as whole numbers using GB or MB
memory=4GB

# Sets the VM to use two virtual processors
processors=2

# Specify a custom Linux kernel to use with your installed distros. The default kernel used can be found at https://github.com/microsoft/WSL2-Linux-Kernel
kernel=C:\\temp\\myCustomKernel

# Sets additional kernel parameters, in this case enabling older Linux base images such as Centos 6
kernelCommandLine = vsyscall=emulate

# Sets amount of swap storage space to 8GB, default is 25% of available RAM
swap=8GB

# Sets swapfile path location, default is %USERPROFILE%\AppData\Local\Temp\swap.vhdx
swapfile=C:\\temp\\wsl-swap.vhdx

# Disable page reporting so WSL retains all allocated memory claimed from Windows and releases none back when free
pageReporting=false

# Turn off default connection to bind WSL 2 localhost to Windows localhost
localhostforwarding=true

# Disables nested virtualization
nestedVirtualization=false

# Turns on output console showing contents of dmesg when opening a WSL 2 distro for debugging
debugConsole=true

배포본 구성 파일 wsl.conf

  • 위치: /etc/wsl.conf
  • wsl1, wsl2 배포본에 대한 구성을 지정한다.
  • 단, Windows 빌드 17093 이상에서만 사용할 수 있다.
  • systemd 지원
  • automount 지원
    DrvFS 지원
    interop 설정 등등
  • wsl.conf 구성 설정

wsl.conf 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Automatically mount Windows drive when the distribution is launched
[automount]

# Set to true will automount fixed drives (C:/ or D:/) with DrvFs under the root directory set above. Set to false means drives won't be mounted automatically, but need to be mounted manually or with fstab.
enabled = true

# Sets the directory where fixed drives will be automatically mounted. This example changes the mount location, so your C-drive would be /c, rather than the default /mnt/c.
root = /

# DrvFs-specific options can be specified.
options = "metadata,uid=1003,gid=1003,umask=077,fmask=11,case=off"

# Sets the `/etc/fstab` file to be processed when a WSL distribution is launched.
mountFsTab = true

# Network host settings that enable the DNS server used by WSL 2. This example changes the hostname, sets generateHosts to false, preventing WSL from the default behavior of auto-generating /etc/hosts, and sets generateResolvConf to false, preventing WSL from auto-generating /etc/resolv.conf, so that you can create your own (ie. nameserver 1.1.1.1).
[network]
hostname = DemoHost
generateHosts = false
generateResolvConf = false

# Set whether WSL supports interop process like launching Windows apps and adding path variables. Setting these to false will block the launch of Windows processes and block adding $PATH environment variables.
[interop]
enabled = false
appendWindowsPath = false

# Set the user when launching a distribution with WSL.
[user]
default = DemoUser

# Set a command to run when a new WSL instance launches. This example starts the Docker container service.
[boot]
command = service docker start

4. wsl 외부 디스크 마운트 하기

윈도우즈 wsl 에서 리눅스 파티션 혹은 USB 파티션 디스크를 마운트해서 사용하려고 한다.

  1. 관리자 모드에서 Powershell 을 연다.

파워쉘에서 연결된 디스크 목록을 확인한다.

1
2
3
4
5
6
7
PS> GET-CimInstance -query "SELECT * from Win32_DiskDrive"

DeviceID Caption Partitions Size Model
-------- ------- ---------- ---- -----
\\.\PHYSICALDRIVE0 ST2000DM008-2FR102 1 2000396321280 ST2000DM008-2FR102
\\.\PHYSICALDRIVE1 WDS500G3X0C-00SJG0 4 500105249280 WDS500G3X0C-00SJG0
\\.\PHYSICALDRIVE2 ATA HGST HTS721010A9 USB Device 1 1000202273280 ATA HGST HTS721010A9...
  1. 관리자 모드 PowerShell 에서 마운트할 Device ID를 마운트 한다.

--bare 를 사용해 마운트 여부를 확인할 수 있다.

1
PS> wsl --mount \\.\PHYSICALDRIVE2 --bare
  1. WSL 리눅스 터미널에서 디스크를 확인한다.

아래 같이 마운트를 실행한다.

1
2
3
4
PS> wsl --mount \\.\PHYSICALDRIVE2 -type ext4
디스크가 '/mnt/wsl/PHYSICALDRIVE2'(으)로 탑재되었습니다.
참고: /etc/wsl.conf에서 automount.root 설정을 수정한 경우 위치가 달라집니다.
디스크를 분리하고 분리하려면 'wsl.exe --unmount \\.\PHYSICALDRIVE2'을 실행하십시오.

파티션을 마운트 한다면

1
2
3
4
PS> wsl --mount \\.\PHYSICALDRIVE2 -p 1   # partition 1
디스크가 '/mnt/wsl/PHYSICALDRIVE2p1'(으)로 탑재되었습니다.
참고: /etc/wsl.conf에서 automount.root 설정을 수정한 경우 위치가 달라집니다.
디스크를 분리하고 분리하려면 'wsl.exe --unmount \\.\PHYSICALDRIVE2'을 실행하십시오.

연결된 디스크가 sdd 에 표시된다.

1
2
3
4
5
6
7
~$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 363.1M 1 disk
sdb 8:16 0 8G 0 disk [SWAP]
sdc 8:32 0 256G 0 disk /mnt/wslg/distro
sdd 8:48 0 931.5G 0 disk
└─sdd1 8:49 0 931.5G 0 part

어떠 파일 시스템인지 확인하려면 lsblk -f 명령을 사용한다.

1
2
3
4
5
6
7
8
~$ lsblk -f
NAME FSTYPE LABEL UUID FSAVAIL FSUSE% MOUNTPOINT
sda ext4
sdb swap 44bcbb9a-3a2c-44db-99e4-9c14dec69098 [SWAP]
sdc ext4 3255683f-53a2-4fdf-91cf-b4c1041e2a62 159.1G 32% /mnt/wslg/distro
sdd
└─sdd1 ext4 9b3c51ab-a49b-41c7-a105-fb9d47a86476
(3.11.1)qkboo@desktop-goyangi:~$

df 명령으로 확인해 보자,

1
2
3
4
5
6
7
8
9
10
s$ df -h
Filesystem Size Used Avail Use% Mounted on
none 16G 4.0K 16G 1% /mnt/wsl
drivers 465G 397G 69G 86% /usr/lib/wsl/drivers
none 16G 0 16G 0% /usr/lib/wsl/lib
/dev/sdc 251G 80G 160G 34% /

...

/dev/sdd1 917G 852G 19G 98% /mnt/wsl/PHYSICALDRIVE2p1

6. 배포본 이름 변경하기

  1. 먼저 모든 WSL 실행 배포본을 종료한다.

현재 배포본 Ubuntu 20.04 인데 do-os-relase 업그레이드로 22.04 로 완료된 상태이다. 하지만 배포본 이름은 20.04 라서 이름을 22.04 로 변경하려고 한다.

1
2
3
PS> wsl -l
Linux용 Windows 하위 시스템 배포:
Ubuntu-20.04(기본값)
  1. 레지스트리 편집기를 열고 다음 위치로 이동한다.

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Lxss

  1. Lxss 항목 중 배포본 레지스트리를 선택하면 아래 같은 내용에서 *DistributionName 을 찾아 변경한 배포본 이름으로 바꾸고 저장한다.
  1. 변경된 이름을 저장하고 wsl 배포본 목록을 확인한다.
1
2
3
PS> wsl -l
Linux용 Windows 하위 시스템 배포:
Ubuntu-22.04(기본값)

— 참고

  1. WSL 시작하기: https://github.com/wslhub/wsl-firststep/

WSL 에서 CUDA 사용을 위한 User Guide

CUDA on WSL User Guide

2021/12/05 일 현재

1. WSL 이란

네이티브 리눅스 앱을 Windows 11 and later OS build 에서 실행할 수 있는 Windows Subsystem for Linux 이다.

WSL 1 vs. WSL 2

WSL2 is the second generation of WSL that offers the following benefits:

  • Linux applications can run as is in WSL2. WSL 2 is characteristically a VM with a Linux WSL Kernel in it that provides full compatibility with mainstream Linux kernel allowing support for native Linux applications including popular Linux distros.

  • Faster file system support and that’s more performant.

  • WSL 2 is tightly integrated with the Microsoft Windows operating system, which allows it to run Linux applications alongside and even interop with other Windows desktop and modern store apps.

2. NVIDIA GPU Accelerated Computing on WSL 2

WSL 2에서 마이크로소프트는 NVIDIA CUDA 및 기타 컴퓨팅 프레임워크와 기술과 함께 데이터 과학, 머신러닝 및 추론 솔루션을 위한 GPU 가속 컴퓨팅을 가능하게 하는 GPU 반가상화 기술을 도입했다. WSL 유사 환경 또는 WSL 2에서 CPU 개입을 줄이면서 GPU에서 더 많은 병렬 작업을 파이프라인으로 수행할 수 있으므로 거의 네이티브에 가까운 성능을 제공한다. NVIDIA 드라이버 지원은 CUDA 및 관련 컴퓨팅 소프트웨어 스택에서 멈추지 않습니다. 다이렉트 ML 지원과 함께 DX12 API를 지원하여 WSL 2에서 그래픽을 활성화하는 DirectX 지원이 있습니다.

Illustration of the possibilities with NVIDIA CUDA software stack on WSL 2

3. WSL2 시작

WSL2 요구사항

  • Geforce, Quadro 제품 계열에서 Pascal 또는 최신 GPU 구조를 WDDM모드로 SKU를 사용할 수 있다.
  • 최신 WSL 커널 로 5.10.16.3 이상을 권장한다. (최소 4.19.121+ 이상)
  • Windows 11 에서는 윈도우 인사이더 프로그램 가입이 필요 없다.
  • Windows 10 에서는 윈도우 인사이더 프리뷰 프로그램이 필요하다.

Step 1: Install NVIDIA Driver for GPU Support

윈도우 11 그래픽 드라이버로 NVIDIA GeForce Game Ready or NVIDIA RTX Quadro 를 설치한다.

3.3. Step 2: Install WSL 2

윈도우 터미널 / 커맨드 라인 / 파워쉘 에서 WSL을 설치

1
wsl.exe --install

Ensure you have the latest WSL kernel:

1
wsl.exe --update

3.4. Setting Up a Linux Development Environment

기본으로 WSL2는 Ubuntu 가 설치되어 온다. 다른 배포본은 MS store에서 설치. wsl 시작.

1
wsl.exe

업데이트를 위한 WSL 명령:

4. Getting Started with CUDA on WSL 2

WSL2에서 CUDA 를 지원하려면 CUDA Toolkit이 설치되고 cuDNN도 설치해야 한다.

4.1 WSL에서 CUDA Toolkit을 설치한다

WSL 2 에서 CUDA application을 실행하려면 CUDA toolkit for Linux 를 설치해야 한다.

CUDA Toolkit 11.5 를 다운로드하고 설치한다.

1
2
3
4
5
6
7
wget https://developer.download.nvidia.com/compute/cuda/repos/wsl-ubuntu/x86_64/cuda-wsl-ubuntu.pin
sudo mv cuda-wsl-ubuntu.pin /etc/apt/preferences.d/cuda-repository-pin-600
wget https://developer.download.nvidia.com/compute/cuda/11.5.1/local_installers/cuda-repo-wsl-ubuntu-11-5-local_11.5.1-1_amd64.deb
sudo dpkg -i cuda-repo-wsl-ubuntu-11-5-local_11.5.1-1_amd64.deb
sudo apt-key add /var/cuda-repo-wsl-ubuntu-11-5-local/7fa2af80.pub
sudo apt-get update
sudo apt-get -y install cuda

4.2 cudnn 설치

CUDA Toolkit 버전에 대응하는 cuDNN 을 설치해야 한다.

1
2
3
sudo apt install libcudnn8
sudo apt install libcudnn8-dev
sudo apt-get install libcudnn8-samples

4.3 CUDA 애플리케이션

윈도우에 CUDA 애프리케이션이 있아면 다음 같이 WSL에서 실행해 보자

1
2
3
$ cd /mnt/c/Users/<username>/Desktop
$ cp /mnt/c/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.5/extras/demo_suite/deviceQuery.exe ~/
$ ./deviceQuery.exe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
(tf25gpu_p39)~$ nvidia-smi
Sun Dec 5 02:29:22 2021
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 510.00 Driver Version: 510.06 CUDA Version: 11.6 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|===============================+======================+======================|
| 0 NVIDIA GeForce ... On | 00000000:09:00.0 On | N/A |
| 0% 43C P8 20W / 320W | 1179MiB / 11264MiB | N/A Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=============================================================================|
| No running processes found |
+-----------------------------------------------------------------------------+

4.4 Building CUDA Samples

CUDA 샘플을 빌드해서 실행해 보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
(tf25gpu_p39)/usr/local/cuda-11.5/samples/4_Finance/BlackScholes$ ./BlackScholes
[./BlackScholes] - Starting...
GPU Device 0: "Pascal" with compute capability 6.1

Initializing data...
...allocating CPU memory for options.
...allocating GPU memory for options.
...generating input data in CPU mem.
...copying input data to GPU mem.
Data init done.

Executing Black-Scholes GPU kernel (512 iterations)...
Options count : 8000000
BlackScholesGPU() time : 0.234201 msec
Effective memory bandwidth: 341.586668 GB/s
Gigaoptions per second : 34.158667

BlackScholes, Throughput = 34.1587 GOptions/s, Time = 0.00023 s, Size = 8000000 options, NumDevsUsed = 1, Workgroup = 128

Reading back GPU results...
Checking the results...
...running CPU calculations.

Comparing the results...
L1 norm: 1.741792E-07
Max absolute error: 1.192093E-05

Shutting down...
...releasing GPU memory.
...releasing CPU memory.
Shutdown done.

[BlackScholes] - Test Summary

NOTE: The CUDA Samples are not meant for performance measurements. Results may vary when GPU Boost is enabled.

Test passed
(tf25gpu_p39)/usr/local/cuda-11.5/samples/4_Finance/BlackScholes$

참고

Windows Powershell: 관리자 administrator 계정 활성화와 Openssh 서버 활성화

외부에서 원격접속해서 관리자 명령을 실행하려면 관리자 권한이 필요하다. 윈도우 파워쉘에서 openssh 설치하고 시작/재시작 등의 작업을 위해서는 administrator 계정이 활성화 되어야 한다.

  1. openssh windows server 설치
  2. administrator 계정 활성화
  3. 원격 ssh 접속

Powershell Openssh 설치

윈도우 파워쉘에서 openssh 설치

administrator 계정

명령행을 관리자 권한으로 실행하고 아래 명령 수행. 어드민 계정이 활성화 상태로 변경됩니다.
어드민 계정이 활성화되어 있기 때문에 Administrator 계정으로 로그인이 가능해집니다.

윈도우즈 administrator 활성화

administrator 게정을 활성화 하려면

  1. 파웨쉘을 관리자로 실행해 다음 같이 실행한다.
1
> net user administrator /active:yes

패스워드 변경은 사용자 계정 변경에서 ‘다른 계정 관리’

  1. 관리자 권한으로 실행할 명령 앞에 runas 명령을 붙여 실행한다.

파워쉘에서 관리자로 명령을 실행하려면 runas 명령을 사용한다.

1
runas.exe /savecred /user:administrator "%sysdrive%\testScripts\testscript1.ps1"

참고

  1. openssh 서버 구성: https://docs.microsoft.com/ko-kr/windows-server/administration/openssh/openssh_server_configuration
  2. https://docs.microsoft.com/ko-kr/powershell/scripting/learn/remoting/ssh-remoting-in-powershell-core?view=powershell-7.1
  3. 윈도우즈 서비스 만들기: https://docs.microsoft.com/ko-kr/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer

WSL 파일시스펨, 네트워크

WSL 파일시스템

윈도우와 WSL 사이의 파일 시스템 공유

WSL 데이터 공간

Windows에 WSL 패키지는 아래의 Packages 폴더 안의 어딘가에 위치한다.

1
C:\Users\[사용자명]\AppData\Local\Packages\

Ubuntu 깔았다면 Packages폴더 아래에 Ubuntu라는 단어가 들어간 폴더명이 보일 것이다. 바로 그 폴더가 Ubuntu WSL의 위치다.

1
2
3
4
5
6
7
8
9
10
11
PS C:\Users\daddy> ls .\AppData\Local\Packages\

Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2020-11-01 오후 10:45 1527c705-839a-4832-9118-54d4Bd6a0c89_cw5n1h2txyewy
d----- 2020-11-01 오후 10:31 ActiveSync
d----- 2020-11-12 오전 8:07 adobe.acrobatreaderdc.protectedmode
d----- 2020-11-01 오후 10:45 c5e2524a-ea46-4f67-841f-6a9465d9d515_cw5n1h2txyewy
d----- 2021-02-16 오후 7:52 CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc
d----- 2021-02-17 오후 4:58 CanonicalGroupLimited.Ubuntu20.04onWindows_79rhkp1fndgsc
d----- 2020-11-01 오후 10:45 E2A4F912-2574-4A75-9BB0-0D023378592B_cw5n1h2txyewy

위 패키지 경로에서 LocalState 폴더 안의 rootfs 폴더가 바로 WSL1의 Root와 동일한 경로이다.

1
2
3
4
5
PS C:\Users\daddy> ls .\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu20.04onWindows_79rhkp1fndgsc\LocalState\

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2021-02-17 오후 5:34 1206910976 ext4.vhdx

권한문제

윈도우와 리눅스는 서로 다른 권한 매커니즘을 가지므로 윈도우 탐색기 상에서 그냥 WSL 경로로 파일을 옮기면 권한이 이상해진다. 가능하면 WSL 로그인후에 사용한다.

탐색기로 홈디렉토리 열기

현재 Working Directory를 네크워크를 통해 Windows 탐색기로 여는 방법
아래의 명령어를 WSL에서 실행하면 현재 작업 중인 위치를 네트워크 연결을 통해서 Windows에서 열어준다.

1
explorer.exe .

WSL 네트워크

DHCP

https://stackoverflow.com/questions/61002681/connecting-to-wsl2-server-via-local-network

참고

WSL 설치

WLS 설치

https://docs.microsoft.com/ko-kr/windows/wsl/install-win10#manual-installation-steps

https://www.44bits.io/ko/post/wsl2-install-and-basic-usage

WSL 에러

가상머신 에러

wsl2 코드 4294967295

Windows 기능 추가/삭제를 이용해 1 Linux 하위시스템, 2 가상머신 껏다 켜는 방법
https://bluenotes.kr/272

wls2 삭제후 재 설치
https://hyelmy.github.io/%EB%81%84%EC%A0%81%EB%81%84%EC%A0%81/honeytips2/

https://blogger.pe.kr/853

재시작

여러가지 방법이 있지만 대부분의 Windows에서 동작하는 방법은 먼저 PowerShell을 관리자 권한으로 열고 다음 명령을 실행하면 됩니다.

1
Restart-Service LxssManager

Windows 10 버전 1903/19H1 (빌드 18362) 이상 부터는 명령 프롬프트(CMD)를 열고 다음 명령어만 간단히 입력함으로서 WSL 시스템을 종료할 수 있습니다.

wsl -t [배포판 이름]
예를 들어 Ubuntu 20.04를 설치하였다면 wsl -t ubuntu를, Debian을 설치하였다면 wsl -t debian과 같이 사용하시면 됩니다.

추가로 Windows 10 버전 2004/20H1 (빌드 18917) 이상 부터는 명령 프롬프트에서 다음 명령어를 사용하여 모든 WSL 시스템을 한 번에 종료할 수 있습니다. 가령 Ubuntu와 Debian 머신이 구동되고 있다면 아래 명령어로 모두 종료 시킬 수 있습니다.

wsl –shutdown

1
2
3
4
5
6
7
(base) PS C:\Users\daddy> wsl -l
Linux용 Windows 하위 시스템 배포:
Ubuntu-20.04(기본값)
(base) PS C:\Users\daddy> wsl -t Ubuntu-20.04
(base) PS C:\Users\daddy>
(base) PS C:\Users\daddy> wsl -t Ubuntu-20.04 --shutdown
(base) PS C:\Users\daddy>

주요 명령

설치

WSL 및 Linux의 기본 Ubuntu 배포판을 설치합니다. WSL은 기본 배포판으로 Ubuntu를 제공한다.

1
wsl --install

설치 가능한 유효한 배포 이름 목록에서 추가 설치 가능한 배포본을 확인할 수 있다

1
wsl --list --online

추가 Linux 배포를 설치할 수도 있습니다.

1
wsl --install <Distribution Name>

설치된 배포판을 변경하려면

wsl –install -d 을 입력합니다. 을 설치하려는 배포판의 이름으로 바꿉니다.


참고


버전

  1. WSL 버전 확인하기 (cmd창에서)

WSL 확인

1
2
3
wsl -l -v

wsl --list --verbose

배포판의 WSL 버전 변경하는 명령어

1
wsl --set-version Ubuntu-20.04 2

종료 시작

  1. 우분투 종료 명령어
    wsl -t Ubuntu-20.04
  • 새로 설치하는 리눅스 배포판에 wsl2로 변경

wsl –set-default-version 2

  1. WSL2 활성화 (Power shell 상)
    dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
    dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

wsl IP 주소

1
wsl hostname -I

네트워크

ssh

https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse?tabs=gui

DHCP

https://stackoverflow.com/questions/61002681/connecting-to-wsl2-server-via-local-network

참고

고정 IP

https://netmarble.engineering/wsl2-static-ip-scheduler-settings/

https://blog.dalso.org/linux/wsl2/11430

1

배치 파일을 만들어서 작업 스케쥴러에 추가해 재시동시 다시 설정한다.

1
2
wsl -d Ubuntu-20.04 -u root ip addr add 192.168.254.10/24 broadcast 192.168.10.255 dev eth0 label eth0:1
netsh interface portproxy add v4tov4 listenport=8585 listenaddress=0.0.0.0 connectport=8585 connectaddress=192.168.254.10
1

참고

HTTPS를 위한 공인인증서 - Let's Encrypt 발급

2020-06-02: 매뉴얼 방식 수정

2020-02-02: 최초 작성
{:.right-history}

Nginx 서버에서 HTTPS 사용할 수 있는 공인인증서를 발급해 설치하려고 한다.

  • 여기서는 Lets Encrypt 무료 공인인증서 발급을 다룬다.
  • letsecrypt 공인인증서는 3개월 정도 기간만 사용 가능하고 갱신해야 한다.
  • **단독 도메인을 호스팅하는 개인 서버에서 Nginx**에 적용해 본다.

인증서는 개별 도메인 혹은 와일드카드 인증서 로 도메인 안의 모든 호스트를 포함하는 두 종류로 발급이 가능하다.

자세히 보기

openSUSE: firewalld

firewalld 를 이용해서 방화벽을 구성해 보자.

  • RedHat, Ubuntu, OpenSUSE LEAP 15.0 등은 시스템 기본 파이어월 관리자로 firewalld 를 제공한다고 한다.

firewalld

firewalld 는 ….

firewalld는 ufw 처럼 iptables 을 구성할 수 있다.

[그림. Firewall Stack (redhat.com)]

네트워크를 지역 관리가 가능해서 다른 네트워크, 지역에 따라 다른 규칙으로 구성해서 사용할 수 있다.
For example “Home” and “Office” where all communications with local machines are allowed, and “Public Wi-Fi” where no communication with the same subnet would be allowed.

https://www.ctrl.blog/entry/ufw-vs-firewalld

firewalld 설치

OpenSUSE LEAP 15.0, RedHat, Ubuntu 등은 시스템 기본 파이어월 관리자로 firewalld 를 제공한다고 한다.

1
$ sudo apt install firewalld

Start firewalld

To start firewalld, enter the following command as root:

1
systemctl start firewalld

root 사용자로 시작한다.

1
2
sudo systemctl enable firewalld
sudo reboot

For more information about the service status, use the systemctl status sub-command:

1
2
3
4
5
6
sudo systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: disabled)
Active: active (running) since Thu 1970-01-01 09:01:48 KST; 48 years 6 months ago

sudo firewall-cmd --state

Stop firewalld

To stop firewalld, enter the following command as root:

1
systemctl stop firewalld

To prevent firewalld from starting automatically at system start, enter the following command as root:

1
systemctl disable firewalld

To make sure firewalld is not started by accessing the firewalld D-Bus interface and also if other services require firewalld, enter the following command as root:

1
systemctl mask firewalld

사용해 보기

firewalld 는 명령라인 firewall-cmd 와 GUI로 firewall-config 명령을 지원한다.

Zone 설정

Get a list of all supported zones

1
firewall-cmd --get-zones

List all zones with the enabled features.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ firewall-cmd --list-all-zones
...

public
target: default
icmp-block-inversion: no
interfaces:
sources:
services: ssh dhcpv6-client http https
ports:
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:

기본으로 제공하는 Zone

  • drop: Any incoming network packets are dropped, there is no reply. Only outgoing network connections are possible.
  • block: Any incoming network connections are rejected with an icmp-host-prohibited message for IPv4 and icmp6-adm-prohibited for IPv6. Only network connections initiated within this system are possible.
  • public: For use in public areas. You do not trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.
  • external: For use on external networks with masquerading enabled especially for routers. You do not trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.
  • dmz: For computers in your demilitarized zone that are publicly-accessible with limited access to your internal network. Only selected incoming connections are accepted.
  • work
    For use in work areas. You mostly trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.
  • home
    For use in home areas. You mostly trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.
  • internal
    For use on internal networks. You mostly trust the other computers on the networks to not harm your computer. Only selected incoming connections are accepted.
  • trusted
    All network connections are accepted.

Zone

1
2
sudo firewall-cmd --get-default-zone
public

서비스

This command prints a space separated list.

Get a list of all supported services

1
$ firewall-cmd --get-services

This command prints a space separated list.

Get a list of all supported icmptypes

1
firewall-cmd --get-icmptypes

서비스를 제거하려면

1
2
3
4
# firewall-cmd --zone=public --remove-service=http
success
root@odroidc2:/home/qkboo# firewall-cmd --zone=public --remove-service=https
success

Http, Ssh 방화벽 활성화

http, https 를 공개 서비스를 지원하는 기본 존인 public에 추가한다.

1
2
3
sudo firewall-cmd --add-service=ssh
sudo firewall-cmd --add-service=http
sudo firewall-cmd --add-service=https

sudo firewall-cmd –zone=public –add-service=http –permanent

방화벽을 갱신한다

1
2
firewall-cmd --reload
firewall-cmd --state

혹은 zone을 지정해 추가한다.

1
2
3
4
sudo firewall-cmd --zone=web --add-service=ssh
sudo firewall-cmd --zone=web --add-service=http
sudo firewall-cmd --zone=web --add-service=https
sudo firewall-cmd --zone=web --list-all

Likewise, we can add the DNS service to our “privateDNS” zone:

1
2
sudo firewall-cmd --zone=privateDNS --add-service=dns
sudo firewall-cmd --zone=privateDNS --list-all

Zone 에 구성한 서비스 등은 런타임 혹은 완전히 방화벽에 구성할 수 있다.

To change settings in both modes, you can use two methods:
Change runtime settings and then make them permanent as follows:

1
2
firewall-cmd <other options>
firewall-cmd --runtime-to-permanent

Set permanent settings and reload the settings into runtime mode:

1
2
firewall-cmd --permanent <other options>
firewall-cmd --reload

모든 구성 내용 확인:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ sudo firewall-cmd --list-all
public
target: default
icmp-block-inversion: no
interfaces:
sources:
services: ssh dhcpv6-client http https
ports:
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:

특정 zone 에 대한 내역을 출력한다:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ sudo firewall-cmd --zone=public --list-all
public
target: default
icmp-block-inversion: no
interfaces:
sources:
services: ssh dhcpv6-client http https
ports:
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:

참조

https://www.linode.com/docs/security/firewalls/introduction-to-firewalld-on-centos/

FirewallD

Firewalld configuration and usage

Raspberry Pi: mmcblk

mmcblk

SD/MMC card 는 MMC 서브시스템을 /dev/mmcblk{id} 형식으로 블럭 장치로 사용한다.

dmesg 로 부트 메시지를 보면 SDHCI 인터페이스에 장착한 장치를 확인할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
[    0.789621] sdhci: Secure Digital Host Controller Interface driver
[ 0.789628] sdhci: Copyright(c) Pierre Ossman
[ 0.789999] sdhost-bcm2835 3f202000.sdhost: could not get clk, deferring probe
[ 0.790252] sdhci-pltfm: SDHCI platform and OF driver helper
[ 0.791051] ledtrig-cpu: registered to indicate activity on CPUs
[ 0.791232] hidraw: raw HID events driver (C) Jiri Kosina
[ 0.791461] usbcore: registered new interface driver usbhid
[ 0.791467] usbhid: USB HID core driver
[ 0.792448] vchiq: vchiq_init_state: slot_zero = 0xb6980000, is_master = 0
[ 0.794533] Initializing XFRM netlink socket
[ 0.794566] NET: Registered protocol family 17
[ 0.794724] Key type dns_resolver registered
[ 0.795223] Registering SWP/SWPB emulation handler
[ 0.796192] registered taskstats version 1
[ 0.796681] vc-sm: Videocore shared memory driver
[ 0.796694] [vc_sm_connected_init]: start
[ 0.802967] [vc_sm_connected_init]: end - returning 0
[ 0.809343] 3f201000.serial: ttyAMA0 at MMIO 0x3f201000 (irq = 87, base_baud = 0) is a PL011 rev2
[ 0.809410] console [ttyAMA0] enabled
[ 0.811406] sdhost: log_buf @ b6913000 (f6913000)
[ 0.889149] mmc0: sdhost-bcm2835 loaded - DMA enabled (>1)
[ 0.889333] of_cfs_init
[ 0.889478] of_cfs_init: OK
[ 0.890211] Waiting for root device /dev/mmcblk0p2...
[ 0.956566] mmc0: host does not support reading read-only switch, assuming write-enable
[ 0.958563] mmc0: new high speed SDHC card at address 59b4
[ 0.959555] mmcblk0: mmc0:59b4 00000 14.9 GiB
[ 0.961428] mmcblk0: p1 p2

메시지에서 보듯 mmc0 장치에 카드가 삽입되기 전에 인터럽트가 없다.

1
2
$ cat /proc/interrupts |grep mmc
86: 393 0 0 0 ARMCTRL-level 88 Edge mmc0

https://developer.toradex.com/knowledge-base/sd-mmc-card-(linux)