[컴] 썬더클랩 Thunderclap

썬더볼트 취약점 /


paper : http://thunderclap.io/thunderclap-paper-ndss2019.pdf

썬더클랩(Thunderclap)

  • 이 취약점은 물리적인 접근을 한 공격자에게 Thunderbolt(썬더볼트) 포트를 이용해서 해당기계를 위험하게 한다.
  • 공격자가 가장높은 권한으로 임의의 코드를 실행시킬 수 있게 해준다. 그래서 잠재적으로 암호, 은행 로그인, 암화화 키, 개인파일등에 접근할 수 있게 해준다.
  • 또한, 공격자가 이 취약점을 이용하면 겉으로 무해해 보이는 충전기, 프로젝터 같은 주변기기가 충전이나, 영상을 쏘아 주는 사이에 "host 머신"을 위험하게 할 수 있다.(이러면, 우리가 제3자의 충전기도 마음대로 사용하기 힘들어진다. 마치 공용 wifi 같이)

동작

네트워크 카드의 동작

  1. OS 가 network interface card(NIC) 에 packet 을 보내라고 요청할 때
  2. OS 는 NIC에 보낼 data 에 대한 address 를 제공해 준다.
  3. 그러면 NIC 의 payload 함수는 plaintext data를 찾으려고 memory 근처를 검색할 것이다.


Thunderclap 방법

When an IOMMU is in operation, the most obvious way touse it for protection requires some changes to ring buffer usage. 
  • First,  packet  data  must  be  allocated  from  a  pool  of  physical memory  that  allows  exposure  to  devices  (some  memory  maybe  inaccessible  due  to  hardware  limitations).  
  • Second,  before a data  block  is  placed  in  the  ring  buffer  for  transmission,  a window must be opened for it to be accessible by the device. This involves creating a mapping for the block in the IOMMU page table.
  • Third, the address written into the ring buffer is now the I/O virtual address of the mapping, rather than the physical address. 
  • Finally, when the device is finished with the data, the operating system should close the window again, revoking the mapping from the IOMMU page table and IOTLB.




How do the Thunderclap vulnerabilities work?

The Thunderclap vulnerabilities stem from the fact that computer peripherals such as network cards and GPUs have traditionally been trusted parts of a computer system: they have direct memory access (DMA), which allows them to read and write all of system memory without operating system oversight. DMA allows peripherals to bypass operating system security policies, and DMA attacks abusing this access have been widely employed by hackers and the intelligence community to take control of and exfiltrate sensitive data from target machines. This means passwords, banking logins, private files and browser activity are all exposed, and an attacker can inject any code they wish onto your machine.

Current systems feature input-output memory management units (IOMMUs), protection mechanisms that allow the operating system to restrict peripheral-device memory access. With IOMMU usage enabled, operating systems can protect against DMA attacks by restricting memory access to peripherals that perform legitimate functions and only allowing access to non-sensitive regions of memory. Unfortunately, IOMMU protection is turned off by default in many systems.

Our work leverages vulnerabilities in operating system IOMMU usage to compromise a target system via DMA, even in the presence of an IOMMU that is enabled and configured to defend against DMA attacks. The novel Thunderclap security evaluation platform, built on field-programmable gate array (FPGA) hardware, mimics the functionality of a legitimate peripheral device to convince a target operating system to grant it access to regions of memory. It then examines those regions of memory to find a rich and nuanced attack surface of vulnerable structures that can be exploited to take control of the system.

The rise of hardware interconnects like Thunderbolt 3 over USB-C that combine power input, video output, and peripheral device DMA over the same port greatly increases the real-world applicability of Thunderclap vulnerabilities. Thunderbolt can allow potentially malicious devices to hotplug into a running machine and obtain direct memory access, which makes DMA attacks against temporarily unattended targets feasible. Furthermore, the confusion of power, video, and DMA facilitates the creation of malicious charging stations or projectors that take control of connected machines.

