시큐어코딩
2. 보안기능 보안기능 ( 인증, 접근제어, 기밀성, 암호화, 권한관리등 ) 을부적절하게구현시발생 할수있는보안약점, 적절한인증없는중요기능허용, 부적절한인가등이포함 취약점명 1 적절한인증없는중요기능허용 2 부적절한인가 3 중요한자원에대한잘못된권한설정 취약점명 9 패스워드평문저장 10 하드코드된암호화키 11 취약한패스워드사용 4 취약한암호화알고리즘사용 12 사용자하드디스크에저장되는쿠키를통한정보노출 5 사용자중요정보평문저장 ( 또는전송 ) 13 보안속성미적용으로인한쿠키노출 6 하드코드된패스워드 14 주석문안에포함된패스워드등시스템주요정보 7 충분하지않은키길이사용 8 적절하지않은난수값사용 15 솔트없이일방향해쉬함수사용 16 무결성검사없는코드다운로드
1. 적절한인증없는중요기능허용 2. 보안기능 CWE-306: Missing Authentication for Critical Function The software does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources. Architecture and Design Language-independent Access Control: Gain privileges / assume identity; Other Exposing critical functionality essentially provides an attacker with the privilege level of that functionality. The consequences will depend on the associated functionality, but they can range from reading or modifying sensitive data, access to administrative or other privileged functionality, or possibly even execution of arbitrary code.
인증 2. 보안기능 악의적인공격에맞서애플리케이션을보호하기위한핵심조치 일차방어선으로이것이무너지면공격자에의해애플리케이션이장악되고저장정보에제한없이접근가능 세션관리, 접근통제와같은핵심보안매커니즘무력화 안전한인증이란미묘한작업으로공격자가좋아하는애플리케이션의가장취약한연결고리
인증의설계상결함 2. 보안기능 안전하지않은비밀번호 Brute force 공격이가능한로그인 불필요하게상세한로그인실패메시지 로그인정보의전송취약성 고유하지않은사용자명문제 예측가능한사용자명 추측가능한초기비밀번호 사용자신원정보의안전하지않은배포 비밀번호변경기능 비밀번호복구기능 내정보기억하기 의처리 신분전환기능 사용자신원의불완전한검증
내정보기억하기해킹 2. 보안기능 로컬저장메커니즘에영구저장되는정보조사 ( 영구쿠키, IE userdata, 실버라이트독립저장소, 플래시로컬공유객체 ) 저장되는정보와예측가능한어떤사용자식별자저장여부조사 암호화나변형으로방어시유사사용자명 / 비밀번호를이용해리버스엔지니어링 영구쿠키정보를바꿔다른사용자처럼애플리케이션공격
Bad Code 2. 보안기능 public void sendbankaccount(string accountnumber,double balance) { BankAccount account = new BankAccount(); account.setaccountnumber(accountnumber); account.settoperson(toperson); account.setbalance(balance); AccountManager.send(account);... }
Good Code // 재인증을위한팝업화면을통해사용자의 credential 을받는다. String newusername = request.getparameter("username"); String newpassword = request.getparameter("password"); if ( newusername == null newpassword == null ) { throw new MyEception(" 데이터오류 :); } // 세션으로부터로긴한사용자의 credential 을읽는다. String password = session.getvalue("password"); String username = session.getvalue("username"); // 재인증을통해서이체여부를판단한다. if (isauthenticateduser() && newusername.equal(username) && newpassword.equal(password) ) {
2. 부적절한인가 2. 보안기능 CWE-255: Improper Authorization The software does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action. Assuming a user with a given identity, authorization is the process of determining whether that user can access a given resource, based on the user's privileges and any permissions or other access-control specifications that apply to the resource. When access control checks are not applied consistently - or not at all - users are able to access data or perform actions that they should not be allowed to perform. This can lead to a wide range of problems, including information exposures, denial of service, and arbitrary code execution.
2. 보안기능
AuthC 2. 보안기능
2. 보안기능 Architecture and Design / Implementation / Operation Language-independent A developer may introduce authorization weaknesses because of a lack of understanding about the underlying technologies. For example, a developer may assume that attackers cannot modify certain inputs such as headers or cookies. Authorization weaknesses may arise when a single-user application is ported to a multi-user environment.
2. 보안기능 Confidentiality: Read application data; Read files or directories An attacker could read sensitive data, either by reading the data directly from a data store that is not properly restricted, or by accessing insufficiently-protected, privileged functionality to read the data. Integrity: Modify application data; Modify files or directories An attacker could modify sensitive data, either by writing the data directly to a data store that is not properly restricted, or by accessing insufficientlyprotected, privileged functionality to write the data. Access Control: Gain privileges / assume identity An attacker could gain privileges by modifying or reading critical data directly, or by accessing insufficiently-protected, privileged functionality.
Bad Code 2. 보안기능 public void f(string ssingleid, int iflag, String sserviceprovider, String suid, String spwd) { env.put(context.initial_context_factory, CommonMySingleConst.INITCTX); env.put(context.provider_url, sserviceprovider); env.put(context.security_authentication, "none"); env.put(context.security_principal, suid); env.put(context.security_credentials, spwd);
Good Code public void f(string ssingleid, int iflag, String sserviceprovider, String suid, String spwd) { env.put(context.provider_url, sserviceprovider); env.put(context.security_authentication, "simple"); env.put(context.security_principal, suid); env.put(context.security_credentials, spwd);
3. 중요한자원에대한잘못된권한설정 2. 보안기능 CWE-732: Incorrect Permission Assignment for Critical Resource The software specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. When a resource is given a permissions setting that provides access to a wider range of actors than required, it could lead to the exposure of sensitive information, or the modification of that resource by unintended parties. This is especially dangerous when the resource is related to program configuration, execution or sensitive user data. Architecture and Design / Implementation / Installation / Operation Language-independent
2. 보안기능 The developer may set loose permissions in order to minimize problems when the user first runs the program, then create documentation stating that permissions should be tightened. Since system administrators and users do not always read the documentation, this can result in insecure permissions being left unchanged. The developer might make certain assumptions about the environment in which the software runs - e.g., that the software is running on a single-user system, or the software is only accessible to trusted administrators. When the software is running in a different environment, the permissions become a problem.
2. 보안기능 Confidentiality: Read application data; Read files or directories An attacker may be able to read sensitive information from the associated resource, such as credentials or configuration information stored in a file. Access Control: Gain privileges / assume identity An attacker may be able to modify critical properties of the associated resource to gain privileges, such as replacing a world-writable executable with a Trojan horse. Integrity Other: Modify application data; Other An attacker may be able to destroy or corrupt critical data in the associated resource, such as deletion of records from a database.
Bad Code 2. 보안기능 // 파일권한 : rw-rw-rw-, 디렉터리권한 : rwxrwxrwx String cmd = "umask 0"; File file = new File("/home/report/report.txt");... Runtime.getRuntime().exec(cmd);
Good Code // 파일권한 : rw-------, 디렉터리권한 : rwx------ String cmd = "umask 77"; File file = new File("/home/report/report.txt");... Runtime.getRuntime().exec(cmd);
4. 취약한암호화알고리즘사용 2. 보안기능 CWE-327: Use of a Broken or Risky Cryptographic Algorithm The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information. The use of a non-standard algorithm is dangerous because a determined attacker may be able to break the algorithm and compromise whatever data has been protected. Well-known techniques may exist to break the algorithm. Architecture and Design Language-independent
2. 보안기능
2. 보안기능 Confidentiality: Read application data The confidentiality of sensitive data may be compromised by the use of a broken or risky cryptographic algorithm. Integrity: Modify application data The integrity of sensitive data may be compromised by the use of a broken or risky cryptographic algorithm. Accountability Non-Repudiation: Hide activities If the cryptographic algorithm is used to ensure the identity of the source of the data (such as digital signatures), then a broken algorithm will compromise this scheme and the source of the data cannot be proven.
2. 보안기능 블록암호운영모드 메시지인증코드 난수발생기 분류 최소안전성수준 블록암호 기밀성기밀성 / 인증 해쉬함수해쉬함수기반블록기반 공개키암호 전자서명 키설정방식 해쉬함수 /HMAC 기반 블록기반 보호함수목록 112 비트 ARIA( 키길이 : 128/192/256), SEED( 키길이 : 128) ECD, CBC, CFB, OFB, CTR CCM, GCM SHA-224/256/384/512 HMAC CMAC, GMAC HASH_DRBG, HMAC_DRBG CTR_DRBG RSAES - ( 공개키길이 ) 2048, 3072 - RSA-OAEP 에서사용되는해쉬함수 : SHA-224/256 RSA-PSS, KCDSA, ECDSA, EC-KCDSA DH, ECDH
Bad Code 2. 보안기능 try { Cipher c = Cipher.getInstance("DES"); c.init(cipher.encrypt_mode, k); rslt = c.update(msg); } catch (InvalidKeyException e) {
Good Code try { Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding"); c.init(cipher.encrypt_mode, k); rslt = c.update(msg); } catch (InvalidKeyException e) {
5. 사용자중요정보평문저장 ( 또는전송 ) 2. 보안기능 CWE-311: Missing Encryption of Sensitive Data The software does not encrypt sensitive or critical information before storage or transmission. The lack of proper data encryption passes up the guarantees of confidentiality, integrity, and accountability that properly implemented encryption conveys. Architecture and Design / Operation Language-independent
2. 보안기능 Confidentiality: Read application data If the application does not use a secure channel, such as SSL, to exchange sensitive information, it is possible for an attacker with access to the network traffic to sniff packets from the connection and uncover the data. This attack is not technically difficult, but does require physical access to some portion of the network over which the sensitive data travels. This access is usually somewhere near where the user is connected to the network (such as a colleague on the company network) but can be anywhere along the path from the user to the end server.
2. 보안기능 Confidentiality Integrity: Modify application data Omitting the use of encryption in any program which transfers data over a network of any kind should be considered on par with delivering the data sent to each user on the local networks of both the sender and receiver. Worse, this omission allows for the injection of data into a stream of communication between two parties -- with no means for the victims to separate valid data from invalid. In this day of widespread network attacks and password collection sniffers, it is an unnecessary risk to omit encryption from the design of any system which might benefit from it.
2. 보안기능 5. 사용자중요정보평문저장 ( 또는전송 ) [1/2] 발생원인 암호화를수행하지않은상태에서전송 / 저장시발생 영향 스니핑 /SQL Injection 등을통한데이터노출등
Bad Code 2. 보안기능 void foo() { try { Socket socket = new Socket("taranis", 4444); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); String password = getpassword(); out.write(password); } catch (FileNotFoundException e) {...
Good Code void foo() { try { Socket socket = new Socket("taranis", 4444); PrintStream out = new PrintStream(socket.getOutputStream(), true); Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding"); String password = getpassword(); encryptedstr= c.update(password.getbytes()); out.write(encryptedstr,0,encryptedstr.length); } catch (FileNotFoundException e) {
2. 보안기능 https (Secure Hypertext Transfer Protocol) 웹에서의암호화통신을위해만들어진 http의강화버전 TCP/IP 포트는 443 SSL이나 TLS를사용
6. 하드코드된패스워드 2. 보안기능 CWE-259: Use of Hard-coded Password The software contains a hard-coded password, which it uses for its own inbound authentication or for outbound communication to external components. A hard-coded password typically leads to a significant authentication failure that can be difficult for the system administrator to detect. Once detected, it can be difficult to fix, so the administrator may be forced into disabling the product entirely. There are two main variations:
2. 보안기능
2. 보안기능 Inbound: the software contains an authentication mechanism that checks for a hard-coded password. In the Inbound variant, a default administration account is created, and a simple password is hard-coded into the product and associated with that account. This hard-coded password is the same for each installation of the product, and it usually cannot be changed or disabled by system administrators without manually modifying the program, or otherwise patching the software. If the password is ever discovered or published (a common occurrence on the Internet), then anybody with knowledge of this password can access the product. Finally, since all installations of the software will have the same password, even across different organizations, this enables massive attacks such as worms to take place. Outbound: the software connects to another system or component, and it contains hardcoded password for connecting to that component. The Outbound variant applies to frontend systems that authenticate with a back-end service. The back-end service may require a fixed password which can be easily discovered. The programmer may simply hard-code those back-end credentials into the front-end software. Any user of that program may be able to extract the password. Client-side systems with hard-coded passwords pose even more of a threat, since the extraction of a password from a binary is usually very simple.
2. 보안기능 Implementation / Architecture and Design Language-independent Access Control: Gain privileges / assume identity If hard-coded passwords are used, it is almost certain that malicious users will gain access through the account in question.
Bad Code 2. 보안기능 public Connection DBConnect(String url, String id) { try { conn = DriverManager.getConnection(url, id, "tiger"); } catch (SQLException e) { System.err.println("..."); } return conn; } }
Good Code try { String url = props.getproperty("url"); String id = props.getproperty("id"); String pwd = props.getproperty("passwd"); byte[] decrypted_pwd = cipher.dofinal(pwd.getbytes()); pwd = new String(decrypted_pwd); conn = DriverManager.getConnection(url, id, pwd);
7. 충분하지않은키길이사용 2. 보안기능 CWE-326: Inadequate Encryption Strength The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required. A weak encryption scheme can be subjected to brute force attacks that have a reasonable chance of succeeding using current attack methods and resources. Architecture and Design All Languages Access Control Confidentiality: Bypass protection mechanism; Read application data An attacker may be able to decrypt the data using brute force attacks.
Bad Code 2. 보안기능 public void target() throws NoSuchAlgorithmException { KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); // Key generator 의불충분한키크기 keygen.initialize(512); KeyPair mykeys = keygen.generatekeypair(); }
Good Code public void target() throws NoSuchAlgorithmException { KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); // Key generator 의값은최소 1024bit 로설정한다. keygen.initialize(1024); KeyPair mykeys = keygen.generatekeypair(); }