Trusted Firmware-A · source analysis

Chain of Trust와 auth_mod_verify_img

certificate parent를 재귀적으로 검증하고 hash, signature, NV counter를 payload image에 적용하는 인증 모듈을 읽습니다.

표의 버전은 소스 분석 기준이며 최신 보안 버전 권고가 아닙니다. TF-A LTS 2.14.3 이후에는 보안 수정이 있습니다. 제품 적용 시 공식 변경 기록과 사용 플랫폼의 errata를 확인하세요.

Series
05 / 12
Baseline
LTS 2.14.3
Commit
f5e765a3443f
Source
drivers/auth/auth_mod.c:444-532 (발췌 범위)

Chain of Trust와 auth_mod_verify_img 단계에서 실제로 바뀌는 상태는 무엇인가?

서명 검증 성공만 보지 말고 어떤 parent에서 어떤 public key와 hash가 추출되어 child image에 연결되는지 추적한다.

child image는 parent가 인증되고 필요한 authenticated data가 채워진 뒤에만 성공 상태가 되며 rollback counter 정책도 함께 통과해야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. Chain of Trust와 auth_mod_verify_img에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01auth_img_desc_t
02auth_method_desc_t
03authenticated_data
04CoT registry

auth_img_desc_t / auth_method_desc_t를 중심에 놓고 왼쪽의 입력이 어떤 검사를 거쳐 오른쪽 결과로 공개되는지 표시했다. 실제 디버깅에서는 각 블록의 주소와 크기를 로그에 대입한다.

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
image ID
parent certificate
public key/signature
hash/NV counter
authenticated flag

화살표는 단순 호출 순서만 뜻하지 않는다. 각 단계가 성공을 반환할 때 다음 단계가 읽을 수 있는 상태가 무엇인지 함께 확인한다. 오류 반환이 발생하면 바로 다음 화살표로 진행하지 않고 해당 단계의 정리 경로를 따라간다.

단계별 입력과 출력

각 단계의 입력과 처리 후 바뀌는 상태를 정리한 표다. 사용 중인 소스 버전에서 다른 필드를 변경한다면 그에 맞춰 표도 수정한다.

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01image IDtrusted boot authentication contextauth_img_desc_tparent certificate
02parent certificateimage ID 완료 상태auth_method_desc_tpublic key/signature
03public key/signatureparent certificate 완료 상태authenticated_datahash/NV counter
04hash/NV counterpublic key/signature 완료 상태CoT registryauthenticated flag
05authenticated flaghash/NV counter 완료 상태CoT registry이 단계의 처리 결과를 사용하는 코드

분석 범위의 전제와 비교해, 다음 단계에 잘못된 입력을 넘긴 부분부터 조사한다.

주소와 객체의 이동을 그림으로 읽기

아래 그림은 주소, 객체를 사용하는 기간, 제어권을 넘기는 시점을 중심으로 정리했다. 실제 주소와 크기는 사용 중인 보드의 bdinfo, 맵 파일과 링커 심벌로 확인한다.

그림 3. Chain of Trust와 auth_mod_verify_img의 실행 순서

각 칸은 제어권이 다음 단계로 넘어가기 전에 확정되어야 하는 상태를 나타낸다.

01image ID
02parent certificate
03public key/signature
04hash/NV counter
05authenticated flag
그림 4. certificate에서 payload 승인까지

왼쪽에서 만든 상태를 오른쪽 단계가 처음 사용하는 관계를 표시한다.

01Root of TrustROTPKkey certificate
02key certificatepublic keycontent certificate
03content certificatehashBL image
04NV counterrollback 비교authenticated flag

원본 코드

아래 코드는 Trusted Firmware-A LTS 2.14.3의 drivers/auth/auth_mod.c에서 444-532줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.