Additionally, our work shows that the Thunderclap vulnerabilities can also be exploited by compromised firmware on existing PCI Express devices, for example network cards or baseboard management controllers (BMCs) integrated into servers. A firmware compromise might be introduced via a firmware vulnerability or a compromise in the device supply chain or factory.


How does this work differ from earlier DMA attacks such as Inception?

Early DMA attacks relied on the absence of an IOMMU. They involved scanning all of a system’s memory for sensitive data from devices that did not appear to the system as legitimate peripherals. These attacks were addressed by the introduction of IOMMUs, which block all memory access from unrecognized devices.

Some previous DMA attacks have taken advantage of weaknesses in IOMMU configuration or setup to disable IOMMU protections. Thunderclap explores serious vulnerabilities that are present even once the IOMMU is configured correctly.

Technical details of the Thunderclap platform

The Thunderclap platform consists of an FPGA that runs the Thunderclap application. The FPGA then plugs into a computer via PCI Express or Thunderbolt. The Thunderclap application makes the FPGA behave to the computer like a genuine Ethernet card (the Intel 82574L network interface card or NIC). The operating system will identify the ethernet peripheral, load drivers, allow the device to access memory (via DMA and an IOMMU if enabled), and ask it to send and receive packets.

With this deep interaction with the operating system, Thunderclap’s device model provides hooks that allow payload functions to be added to device behavior. For example, when the operating system asks the NIC to send a packet, it provides the NIC with the address of the data to send. A payload function might search nearby memory looking for plaintext data that was intended for a different network device.

The Thunderclap application runs on Intel/Altera FPGA boards:
  1. Intel Arria 10 SoC Development Kit ($4500) with Samtec HDR-181157-01-PCIEC cable (available from Samtec direct) - currently recommended
  2. Enclustra Mercury+ AA1 module (ME-AA1-270-3E4-D11E) on PE1 carrier board (~EUR 800) - work in progress
  3. Terasic DE5-Net board (Stratix V) with BERI soft-CPU - no longer supported
  4. As far as we can ascertain, Xilinx, Lattice and Intel Cyclone FPGAs don’t allow us to replace the vendor-supplied implementation of configuration registers with our own (Intel calls it ‘config bypass’ mode) which we require.
It is composed of several pieces:
  1. The underlying FPGA bitfile, containing the hardware that receives PCIe packets (TLPs) and delivers them to software. The FPGA contains an Arm Cortex A9 CPU (hard processor system or HPS) to run our software stack. GitHub repo
  2. The Ubuntu 16.04 operating system running on the on the Arm, including kernel, device tree and u-boot bootloader (which also loads the FPGA bitfile at boot time). Automated build scripts (work in progress): GitHub repo
  3. The Thunderclap application, which is a substantially cut down version of QEMU, based on its e1000e device. This runs in Ubuntu on the ARM core and connects directly to the PCIe queues provided by the hardware. GitHub repo





[컴] 소프트웨어 팀장(Leader) 가 하지 말아야 하는 행위

PL업무 / sw 개발 / 프로젝트 리더 / 관리자 / 관리

소프트웨어 팀장(Leader) 이 하지 말아야 하는 행위

‘팀 플레이’라는 안티패턴

  • 팀에 인원이 너무 많은 경우, 개발자들이 서로 반목하면서 동일한 코드를 업데이트하려 경쟁하게 된다.
    --> 검토할 코드가 많아지고, 그 누구도 코드를 일일이 검토해 통합하기 원하지 않게 된다.
  • 마이크로서비스 아키텍처를 구성하는 것은 개발자에게 숨쉴 공간을 준다. 독립적으로 자신이 맡은 코드 작업을 할 수 있다.

‘분할 관리’라는 안티패턴

  • 더 중앙에서 통제를 하고, 더 중앙에서 테스트를 하는 것이 필요하다.
  • 일부 개발자를 지정, 부분들이 가능한 원활하게 함께 작동할 수 있도록 통합을 지속적으로 모니터링하는 일을 맡긴다. 
  • 부분들이 함께 작동하도록 만드는 일은 부분들을 구현하는 것만큼 힘든 일이다. 
  • 개발자들을 동일한 방향으로 계속 유도하는 것 자체가 하나의 ‘일’이다.

‘비전을 따르라’는 안티패턴

  • 모든 개발자가 이런 상상 후, 단 몇 줄의 코드로 모든 기능을 구현하는 ‘초능력’에 대해 상상한다.
  • 계획 수립은 번거로운 일이다. 그러나 나중에 코드를 디버깅하는 것보다 빨리 할 수 있다. 때로는 다짜고짜 저지르기보다 그저 앉아 있는 게 나을 수 있다. 

‘교과서대로’라는 안티패턴

  • 스펙을 만드는 데 몇 달을 소비하고도, 모든 것이 거의 마무리되었을 때 새로운 각도나 문제를 발견하게 된다.
  • 유능한 관리자는 방법론을 선택한 후, 이 방법론이 실패할 가능성에 대비한다.
  • 어느 누구도 항상 성공할 수는 없다. 대비가 중요하다.  

‘프로세스 신뢰’라는 안티패턴

  • 창의성을 방해할까 두려워 세부 사항을 계속 추적하지 않으면 악성 결과가 초래될 수 있다.
  • 책임자는 항상 지연을 초래하는 많은 장벽, 장애물, 문제에 직면하게 된다. 책임자의 도전과제는 효율적으로 일어나는 일을 모니터링하고, 현명한 결정을 내리기에 충분한 정도로 세부사항을 계속 추적하는 방법을 찾는 것이다.
  • 소프트웨어 개발 매트릭스가 부정확할 수 있다.
  • 그러나 지나치게 많은 기대를 하지 않으면, 누가 무슨 일을 하고 있는지 추적할 수 있도록 도와준다.

‘측정하지 않은 것은 관리할 수 없음’이라는 안티패턴

  • 적합한 점수를 파악하는 것은 애초 문제를 해결하는 것만큼 어렵다.
  • 정말 지독한 팀은 더 정확한 평가를 위해 서로를 경쟁시키기도 한다. 이는 팀웍이나 협업에 도움이 되지 않는다.
  • 가장 큰 위험은 개발자들이 힘든 일이나 예측하기 어려운 일을 피하게 되는 것이다.
  • 분기말, 연말에 충분한 점수를 얻게 되지 못할까 우려하는 행태가 번기는 것이다.
  • 해결책은 이런 매트릭스를 지나치게 신뢰하지 않는 것이다. 점수를 추적 관리할 수는 있다. 그러나 이런 점수를 절대적인 척도로 간주해서는 안 된다.

'어리석은 일관성은 편협한 사람들의 망상’이라는 안티패턴

  • 코드에 어느 정도 일관성이 있을 때, 패턴과 시각적인 리듬의 예측성이 높을 때, 코드를 더 쉽게 판독할 수 있다.
  • ESLint 등을 이용하자.

‘기준이 구원자’라는 안티패턴

  • 실행 코드의 품질에 거의 영향을 주지 않는 기준을 강제하는 것은 좋지 않다. 
    • 필자생각: 코드의 일관성을 유지하는 것과의 균형을 잡는 것이 중요할 듯 하다.
  • 스페이스의 위치 같은 것은 사람을 위한 것이다. 사람들이 지나치게 많은 것을 주장하지 않도록 만드는 데 목적이 있다. 
  • 기준을 사용하고 싶다면, 적용하기 쉽고, 실제 유의미한 세부 사항만 신경 쓰도록 단순하게 만들어야 한다

‘스택 단순화’라는 안티패턴

  • 코드 기반의 ‘순정함’을 유지하면, 그 대가로 속도와 효율성을 잃게 된다. 
  • 사용자를 만족시킬 수 있다면, 코드 기반의 이탈을 어느 정도 용인하는 것이 합리적이다. 
  • 절충의 가치가 있는 때를 파악하는 것이 핵심이다.