commitf5e765a3443fe21154aa908228e75ee2600085f6anchor · L468int auth_mod_verify_img(unsigned int img_id
444		return 1;
445	}
446
447	*parent_id = img_desc->parent->img_id;
448	return 0;
449}
450
451/*
452 * Initialize the different modules in the authentication framework
453 */
454void auth_mod_init(void)
455{
456	/* Check we have a valid CoT registered */
457	assert(cot_desc_ptr != NULL);
458
459	/* Image parser module */
460	img_parser_init();
461}
462
463/*
464 * Authenticate a certificate/image
465 *
466 * Return: 0 = success, Otherwise = error
467 */
468int auth_mod_verify_img(unsigned int img_id,
469			void *img_ptr,
470			unsigned int img_len)
471{
472	const auth_img_desc_t *img_desc = NULL;
473	const auth_param_type_desc_t *type_desc = NULL;
474	const auth_method_desc_t *auth_method = NULL;
475	void *param_ptr;
476	unsigned int param_len;
477	int rc, i;
478	unsigned int cert_nv_ctr = 0;
479	bool need_nv_ctr_upgrade = false;
480	bool sig_auth_done = false;
481	const auth_method_param_nv_ctr_t *nv_ctr_param = NULL;
482
483	/* Get the image descriptor from the chain of trust */
484	img_desc = FCONF_GET_PROPERTY(tbbr, cot, img_id);
485
486	/* Ask the parser to check the image integrity */
487	rc = img_parser_check_integrity(img_desc->img_type, img_ptr, img_len);
488	if (rc != 0) {
489		VERBOSE("[TBB] %s():%d failed with error code %d.\n",
490			__func__, __LINE__, rc);
491		return rc;
492	}
493
494	/* Authenticate the image using the methods indicated in the image
495	 * descriptor. */
496	if (img_desc->img_auth_methods == NULL)
497		return 1;
498	for (i = 0 ; i < AUTH_METHOD_NUM ; i++) {
499		auth_method = &img_desc->img_auth_methods[i];
500		switch (auth_method->type) {
501		case AUTH_METHOD_NONE:
502			rc = 0;
503			break;
504		case AUTH_METHOD_HASH:
505			rc = auth_hash(&auth_method->param.hash,
506					img_desc, img_ptr, img_len);
507			break;
508		case AUTH_METHOD_SIG:
509			rc = auth_signature(&auth_method->param.sig,
510					img_desc, img_ptr, img_len);
511			sig_auth_done = true;
512			break;
513		case AUTH_METHOD_NV_CTR:
514			nv_ctr_param = &auth_method->param.nv_ctr;
515			rc = auth_nvctr(nv_ctr_param,
516					img_desc, img_ptr, img_len,
517					&cert_nv_ctr, &need_nv_ctr_upgrade);
518			break;
519		default:
520			/* Unknown authentication method */
521			rc = 1;
522			break;
523		}
524		if (rc != 0) {
525			VERBOSE("[TBB] %s():%d failed with error code %d.\n",
526				__func__, __LINE__, rc);
527			return rc;
528		}
529	}
530
531	/*
532	 * Do platform NV counter upgrade only if the certificate gets

발췌 범위와 읽기 기준

원문 444-532줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 int auth_mod_verify_img(unsigned int img_id은 L468에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

서명 검증 성공만 보지 말고 어떤 parent에서 어떤 public key와 hash가 추출되어 child image에 연결되는지 추적한다.

함께 읽어야 하는 원본 코드

첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.

01. certificate signature와 public key를 검증

drivers/auth/auth_mod.c 146-260줄이다.

filedrivers/auth/auth_mod.canchor · L156static int auth_signature
146 * case, the signature verification is considered just an integrity check and
147 * the authentication is established by calculating the hash of the key and
148 * comparing it with the hash obtained from the parent.
149 *
150 * If the image has no parent (NULL), it means it has to be authenticated using
151 * the ROTPK stored in the platform. Again, this ROTPK could be the key itself
152 * or a hash of it.
153 *
154 * Return: 0 = success, Otherwise = error
155 */
156static int auth_signature(const auth_method_param_sig_t *param,
157			  const auth_img_desc_t *img_desc,
158			  void *img, unsigned int img_len)
159{
160	void *data_ptr, *pk_ptr, *cnv_pk_ptr, *pk_plat_ptr, *sig_ptr, *sig_alg_ptr, *pk_oid;
161	unsigned int data_len, pk_len, cnv_pk_len, pk_plat_len, sig_len, sig_alg_len;
162	unsigned int flags = 0;
163	int rc;
164
165	/* Get the data to be signed from current image */
166	rc = img_parser_get_auth_param(img_desc->img_type, param->data,
167			img, img_len, &data_ptr, &data_len);
168	if (rc != 0) {
169		VERBOSE("[TBB] %s():%d failed with error code %d.\n",
170			__func__, __LINE__, rc);
171		return rc;
172	}
173
174	/* Get the signature from current image */
175	rc = img_parser_get_auth_param(img_desc->img_type, param->sig,
176			img, img_len, &sig_ptr, &sig_len);
177	if (rc != 0) {
178		VERBOSE("[TBB] %s():%d failed with error code %d.\n",
179			__func__, __LINE__, rc);
180		return rc;
181	}
182
183	/* Get the signature algorithm from current image */
184	rc = img_parser_get_auth_param(img_desc->img_type, param->alg,
185			img, img_len, &sig_alg_ptr, &sig_alg_len);
186	if (rc != 0) {
187		VERBOSE("[TBB] %s():%d failed with error code %d.\n",
188			__func__, __LINE__, rc);
189		return rc;
190	}
191
192	/*
193	 * Set Zero-OID for ROTPK(subject key) as a the certificate
194	 * does not hold Key-OID information for ROTPK.
195	 */
196	if (param->pk->cookie != NULL) {
197		pk_oid = param->pk->cookie;
198	} else {
199		pk_oid = ZERO_OID;
200	}
201
202	set_current_pk_oid(pk_oid);
203
204	/* Get the public key from the parent. If there is no parent (NULL),
205	 * the certificate has been signed with the ROTPK, so we have to get
206	 * the PK from the platform */
207	if (img_desc->parent != NULL) {
208		rc = auth_get_param(param->pk, img_desc->parent,
209				&pk_ptr, &pk_len);
210		if (rc != 0) {
211			VERBOSE("[TBB] %s():%d failed with error code %d.\n",
212				__func__, __LINE__, rc);
213			return rc;
214		}
215	} else {
216		/*
217		 * Root certificates are signed with the ROTPK, so we have to
218		 * get it from the platform.
219		 */
220		rc = plat_get_rotpk_info(param->pk->cookie, &pk_plat_ptr,
221					 &pk_plat_len, &flags);
222		if (rc != 0) {
223			VERBOSE("[TBB] %s():%d failed with error code %d.\n",
224				__func__, __LINE__, rc);
225			return rc;
226		}
227
228		assert(is_rotpk_flags_valid(flags));
229
230		/* Also retrieve the key from the image. */
231		rc = img_parser_get_auth_param(img_desc->img_type,
232					       param->pk, img, img_len,
233					       &pk_ptr, &pk_len);
234		if (rc != 0) {
235			VERBOSE("[TBB] %s():%d failed with error code %d.\n",
236				__func__, __LINE__, rc);
237			return rc;
238		}
239
240		/*
241		 * Validate the certificate's key against the platform ROTPK.
242		 *
243		 * Platform may store key in one of the following way -
244		 * 1. Hash of ROTPK
245		 * 2. Hash if prefixed, suffixed or modified ROTPK
246		 * 3. Full ROTPK
247		 */
248		if ((flags & ROTPK_NOT_DEPLOYED) != 0U) {
249			NOTICE("ROTPK is not deployed on platform. "
250				"Skipping ROTPK verification.\n");
251		} else if ((flags & ROTPK_IS_HASH) != 0U) {
252			/*
253			 * platform may store the hash of a prefixed,
254			 * suffixed or modified pk
255			 */
256			rc = crypto_mod_convert_pk(pk_ptr, pk_len, &cnv_pk_ptr, &cnv_pk_len);
257			if (rc != 0) {
258				VERBOSE("[TBB] %s():%d failed with error code %d.\n",
259					__func__, __LINE__, rc);
260				return rc;

02. certificate와 platform counter를 비교하는 rollback 검사

drivers/auth/auth_mod.c 313-421줄이다.

filedrivers/auth/auth_mod.canchor · L323static int auth_nvctr
313 * value that should not be lower than the value stored in the platform. If the
314 * value is larger, the counter in the platform must be updated to the new value
315 * (provided it has been authenticated).
316 *
317 * Return: 0 = success, Otherwise = error
318 * Returns additionally,
319 * cert_nv_ctr -> NV counter value present in the certificate
320 * need_nv_ctr_upgrade = 0 -> platform NV counter upgrade is not needed
321 * need_nv_ctr_upgrade = 1 -> platform NV counter upgrade is needed
322 */
323static int auth_nvctr(const auth_method_param_nv_ctr_t *param,
324		      const auth_img_desc_t *img_desc,
325		      void *img, unsigned int img_len,
326		      unsigned int *cert_nv_ctr,
327		      bool *need_nv_ctr_upgrade)
328{
329	unsigned char *p;
330	void *data_ptr = NULL;
331	unsigned int data_len, len, i;
332	unsigned int plat_nv_ctr;
333	int rc;
334
335	/* Get the counter value from current image. The AM expects the IPM
336	 * to return the counter value as a DER encoded integer */
337	rc = img_parser_get_auth_param(img_desc->img_type, param->cert_nv_ctr,
338				       img, img_len, &data_ptr, &data_len);
339	if (rc != 0) {
340		VERBOSE("[TBB] %s():%d failed with error code %d.\n",
341			__func__, __LINE__, rc);
342		return rc;
343	}
344
345	/* Parse the DER encoded integer */
346	assert(data_ptr);
347	p = (unsigned char *)data_ptr;
348
349	/*
350	 * Integers must be at least 3 bytes: 1 for tag, 1 for length, and 1
351	 * for value.  The first byte (tag) must be ASN1_INTEGER.
352	 */
353	if ((data_len < 3) || (*p != ASN1_INTEGER)) {
354		/* Invalid ASN.1 integer */
355		return 1;
356	}
357	p++;
358
359	/*
360	 * NV-counters are unsigned integers up to 31 bits.  Trailing
361	 * padding is not allowed.
362	 */
363	len = (unsigned int)*p;
364	if ((len > 4) || (data_len - 2 != len)) {
365		return 1;
366	}
367	p++;
368
369	/* Check the number is not negative */
370	if (*p & 0x80) {
371		return 1;
372	}
373
374	/* Convert to unsigned int. This code is for a little-endian CPU */
375	*cert_nv_ctr = 0;
376	for (i = 0; i < len; i++) {
377		*cert_nv_ctr = (*cert_nv_ctr << 8) | *p++;
378	}
379
380	/* Get the counter from the platform */
381	rc = plat_get_nv_ctr(param->plat_nv_ctr->cookie, &plat_nv_ctr);
382	if (rc != 0) {
383		VERBOSE("[TBB] %s():%d failed with error code %d.\n",
384			__func__, __LINE__, rc);
385		return rc;
386	}
387
388	if (*cert_nv_ctr < plat_nv_ctr) {
389		/* Invalid NV-counter */
390		return 1;
391	} else if (*cert_nv_ctr > plat_nv_ctr) {
392#if PSA_FWU_SUPPORT && IMAGE_BL2
393		if (fwu_get_active_bank_state() == FWU_BANK_STATE_ACCEPTED) {
394			*need_nv_ctr_upgrade = true;
395		} else {
396			*need_nv_ctr_upgrade = false;
397		}
398#elif PSA_FWU_SUPPORT && IMAGE_BL1
399		/* The check is for bl1 only */
400		if (bl1_plat_is_shared_nv_ctr() == false) {
401			/* If NV ctr is not shared, it can be upgraded */
402			*need_nv_ctr_upgrade = true;
403		} else {
404			/* If NV ctr is shared, the upgrade should happens in BL2 */
405			*need_nv_ctr_upgrade = false;
406		}
407#else
408		*need_nv_ctr_upgrade = true;
409#endif /* PSA_FWU_SUPPORT && IMAGE_BL2 */
410	}
411
412	return 0;
413}
414
415int plat_set_nv_ctr2(void *cookie, const auth_img_desc_t *img_desc __unused,
416		unsigned int nv_ctr)
417{
418	return plat_set_nv_ctr(cookie, nv_ctr);
419}
420
421/*

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

image ID에서 들어온 실행은 trusted boot authentication context에 놓여 있다. 이때 interrupt, MMU/cache, stack, heap 중 무엇이 이미 준비되었는지 소스의 호출자까지 올라가 확인한다. 같은 함수라도 SPL, relocation 전후, app thread처럼 호출 문맥이 달라지면 허용되는 API와 지연 시간이 달라진다.

서명 검증 성공만 보지 말고 어떤 parent에서 어떤 public key와 hash가 추출되어 child image에 연결되는지 추적한다.

02

중심 객체의 생성과 공개를 나눈다

이 글의 중심 객체는 auth_img_desc_t / auth_method_desc_t다. 메모리를 확보한 시점, 필드를 채운 시점, 전역 list나 다른 subsystem에 공개한 시점을 구분한다. 공개 뒤 오류가 발생한다면 목록에서 제거하고 child, buffer, reference를 역순으로 정리하는지 확인한다.

빌드 산출물 관점에서는 최종 부트로더 이미지 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.

03

주소, 크기와 정렬을 계산한다

부트 코드에서는 주소 계산 오류를 주의해야 한다. 원본과 목적지의 주소 범위, 헤더에 기록된 데이터 크기, 블록·페이지 단위를 표로 정리하고 각 구간의 끝 주소를 계산한다. 끝 주소가 start + size - 1처럼 마지막 바이트를 가리키는지, 구간 바로 다음 주소를 가리키는지는 API 규약에서 확인한다.

04

성공 flag와 실제 완료 시점을 맞춘다

parent certificate → public key/signature → hash/NV counter 구간에서는 부분 초기화 상태가 생길 수 있다. flag, list insertion, callback 등록, storage write 완료 중 무엇이 성공의 기준인지 찾는다. hardware write나 DMA가 포함되면 함수 반환과 장치 완료가 같은 시점인지도 확인한다.

다른 CPU, 인터럽트 처리기, USB 완료 콜백, 셸 명령에서도 이 상태를 읽는다면 메모리 접근 순서와 잠금 범위를 함께 확인한다.

05

제어권을 넘기기 전에 확인할 조건을 정리한다

정상 경로는 authenticated flag에서 끝난다. 이 단계가 함수 반환인지, scheduler 전환인지, 다른 image로의 비복귀 분기인지 구분한다. 비복귀 handoff라면 cache clean/invalidate, interrupt disable, 장치 quiesce, argument register와 FDT 또는 image address가 최종 점검 항목이다.

호출한 함수로 돌아오는 경로라면 오류와 일부 처리만 완료된 상태를 구분하는지 확인한다. 이어서 다음 후보를 시도할지, 복구 절차를 실행할지 살펴본다.

구현을 읽을 때 놓치기 쉬운 부분

01

image ID에서 authenticated flag까지 제어권이 이동하는 조건

certificate parent를 재귀적으로 검증하고 hash, signature, NV counter를 payload image에 적용하는 인증 모듈을 읽습니다. 이 경로는 함수 호출 목록만 외워서는 연결되지 않는다. image ID → parent certificate → public key/signature → hash/NV counter → authenticated flag 순서에서 각 단계가 읽는 입력, 새로 확정하는 상태, 다음 단계에 넘기는 값을 구분해야 한다. 특히 trusted boot authentication context에서는 이전 단계가 남긴 register와 memory attribute가 C 코드의 전제 조건이 된다.

서명 검증 성공만 보지 말고 어떤 parent에서 어떤 public key와 hash가 추출되어 child image에 연결되는지 추적한다. 따라서 첫 지점에서 auth_img_desc_t / auth_method_desc_t의 주소와 owner를 기록하고, 마지막 지점에서 같은 값이 그대로 유지되는지 아니면 새 객체로 교체되는지를 확인한다. 중간 함수가 성공을 반환해도 child image는 parent가 인증되고 필요한 authenticated data가 채워진 뒤에만 성공 상태가 되며 rollback counter 정책도 함께 통과해야 한다.

02

auth_img_desc_t와 CoT registry의 생성 시점과 수명

이 글에서 함께 나타나는 객체는 auth_img_desc_t, auth_method_desc_t, authenticated_data, CoT registry이다. 이름이 비슷해도 저장 위치와 수명은 다르다. build-time descriptor인지, boot 단계의 임시 객체인지, world switch 뒤에도 남는 runtime 객체인지 나눠야 pointer를 따라가다 다른 단계의 구조체를 같은 것으로 오해하지 않는다.

auth_img_desc_t / auth_method_desc_t을 기준으로 allocation 또는 정적 배치 위치, list/table에 공개되는 시점, 참조가 끊기는 시점을 적는다. 그 다음 source와 destination 범위, per-CPU 여부, secure/non-secure 접근 권한을 map과 runtime log로 대조한다. 이 절차를 거치면 단순한 호출 순서가 아니라 실제 소유권 이동이 보인다.

03

성공 로그만으로 놓치기 쉬운 오류

대표적인 실패 조건은 parent cycle/누락: 인증 경로 단절; hash parameter 혼동: 다른 payload 승인; NV counter 역행: rollback 허용이다. 이 문제들은 대개 fault가 발생한 함수보다 앞에서 만들어진 잘못된 주소, size, security state 또는 refcount 때문에 생긴다. 마지막 출력만 보지 말고 각 경계 직전의 상태를 한 줄씩 남겨 최초 불일치 지점을 찾는다.

재현에는 certificate chain을 fiptool과 cert tool 출력으로 대조; payload와 certificate를 각각 변조; NV counter를 낮춰 rollback 거부 확인를 사용한다. 정상 경로와 실패 경로에서 같은 필드를 같은 위치에 출력하고, 실패가 검증 단계에서 차단되는지 아니면 다음 context까지 전파되는지 비교한다. firmware와 secure world에서는 실패 뒤의 cleanup 또는 reset 경로도 정상 경로만큼 중요하다.

레지스터에서 오류 판정까지 상세 분석

Chain of Trust는 모든 image에 같은 RSA 검증 함수를 한 번씩 호출하는 구조가 아니다. auth_img_desc_t가 parent와 여러 auth_method를 정의하고, certificate에서 추출한 public key·hash·NV counter가 다음 child 검증의 입력으로 전달된다.

따라서 image 하나의 signature가 맞는지만 보지 말고 root key에서 해당 payload까지 어떤 authenticated_data가 생성되고 소비되는지 그래프로 그려야 한다. rollback 방지는 hash/signature 성공과 별개의 counter 정책이며, counter update 시점까지 포함해야 완전한 경로가 된다.

그림 5. 이 경로를 통과하는 다섯 개의 진입 계약
01image ID

CoT registry에 존재하고 parent chain이 종료 가능해야 한다.

02payload bytes/length

검증 이후 실행·사용할 byte와 정확히 같아야 한다.

03root public key

hash 또는 full key가 신뢰 가능한 저장소에서 와야 한다.

04authenticated data

OID, type, buffer length이 child method 기대와 일치해야 한다.

05NV counter

certificate counter보다 작지 않은 정책을 정확히 적용한다.

각 계약은 앞 단계가 생산하고 현재 단계가 검증한 뒤 다음 소비자에게 넘기는 상태다. 한 항목이라도 확인되지 않으면 뒤 단계의 fault를 그 지점의 문제로 단정하지 않는다.

진입 레지스터와 메모리 계약

함수 첫 줄에 도달했을 때 이미 참이라고 가정하는 값과, 그 값이 틀렸을 때 영향을 받는 범위를 함께 적었다.

#입력 상태생산자정상 조건확인 이유
01image IDBL1/BL2 load loopCoT registry에 존재하고 parent chain이 종료 가능해야 한다.인증 descriptor 탐색의 key다.
02payload bytes/lengthloader검증 이후 실행·사용할 byte와 정확히 같아야 한다.검증 대상과 소비 대상의 분리를 막는다.
03root public keyROTPK platform hookhash 또는 full key가 신뢰 가능한 저장소에서 와야 한다.CoT의 유일한 외부 trust anchor다.
04authenticated dataparent certificate parserOID, type, buffer length이 child method 기대와 일치해야 한다.key와 hash를 child descriptor에 전달한다.
05NV countertrusted counter backendcertificate counter보다 작지 않은 정책을 정확히 적용한다.이전 signed image의 재사용을 막는다.

핵심 구조체 필드의 생산자, 소비자와 수명

구조체 이름만 나열하지 않고 어떤 코드가 값을 쓰고, 어느 코드가 처음 읽으며, 언제까지 주소와 내용이 유지되어야 하는지 구분했다.

#객체 또는 필드생산자소비자수명과 불변 조건
01auth_img_desc_t.parentplatform CoT tableauth_mod_verify_imgbuild된 firmware 수명 동안 불변이며 cycle이 없어야 한다.
02auth_methods[]CoT descriptorauth module method loopsignature, hash, NV counter method의 parameter type과 순서가 일치해야 한다.
03auth_param_type_desc_tauth frameworkcertificate parser/methodOID와 cookie가 어떤 authenticated_data를 지칭하는지 고정한다.
04auth_param_data_desc_tparent 인증child 검증buffer 주소와 길이는 child 검증이 끝날 때까지 유지돼야 한다.
05authenticated flagauth_mod_verify_img 성공 경로loader/handoff모든 method가 성공한 뒤에만 설정하고 실패 시 stale success를 남기지 않는다.
06platform NV counterrollback backendNV counter method/update전원 차단과 실패에도 monotonic 특성을 잃지 않아야 한다.

함수 내부 실행 순서

소스의 큰 분기와 side effect를 실행 순서대로 다시 펼쳤다. breakpoint는 이 목록의 경계에 두고, 다음 번호로 넘어갈 때 새로 유효해진 객체를 기록한다.

  1. 01

    요청 image ID로 auth descriptor를 찾고 아직 인증되지 않은 parent가 있는지 확인한다.

  2. 02

    parent certificate를 재귀적으로 load·verify해 child가 요구하는 key/hash/counter data를 추출한다.

  3. 03

    root certificate 경로에서는 platform ROTPK hook의 key 또는 key hash를 검증 입력으로 사용한다.

  4. 04

    descriptor의 auth method를 순회하면서 method type과 parameter descriptor를 해석한다.

  5. 05

    signature method가 certificate의 signed region과 public key algorithm을 맞춰 검증한다.

  6. 06

    hash method가 실제 payload byte 전체의 digest를 계산해 parent가 인증한 digest와 비교한다.

  7. 07

    NV counter method가 trusted counter와 certificate 값을 정책에 맞게 비교하고 rollback을 거부한다.

  8. 08

    모든 method 성공 뒤 authenticated flag와 child용 authenticated_data를 공개한다.

  9. 09

    실패 시 민감 buffer와 partial state를 정리하고 entry/handoff 경로가 image를 사용하지 못하게 한다.

빌드 설정이 바꾸는 실제 코드 경로

동일한 함수 이름이라도 아래 설정에 따라 포함되는 source, 구조체 크기, 인자 의미와 failure path가 달라진다.

#설정바뀌는 동작확인 방법
01TRUSTED_BOARD_BOOTauth module과 CoT 전체를 build에 포함한다.release image에서 이 값이 실제 define됐는지 map과 log로 확인한다.
02KEY_ALG/HASH_ALGcertificate와 runtime crypto algorithm을 선택한다.cert_create option과 auth method가 같은 algorithm을 기대하는지 본다.
03COT / platform CoT sourceimage parent graph와 OID를 바꾼다.생성된 certificate 목록과 descriptor registry를 나란히 놓는다.
04NV counter backendrollback 저장 위치와 update 특성이 platform마다 다르다.read/update 실패가 fail-open이 아닌지 fault injection한다.

증상에서 최초 불일치 지점까지 추적하기

마지막 panic 메시지가 아니라 어디에서 멈추고 무엇을 읽어 어떤 결론을 내릴지 정리했다. 정상값과 실패값은 같은 build와 같은 위치에서 비교한다.

#관찰 증상중단 위치기록할 값판정
01root certificate부터 모두 실패ROTPK 반환과 첫 signature methodkey hash, DER length, algorithm잘못 provision된 ROTPK와 parser 문제를 구분한다.
02certificate는 통과하고 payload hash만 실패hash method 직전payload base/size, expected/actual digestload 범위 또는 package payload 불일치를 찾는다.
03새 image인데 rollback으로 거부NV counter comparetrusted counter, certificate counter, endian/widthcounter encode 방식과 update 정책을 확인한다.
04한 번 성공한 뒤 변조 image도 통과authenticated flag lookupimage ID별 flag, reload 여부, buffer hashcache된 인증 상태가 다른 payload에 재사용되는지 검사한다.

객체와 수명

대상만들어지는 시점유효 범위확인할 조건
auth_img_desc_t / auth_method_desc_tparent certificateauthenticated flag 또는 오류 정리 완료까지진입 전제와 상태 계약
입력 buffer / metadataimage IDparse와 검증이 끝날 때까지길이, 정렬, 소유권, 변조 가능성
등록된 list / descriptorpublic key/signature하위 시스템을 종료하거나 다음 이미지에 제어권을 넘길 때까지중복 등록, 해제된 객체를 가리키는 포인터, 오류 후 자원 정리
hardware 또는 persistent state실제 write/probe가 완료된 뒤reset 또는 명시적 해제·갱신까지쓰기 완료, 시간 초과, 전원 차단, 이전 상태 복원
최종 부트로더 이미지link/image 생성 시점다음 stage가 새 image로 교체할 때까지적재 주소, 진입점, 섹션, 헤더의 일치 여부

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01parent cycle/누락인증 경로 단절parent certificate
02hash parameter 혼동다른 payload 승인public key/signature
03NV counter 역행rollback 허용hash/NV counter

로그가 끊긴 함수뿐 아니라 그 함수에 주소, 크기, 플래그를 전달한 앞 단계도 조사한다. 오류 처리 후 등록된 객체나 하드웨어 설정이 그대로 남아 있는지도 확인한다.

소스 밖에서 확인할 증거

소스에서 파악한 동작을 실제 빌드 결과와 대상 보드의 로그로 확인한다. 아래 명령의 보드 이름과 툴체인 접두사는 사용 중인 빌드 환경에 맞게 바꾼다.

#목적명령 또는 계측판정 기준
01빌드 산출물make PLAT=<platform> DEBUG=1 all fipBL1, BL2, BL31과 FIP가 같은 설정으로 만들어졌는지 전체 빌드 명령부터 기록한다.
02FIP 구성tools/fiptool/fiptool info build/<platform>/debug/fip.binFIP 안의 BL31, BL32, BL33 UUID와 offset, 크기를 확인해 실제 적재 입력을 고정한다.
03심볼과 주소${CROSS_COMPILE}nm -n build/<platform>/debug/bl31/bl31.elf | grep 'int auth_mod_verify_img'대상 함수가 BL31의 어느 주소와 섹션에 놓였는지 확인한다.
04EL3 명령 추적${CROSS_COMPILE}objdump -drS build/<platform>/debug/bl31/bl31.elfC 코드가 EL3 system register 접근과 eret 경로로 어떻게 번역됐는지 대조한다.
05실행 시점 증거TF-A DEBUG log + CurrentEL/SCR_EL3/SPSR_EL3/x0-x3 기록어느 exception level에서 어떤 security state와 인자를 다음 이미지에 넘겼는지 serial log로 남긴다.

직접 확인할 실험

  1. 01
    certificate chain을 fiptool과 cert tool 출력으로 대조

    parent certificate 진입 전후에 auth_img_desc_t의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    payload와 certificate를 각각 변조

    public key/signature 진입 전후에 auth_method_desc_t의 주소·크기·반환값과 timestamp를 함께 남긴다.

  3. 03
    NV counter를 낮춰 rollback 거부 확인

    hash/NV counter 진입 전후에 authenticated_data의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글