‘개발자가 직접 도구를 선택’이라는 안티패턴

  • 나중에 문제가 발생한다. 코트린(Kotlin)을 좋아하는 개발자가 팀을 떠나고, PHP를 좋아하는 사람이 코드를 물려 받으면 이를 해독할 수가 없다.
  • 적합한 스킬을 가진 사람들로 팀을 구성해 유지하는 경우에도, 자바스크립트 개발자들은 스위프트(Swift)로 작성된 코드를 확인할 때 고생을 하게 된다.
  • 지나치게 개방적으로 모든 것을 수용해서는 안 된다.

‘성공의 열쇠는 동기 부여’라는 안티패턴

  • 동료가 한 장의 티켓을 여러 티켓으로 분리해야 한다고 주장하는 것을 보았다. 봉급에서 보상을 받기 위해서이다. 이 동료는 풀 리퀘스트, 지원 티켓, 애자일 매트릭스를 ‘조종’하는 데 있어 ‘달인’이었다.
    • 필자생각: 소프트웨어 개발에 경영을 위한 측정을 하겠다는 생각은 어리석다. 왜냐면 그것은 개발자 마음대로 쪼개고 늘리고 할 수 있는데다, 복잡도는 높다. 그래서 룰을 만들어도 쉽게 룰을 피해갈 수 있으며, 완벽한 룰을 만들면 할 수록 개발은 유연성을 잃고, 제대로 된 개발을 할 수 없게 되기 때문이다.
  • 개발자들에게 진짜 동기를 부여하는 것은 수수께끼 같은 난제이다. 
  • 개발자들은 흔히 자신만의 생각을 갖고 있으며, 누구보다 도구를 잘 이해한다. 
  • 우리가 할 수 있는 최선은 ‘파트너십’에 대한 의식을 불어넣고, 큰 그림을 이해하도록 만드는 것이다. 
  • 그런 후, 이들이 추상적인 목표를 여러 수 많은 깨끗한, 테스트가 완료된, 버그가 거의 없는 코드로 바꿔 놓도록 바래야 한다.

See Also

  1. 엔지니어링 관리자를 위한 조언

References

  1. SW 프로젝트를 산으로… 서툰 리더십 행태 11가지 - CIO Korea





[컴] V8 의 메모리 관련, Garbage Collector GC

가비지 컬렉터 ,


V8 의 메모리 관련 글

See Also

[컴][리눅스] disk 사용량 관련 리눅스 명령어 정리

디스크 / 어느파일이 용량을 많이 먹는지 알 수 있는 /

disk 사용량 관련 리눅스 명령어 정리

# 접근한지 365일이 지난 file 들 list
find /home -atime +365

# 그 file 들을 지우는 방법
rm `find /home -atime +365`

# 100MB 이상의 파일을 찾는법
find / -type f -size +100M 

# 특정 directory 를 제외하는 법,
# data0* 를 제외하고, 100MB 이상의 파일을 찾는다.
find / -name 'data0*' -prune -o -type f -size +100M 

# /dev 디렉토리내의 파일들의 disk 사용량
du -h /dev

# -c option 을 넣으면, 마지막줄에 total 을 보여준다.
du -hc /dev

# max-depth 를 정할 수 있다. 
# /home에서 어느 directory 가 많은 용량을 차지하는지 확인할 때
sudo du -hc /home --max-depth=1

# /var/log 에서 어느 폴더가 가장 많은 용량을 차지하는지 알고 싶을 때
sudo du --max-depth=1 -h /var/log | sort --human-numeric-sort

References

  1. How to Find & Remove Unused Files in Linux - Fedingo
  2. How to find files larger than 100MB in Linux – TecAdmin
  3. How to Exclude a Directory While Finding Files in Linux
  4. How to Check the Size of a Directory in Linux {3 Options}

[웹] 텔레그램 Bot 이용하기

telegram bot

Telegram bot

Telegram 은 @BotFather 를 제공하는데 @BotFather 를 통해 간단히 Bot 을 만들 수 있다.

Bot 만들기

  1. @BotFather 와 대화를 시작한다
  2. /newbot
  3. "bot 이름" / "user 이름" 을 알려준다
  4. bot 이 만들어지고, access token 을 알려준다.


Bot 에 메시지 보내기

telegram 에서 bot 을 등록한다.(찾기에서 "bot 이름" 을 치면 나온다.)

getUpdates 를 하면 chat_id 를 얻을 수 있다.

  1. bot 을 등록하지 않으면, update 할 내용이 없어서, 아무런 내용이 나오지 않는다. 그래서 chat_id 를 얻을 수 없다.
  2. https://api.telegram.org/bot<token>/getUpdates

telegram 에 메시지 보내기

  1. https://api.telegram.org/bot<token>/sendMessage?chat_id=234324&text=helloworld

여러명에게 메시지 보내기

텔레그램에서 기본적으로 봇도 일종의 사람의 역할을 한다. 그래서 이 봇을 찾아서 등록 하는 것은 그 봇과 채팅방을 하나 여는 것이 된다. 이때 chat id 가 생긴다.

처음에 필자가 오해했던 부분은 봇을 등록하기만 하면 모두에게 문자가 갈 것이라 생각했다. 하지만 지정된 채팅방(chat id) 로만 보낸다. 그래서 만약 단체알림의 용도로 쓰고 싶다면 이 봇이 참여한 그룹을 하나 만들어야 한다. 그리고 알람을 받을 인원을 이 그룹에 참여시켜야 한다. 그리고 봇이 이 그룹채팅방(chat id)에 문자를 보내도록 해야 한다.

Get TELEGRAM Channel/Group ID, StackOverflow 에 나온 것처럼 web telegram 을 이용하면, 쉽게 group chat id 를 알 수 있다.

조심할 점은 group 이 super group 으로 자동으로 변경되는 경우가 있다. 이때는 chat id 가 변경되기 때문에 api 의 parameter 에 쓰이는 chat_id 값도 변경이 필요하다.

전송방식

Bot <--> Someone

아래 4가지 방식으로 message 를 보내고 받을 수 있다.(UTF-8 이다.)

  1. URL query string
  2. application/x-www-form-urlencoded
  3. application/json (except for uploading files)
  4. multipart/form-data (use to upload files)

전송 한계


API 가 초당 한 user에게 최대 30개의 문자(30 messages) 만 보낼 수 있게 되어 있다. 이 이상보내면 429 error 가 뜬다.

그리고 같은 group 으로 보내는 메시지는 1분에 20개 이상은 안된다.

이것을 피하려면 하나의 알림에 대해 여러개의 bot 을 사용해야 할 듯 하다. 또는 보내는 message 를 모아서 한번에 보내면 된다. 대략 3초에 1번 정도만 send 를 한다.

한번에 보낼 수 있는 길이는 4096 UTF character 이다. 너무 긴 글자를 보내면 400 error code 가 뜬다.

update 받는 방식

Someone --> Bot


이건 누군가가 bot 에게 보낸 내용을 확인하는 방법이다. 이것은 텔레그램 client 채팅방 같은 것을 구성할 때 필요하다고 보면 된다. client 를 구성하려면 상대가 한 이야기를 가져와야 한다. 그 방법을 제공하는 것이다.

또는 텔레그램을 통해서 서버에 명령을 내리거나 하는 기능을 구현할 때 등에 사용해도 된다.

2중 한개를 쓰면 다른 하나는 사용이 안된다.

  1. getUpdates : pull, 이녀석은 우리가 호출할 때 bot 이 받은 내용을 알려주는 것이고,
  2. setWebhook : push, 이 녀석은 메시지가 오면 자동으로 특정 url 로 날려주게 설정해서 사용할 수 있다. 그래서 이녀석의 사용을 위해서는 server 가 필요하다.

setWebhook


bot 설정 변경

이름 변경

  1. @BotFather 에서 /setuserpic을 치면, 현재 소유한 bot 들이 나온다. 
  2. 그러면, 이제 bot 을 선택하면, 
  3. image 를 send 해달라고 메시지가 나온다.
  4. image 를 보내면 된다.(채팅창에서)

기타 변경

@BotFather 에서 /help 를 치면 가능한 명령어가 나온다.

  • /setname - change a bot's name
  • /setdescription - change bot description
  • /setabouttext - change bot about info
  • /setuserpic - change bot profile photo
  • /setcommands - change the list of commands
  • /deletebot - delete a bot
  • /mybots - 내가 만든 모든 bot 들이 보인다. 여기서 bot 을 선택하면 Bot Settings 를 메뉴가 나온다.
    • group privacy : group 안에 있을 때 privacy mode 일때는 '/'로 시작되는 message 만 받게 된다. admin 인 경우는 모든 message 를 수신한다.(Bots: privacy mode)
    • allow groups: group 에 초대가 안되게 할 수 있다.

[컴][웹] AWS 요금

email 서버 금액 / aws 요금 / 아마존 요금


Amazon 요금

Amazon SES pricing


상황 지불 추가요금
이메일을 Amazon EC2 에서 보내면 매달 62,000 건까지 무료, 초과 1,000 건 당 $0.1 첨부파일들 전체용량 1GB 당 $0.12 를 지불
EC2 외에 다른곳에서 보내면 1,000 건 당 $0.1  첨부파일들 전체용량 1GB 당 $0.12 를 지불
이메일 수신 총 1,000 건 수신은 무료, 그 이후부터는 1,000 건 당 $0.1 매 수신하는 256MB에 대해 $0.09 을 지불.( 1,000개의 incoming email chunks(256 kilobytes (KB)) )








[컴][웹] vscode remote debugger 를 remote node server 에 attach 하기

원격 서버에 붙이기 / 디버거 붙이기 노드서버에 붙이기 / agent forwarding

vscode remote debugger 를 remote node server 에 attach

ssh tunneling

ref. 1 에서 추천하는 방법인데, remote server 에서 debugging 을 위해 모든 ip address 로 부터의 접근을 허락하는 것은 위험하니, remote server 는 9229 만 debugging 용으로 열어놓고, 접근하는 쪽에서 ssh tunneling 을 열어서 debugging 을 하라는 이야기다.

하지만 여전히 debugging port 를 열어놓는 것은 좋지 않은 행위이니, 실서버에서의 사용은 자제하는 것이 좋다.

server 에서 debugging mode 로 실행

$ node --inspect server.js
Debugger listening on ws://127.0.0.1:9229/3ee2ba78-e563-4f9a-9fa1-06e8b6bb8539
For help, see: https://nodejs.org/en/docs/inspector

ssh tunneling 실행

먼저 ssh tunneling 을 열어놓는다.

ssh -N -L 9221:localhost:9229 myhome@ec2-174-69-46-3.ap-northeast-.compute.amazonaws.com -i .\ec2-dev.pem

ssh <bastion_server_connect_info> -N -L <source_port>:<destination_ip>:<destination_port>

localhost:<source_port> 로 요청하면, ec2-174-69-46-3.ap-northeast-.compute.amazonaws.com:<destination_port> (ssh tunnel) 을 타고, <destination_server>:<destination_port> 로 가게 된다.

vscode

그리고 vscode 에서 source 를 열어놓고, 아래 debug option 을 선택해서 실행하면 된다.

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [

        
        ...
        {
            "type": "node",
            "request": "attach",
            "name": "Attach to Remote",
            "address": "localhost",
            "port": 9221,
            "localRoot": "${workspaceFolder}",
            "remoteRoot": "/home/myhome/myserver"
        }
    ]
}


See Also

  1. ssh man page
  2. 쿠…sal: [컴] ssh tunneling

References

  1. Debugging - Getting Started | Node.js