permissions := strconv.Atoi(os.Getenv("filePermissions"));
fMode := os.FileMode(permissions)
os.chmod(filePath, fMode);
...
String permissionMask = System.getProperty("defaultFileMask");
Path filePath = userFile.toPath();
...
Set<PosixFilePermission> perms = PosixFilePermissions.fromString(permissionMask);
Files.setPosixFilePermissions(filePath, perms);
...
$rName = $_GET['publicReport'];
chmod("/home/". authenticateUser . "/public_html/" . rName,"0755");
...
../../localuser/public_html/.htpasswd
" 등과 같이 publicReport
에 대해 악성 값을 제공할 경우, 응용 프로그램은 지정된 파일을 공격자가 읽을 수 있게 합니다.
...
$mask = $CONFIG_TXT['perms'];
chmod($filename,$mask);
...
permissions = os.getenv("filePermissions");
os.chmod(filePath, permissions);
...
...
rName = req['publicReport']
File.chmod("/home/#{authenticatedUser}/public_html/#{rName}", "0755")
...
../../localuser/public_html/.htpasswd
" 등과 같이 publicReport
에 대해 악성 값을 제공할 경우, 응용 프로그램은 지정된 파일을 공격자가 읽을 수 있게 합니다.
...
mask = config_params['perms']
File.chmod(filename, mask)
...
crossdomain.xml
구성 파일의 적절한 설정을 통해 정책을 수정할 수 있습니다. 그러나, 지나치게 허용적인 도메인 간 정책을 사용하면 악성 응용 프로그램이 부적절한 방법으로 피해자 응용 프로그램과 통신하여 스푸핑, 데이터 도난, 릴레이 및 기타 공격으로 이어질 수 있기 때문에 설정 변경 시 주의해야 합니다.
flash.system.Security.allowDomain("*");
*
를 allowDomain()
에 대한 인수로 사용하는 것은 응용 프로그램의 데이터가 임의의 도메인에서 다른 SWF 응용 프로그램으로 접근할 수 있음을 나타냅니다.crossdomain.xml
구성 파일의 적절한 설정을 통해 정책을 수정할 수 있습니다. Flash Player 9,0,124,0부터 Adobe는 Flash Player에서 여러 도메인에 걸쳐 보낼 수 있는 사용자 지정 헤더를 정의하는 기능도 도입했습니다. 그러나 지나치게 허용적인 도메인 간 정책과 함께 적용할 경우, 지나치게 허용적인 사용자 지정 헤더 정책은 선택된 헤더를 악성 응용 프로그램이 대상 응용 프로그램으로 전송할 수 있어, 수신한 헤더를 처리하지 못하는 응용 프로그램 실행 시 다양한 공격으로 이어지거나 오류가 발생할 수 있기 때문에 이러한 설정 정의 시 주의해야 합니다.
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>
*
를 headers
속성 값으로 사용하면 모든 헤더가 여러 도메인에 걸쳐 전송됨을 나타냅니다.crossdomain.xml
구성 파일의 적절한 설정을 통해 정책을 수정할 수 있습니다. 그러나, 지나치게 허용적인 도메인 간 정책을 사용하면 악성 응용 프로그램이 부적절한 방법으로 피해자 응용 프로그램과 통신하여 스푸핑, 데이터 도난, 릴레이 및 기타 공격으로 이어질 수 있기 때문에 설정에 영향을 미칠 수 있는 사람을 결정할 때 주의해야 합니다. 정책 제한 무시 취약점은 다음과 같은 경우 발생합니다.예제 2: 다음 코드는 로드한 SWF 파일에 대한 매개변수 중 하나의 값을 사용하여 신뢰할 수 있는 도메인 목록을 정의합니다.
...
var params:Object = LoaderInfo(this.root.loaderInfo).parameters;
var url:String = String(params["url"]);
flash.system.Security.loadPolicyFile(url);
...
...
var params:Object = LoaderInfo(this.root.loaderInfo).parameters;
var domain:String = String(params["domain"]);
flash.system.Security.allowDomain(domain);
...
crossdomain.xml
구성 파일의 적절한 설정을 통해 이 제한을 수정할 수 있습니다. 그러나 HTTP로 로드한 SWF 응용 프로그램은 MITM(Man-In-The-Middle) 공격을 받을 수 있으므로 이러한 설정 정의 시 주의해야 하며, 따라서 신뢰하지 말아야 합니다.allowInsecureDomain()
을 호출하여 HTTP로 로드된 SWF 응용 프로그램이 HTTPS로 로드된 SWF 응용 프로그램의 데이터에 접근하는 것을 막는 제한을 끕니다.
flash.system.Security.allowInsecureDomain("*");
services-config.xml
설명 파일이 “Logging” XML 요소를 지정하여 로깅의 다양한 부분을 설명합니다. 다음과 같습니다.
<logging>
<target class="flex.messaging.log.ConsoleTarget" level="Debug">
<properties>
<prefix>[BlazeDS]</prefix>
<includeDate>false</includeDate>
<includeTime>false</includeTime>
<includeLevel>false</includeLevel>
<includeCategory>false</includeCategory>
</properties>
<filters>
<pattern>Endpoint.*</pattern>
<pattern>Service.*</pattern>
<pattern>Configuration</pattern>
</filters>
</target>
</logging>
target
태그는 level
라는 옵션 속성을 갖습니다. 이는 로그 레벨을 나타냅니다. 디버그 수준이 너무 자세한 수준으로 설정되어 있으면 응용 프로그램에서 민감한 데이터를 로그 파일에 쓸 수 있습니다.sprintf()
, FormatMessageW()
또는 syslog()
와 같은 함수에 format string 인수로서 전달됩니다.snprintf()
를 사용하여 명령줄 인수를 버퍼에 복사합니다.
int main(int argc, char **argv){
char buf[128];
...
snprintf(buf,128,argv[1]);
}
%x
)를 제공하여 스택의 내용을 읽을 수 있습니다. (이 예제에서는 함수가 서식 지정할 인수를 받지 않습니다.) 공격자는 %n
서식 지정자를 사용하여 스택에 쓸 수 있으므로(의도한 동작인 인수에서 값을 읽는 대신) snprintf()
가 지정한 인수에 지금까지 출력한 바이트 수를 쓰도록 합니다. 이 공격의 정교한 버전은 네 가지 서식 지정자(staggered write)를 사용하여 스택의 포인터 값을 완전히 제어합니다.
printf("%d %d %1$d %1$d\n", 5, 9);
5 9 5 5
Example 1
에서 언급한 것과 같이 네 개의 서식 지정자를 사용하는 것보다 공격을 수행하는 것이 훨씬 간단해집니다.syslog()
함수는 다음과 같이 사용됩니다.
...
syslog(LOG_ERR, cmdBuf);
...
syslog()
의 두 번째 매개 변수가 format string이기 때문에 cmdBuf
에 포함된 서식 지정자는 Example 1
에서 설명한 방식으로 해석됩니다.syslog()
사용 예를 보여줍니다.
...
syslog(LOG_ERR, "%s", cmdBuf);
...
sprintf()
, FormatMessageW()
, syslog()
, NSLog
또는 NSString.stringWithFormat
과 같은 함수에 format string 인수로서 전달됩니다.NSString.stringWithFormat:
의 format string으로 명령줄 인수를 활용합니다.
int main(int argc, char **argv){
char buf[128];
...
[NSString stringWithFormat:argv[1], argv[2] ];
}
%x
)를 제공하여 스택의 내용을 읽을 수 있습니다. (이 예제에서는 함수가 서식 지정할 인수를 받지 않습니다.)
printf("%d %d %1$d %1$d\n", 5, 9);
5 9 5 5
Example 1
에서 언급한 것과 같이 네 개의 서식 지정자를 사용하는 것보다 공격을 수행하는 것이 훨씬 간단해집니다.syslog()
함수는 다음과 같이 사용됩니다.
...
syslog(LOG_ERR, cmdBuf);
...
syslog()
의 두 번째 매개 변수가 format string이기 때문에 cmdBuf
에 포함된 서식 지정자는 Example 1
에서 설명한 방식으로 해석됩니다.syslog()
사용 예를 보여줍니다.예제 4: Apple 코어 클래스는 format string 취약점을 익스플로이트하기 위한 흥미로운 방안을 제공합니다.
...
syslog(LOG_ERR, "%s", cmdBuf);
...
String.stringByAppendingFormat()
함수는 다음과 같이 사용됩니다.
...
NSString test = @"Sample Text.";
test = [test stringByAppendingFormat:[MyClass
formatInput:inputControl.text]];
...
stringByAppendingFormat()
사용 예를 보여줍니다.
...
NSString test = @"Sample Text.";
test = [test stringByAppendingFormat:@"%@", [MyClass
formatInput:inputControl.text]];
...
strncpy()
와 같은 범위 지정 함수도 잘못 사용되면 취약점을 일으킬 수 있습니다. 대부분의 buffer overflow의 원인은 메모리 조작과 데이터의 크기 또는 구성에 대한 가정 위반이 결합된 것입니다.
void wrongNumberArgs(char *s, float f, int d) {
char buf[1024];
sprintf(buf, "Wrong number of %.512s");
}
strncpy()
와 같은 범위 지정 함수도 잘못 사용되면 취약점을 일으킬 수 있습니다. 대부분의 buffer overflow의 원인은 메모리 조작과 데이터의 크기 또는 구성에 대한 가정 위반이 결합된 것입니다.%d
포맷 지정자를 사용하여 float에서 f
를 잘못 변환합니다.
void ArgTypeMismatch(float f, int d, char *s, wchar *ws) {
char buf[1024];
sprintf(buf, "Wrong type of %d", f);
...
}
...
String lang = Request.Form["lang"];
WebClient client = new WebClient();
client.BaseAddress = url;
NameValueCollection myQueryStringCollection = new NameValueCollection();
myQueryStringCollection.Add("q", lang);
client.QueryString = myQueryStringCollection;
Stream data = client.OpenRead(url);
...
en&poll_id=1
같은 lang
을 제공할 가능성을 고려하지 않았기 때문에 공격자는 마음대로 poll_id
를 변경할 수 있게 됩니다.
...
String lang = request.getParameter("lang");
GetMethod get = new GetMethod("http://www.example.com");
get.setQueryString("lang=" + lang + "&poll_id=" + poll_id);
get.execute();
...
en&poll_id=1
같은 lang
을 제공할 가능성을 고려하지 않았기 때문에 공격자는 마음대로 poll_id
를 변경할 수 있게 됩니다.
<%
...
$id = $_GET["id"];
header("Location: http://www.host.com/election.php?poll_id=" . $id);
...
%>
name=alice
를 지정했지만 name=alice&
를 더 추가했으며, 첫 번째 것을 가져오는 서버에서 이것이 사용되면 alice
로 가장하여 이 사용자의 계정에 대한 추가 정보를 획득할 수 있습니다.allowBackup
속성을 true
(기본값)로 설정하고 <application>
태그에서 backupAgent
속성을 정의하면 됩니다.Environment.getExternalStorageDirectory()
는 Android 장치의 외부 저장소에 대한 참조를 반환합니다.private void WriteToFile(String what_to_write) {
try{
File root = Environment.getExternalStorageDirectory();
if(root.canWrite()) {
File dir = new File(root + "write_to_the_SDcard");
File datafile = new File(dir, number + ".extension");
FileWriter datawriter = new FileWriter(datafile);
BufferedWriter out = new BufferedWriter(datawriter);
out.write(what_to_write);
out.close();
}
}
}
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
:kSecAttrAccessibleAlways
:kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
:kSecAttrAccessibleAlwaysThisDeviceOnly
:kSecAttrAccessibleWhenUnlocked
:kSecAttrAccessibleWhenUnlockedThisDeviceOnly
:ThisDeviceOnly
가 포함되지 않은 액세스 가능성 수준은 iCloud로 백업되며 모든 장치로 복원할 수 있는 암호화되지 않은 백업을 사용 중이더라도 iTunes로 백업됩니다. 이 경우 저장된 데이터의 민감도 및 개인 정보 관련성에 따라 개인 정보 문제가 발생할 수 있습니다.
...
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSData *token = [@"secret" dataUsingEncoding:NSUTF8StringEncoding];
// Configure KeyChain Item
[dict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id) kSecClass];
[dict setObject:token forKey:(__bridge id)kSecValueData];
...
[dict setObject:(__bridge id)kSecAttrAccessibleWhenUnlocked forKey:(__bridge id) kSecAttrAccessible];
OSStatus error = SecItemAdd((__bridge CFDictionaryRef)dict, NULL);
...
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
:kSecAttrAccessibleAlways
:kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
:kSecAttrAccessibleAlwaysThisDeviceOnly
:kSecAttrAccessibleWhenUnlocked
:kSecAttrAccessibleWhenUnlockedThisDeviceOnly
:ThisDeviceOnly
가 포함되지 않은 액세스 가능성 수준은 iCloud로 백업되며 모든 장치로 복원할 수 있는 암호화되지 않은 백업을 사용 중이더라도 iTunes로 백업됩니다. 이 경우 저장된 데이터의 민감도 및 개인 정보 관련성에 따라 개인 정보 문제가 발생할 수 있습니다.
...
// Configure KeyChain Item
let token = "secret"
var query = [String : AnyObject]()
query[kSecClass as String] = kSecClassGenericPassword
query[kSecValueData as String] = token as AnyObject?
...
query[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlocked
SecItemAdd(query as CFDictionary, nil)
...
protected void onCreate(Bundle savedInstanceState) {
...
try {
File httpCacheDir = new File(context.getExternalCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) {
Log.i(TAG, "HTTP response cache installation failed:" + e);
}
}
protected void onStop() {
...
HttpResponseCache cache = HttpResponseCache.getInstalled();
if (cache != null) {
cache.flush();
}
}
{app ID}/Library/Caches/com.mycompany.myapp/Cache.db*
파일에 저장합니다.{app ID}/Library/Caches/com.mycompany.myapp/Cache.db*
파일에 저장합니다.{app ID}/Library/Caches/com.mycompany.myapp/Cache.db*
파일에 저장합니다. URLCache
클래스의 diskCapacity
또는 memoryCapacity
속성을 0으로 설정하여 HTTP(S) 응답 캐시 시스템을 실제로 비활성화했다고 생각할 수 있습니다. 하지만 NSURLCache
설명서에는, 장치의 메모리 또는 디스크 공간이 부족한 경우에만 디스크 및 메모리 캐시가 구성된 크기로 잘린다고 명시되어 있습니다. 두 설정은 보안 제어의 용도가 아니라 시스템이 시스템 리소스를 확보하여 성능을 향상시키기 위한 용도입니다.{app ID}/Library/Caches/com.mycompany.myapp/Cache.db*
파일에 저장합니다. URLCache
클래스의 diskCapacity
또는 memoryCapacity
속성을 0으로 설정하여 HTTP(S) 응답 캐시 시스템을 실제로 비활성화했다고 생각할 수 있습니다. 하지만 NSURLCache
설명서에는, 장치의 메모리 또는 디스크 공간이 부족한 경우에만 디스크 및 메모리 캐시가 구성된 크기로 잘린다고 명시되어 있습니다. 두 설정은 보안 제어의 용도가 아니라 시스템이 시스템 리소스를 확보하여 성능을 향상시키기 위한 용도입니다.NSFileManager
인스턴스와 연결된 NSDictionary
의 NSFileProtectionKey
키 값으로 할당되는 상수로 NSFileManager
에 대해 정의됩니다. setAttributes:ofItemAtPath:error:
, attributesOfItemAtPath:error:
, createFileAtPath:contents:attributes:
등의 NSFileManager
함수를 사용하면 파일을 만들거나 파일의 데이터 보호 클래스를 수정할 수 있습니다. 또한 NSData
개체에 대해서도 해당하는 데이터 보호 상수가 NSDataWritingOptions
로 정의되며, 이는 NSData
함수 writeToURL:options:error:
및 writeToFile:options:error:
에 options
인수로 전달할 수 있습니다. NSFileManager
및 NSData
에 지정되는 다양한 데이터 보호 클래스 상수의 정의는 다음과 같습니다.NSFileProtectionComplete
, NSDataWritingFileProtectionComplete
:NSFileProtectionCompleteUnlessOpen
, NSDataWritingFileProtectionCompleteUnlessOpen
:NSFileProtectionCompleteUntilFirstUserAuthentication
, NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
:NSFileProtectionNone
, NSDataWritingFileProtectionNone
:NSFileProtectionCompleteUnlessOpen
또는 NSFileProtectionCompleteUntilFirstUserAuthentication
으로 표시하면 사용자의 암호 및 장치의 UID에서 파생된 키를 사용하여 암호화할 수 있으며 특정 상황에서도 계속해서 데이터에 접근할 수 있습니다. NSFileProtectionCompleteUnlessOpen
또는 NSFileProtectionCompleteUntilFirstUserAuthentication
을 이와 같이 사용하는 경우 신중하게 검토하여 NSFileProtectionComplete
를 통한 추가 보호가 보증되는지를 확인해야 합니다.예제 2: 다음 예제에서는 지정된 데이터가 사용자가 장치를 켜고 암호를 처음 입력할 때까지만 보호됩니다(다음 재부팅 시까지).
...
filepath = [self.GetDocumentDirectory stringByAppendingPathComponent:self.setFilename];
...
NSDictionary *protection = [NSDictionary dictionaryWithObject:NSFileProtectionCompleteUntilFirstUserAuthentication forKey:NSFileProtectionKey];
...
[[NSFileManager defaultManager] setAttributes:protection ofItemAtPath:filepath error:nil];
...
BOOL ok = [testToWrite writeToFile:filepath atomically:YES encoding:NSUnicodeStringEncoding error:&err];
...
...
filepath = [self.GetDocumentDirectory stringByAppendingPathComponent:self.setFilename];
...
NSData *textData = [textToWrite dataUsingEncoding:NSUnicodeStingEncoding];
...
BOOL ok = [textData writeToFile:filepath options:NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication error:&err];
...
NSFileManager
인스턴스와 연결된 Dictionary
의 NSFileProtectionKey
키 값으로 할당되는 상수로 NSFileManager
에서 정의됩니다. setAttributes(_:ofItemAtPath:)
, attributesOfItemAtPath(_:)
, createFileAtPath(_:contents:attributes:)
등의 NSFileManager
함수를 사용하면 파일을 만들거나 파일의 데이터 보호 클래스를 수정할 수 있습니다. 또한 NSDataWritingOptions
열거의 NSData
개체에 대해서도 해당하는 데이터 보호 상수가 정의됩니다. 이 상수는 NSData
함수에 대한 options
인수로 전달할 수 있으며, 해당 함수는
writeToFile(_:options:)
등이 있습니다. NSFileManager
및 NSData
에 지정되는 다양한 데이터 보호 클래스 상수의 정의는 다음과 같습니다.NSFileProtectionComplete
, NSDataWritingOptions.DataWritingFileProtectionComplete
:NSFileProtectionCompleteUnlessOpen
, NSDataWritingOptions.DataWritingFileProtectionCompleteUnlessOpen
:NSFileProtectionCompleteUntilFirstUserAuthentication
, NSDataWritingOptions.DataWritingFileProtectionCompleteUntilFirstUserAuthentication
:NSFileProtectionNone
, NSDataWritingOptions.DataWritingFileProtectionNone
:NSFileProtectionCompleteUnlessOpen
또는 NSFileProtectionCompleteUntilFirstUserAuthentication
으로 표시하면 사용자의 암호 및 장치의 UID에서 파생된 키를 사용하여 암호화할 수 있으며 특정 상황에서도 계속해서 데이터에 접근할 수 있습니다. NSFileProtectionCompleteUnlessOpen
또는 NSFileProtectionCompleteUntilFirstUserAuthentication
을 이와 같이 사용하는 경우 신중하게 검토하여 NSFileProtectionComplete
를 통한 추가 보호가 보증되는지를 확인해야 합니다.예제 2: 다음 예에서는 지정된 데이터가 사용자가 장치를 켜고 암호를 처음 입력할 때까지만 보호됩니다(다음 재부팅 시까지).
...
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let filename = "\(documentsPath)/tmp_activeTrans.txt"
let protection = [NSFileProtectionKey: NSFileProtectionCompleteUntilFirstUserAuthentication]
do {
try NSFileManager.defaultManager().setAttributes(protection, ofItemAtPath: filename)
} catch let error as NSError {
NSLog("Unable to change attributes: \(error.debugDescription)")
}
...
BOOL ok = textToWrite.writeToFile(filename, atomically:true)
...
...
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let filename = "\(documentsPath)/tmp_activeTrans.txt"
...
BOOL ok = textData.writeToFile(filepath, options: .DataWritingFileProtectionCompleteUntilFirstUserAuthentication);
...
kSecAttrAccessible
키에 대한 값으로 할당됩니다. 다양한 키 집합 액세스 가능성 상수에 대한 정의는 다음과 같습니다.kSecAttrAccessibleAfterFirstUnlock
:kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
:kSecAttrAccessibleAlways
:kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
:kSecAttrAccessibleAlwaysThisDeviceOnly
:kSecAttrAccessibleWhenUnlocked
:kSecAttrAccessibleWhenUnlockedThisDeviceOnly
:kSecAttrAccessibleAfterFirstUnlock
으로 표시하면 사용자의 암호 및 장치의 UID에서 파생된 키를 사용하여 암호화할 수 있으며 특정 상황에서도 계속해서 데이터에 액세스할 수 있습니다. kSecAttrAccessibleAfterFirstUnlock
의 사용을 신중하게 검토하여 추가 보호가 보증되는지 확인해야 합니다.
...
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSData *token = [@"secret" dataUsingEncoding:NSUTF8StringEncoding];
// Configure KeyChain Item
[dict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id) kSecClass];
[dict setObject:token forKey:(__bridge id)kSecValueData];
...
[dict setObject:(__bridge id)kSecAttrAccessibleAfterFirstUnlock forKey:(__bridge id) kSecAttrAccessible];
OSStatus error = SecItemAdd((__bridge CFDictionaryRef)dict, NULL);
...
kSecAttrAccessible
키에 대한 값으로 할당됩니다. 다양한 키 집합 액세스 가능성 상수에 대한 정의는 다음과 같습니다.kSecAttrAccessibleAfterFirstUnlock
:kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
:kSecAttrAccessibleAlways
:kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
:kSecAttrAccessibleAlwaysThisDeviceOnly
:kSecAttrAccessibleWhenUnlocked
:kSecAttrAccessibleWhenUnlockedThisDeviceOnly
:kSecAttrAccessibleAfterFirstUnlock
으로 표시하면 사용자의 암호 및 장치의 UID에서 파생된 키를 사용하여 암호화할 수 있으며 특정 상황에서도 계속해서 데이터에 액세스할 수 있습니다. kSecAttrAccessibleAfterFirstUnlock
의 사용을 신중하게 검토하여 추가 보호가 보증되는지 확인해야 합니다.
...
// Configure KeyChain Item
let token = "secret"
var query = [String : AnyObject]()
query[kSecClass as String] = kSecClassGenericPassword
query[kSecValueData as String] = token as AnyObject?
...
query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
SecItemAdd(query as CFDictionary, nil)
...
NSFileManager
인스턴스와 연결된 NSDictionary
의 NSFileProtectionKey
키 값으로 할당되는 상수로 NSFileManager
에 대해 정의됩니다. setAttributes:ofItemAtPath:error:
, attributesOfItemAtPath:error:
, createFileAtPath:contents:attributes:
등의 NSFileManager
함수를 사용하면 파일을 만들거나 파일의 데이터 보호 클래스를 수정할 수 있습니다. 또한 NSData
개체에 대해서도 해당하는 데이터 보호 상수가 NSDataWritingOptions
로 정의되며, 이는 NSData
함수 writeToURL:options:error:
및 writeToFile:options:error:
에 options
인수로 전달할 수 있습니다. NSFileManager
및 NSData
에 지정되는 다양한 데이터 보호 클래스 상수의 정의는 다음과 같습니다.NSFileProtectionComplete
, NSDataWritingFileProtectionComplete
:NSFileProtectionCompleteUnlessOpen
, NSDataWritingFileProtectionCompleteUnlessOpen
:NSFileProtectionCompleteUntilFirstUserAuthentication
, NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
:NSFileProtectionNone
, NSDataWritingFileProtectionNone
:NSFileProtectionNone
을 지정하면 장치의 UID만을 토대로 파생된 키를 사용하여 암호화됩니다. 이렇게 되면 암호로 잠겨 있는 경우나 부팅할 때를 비롯해 장치가 켜져 있을 때는 언제든지 이러한 파일에 접근할 수 있게 됩니다. NSFileProtectionNone
을 이와 같이 사용하는 경우 신중하게 검토하여 더 엄격한 데이터 보호 클래스를 통한 추가 보호가 보증되는지를 확인해야 합니다.예제 2: 다음 예제에서는 지정된 데이터가 보호되지 않습니다(장치가 켜져 있을 때는 언제든지 접근 가능).
...
filepath = [self.GetDocumentDirectory stringByAppendingPathComponent:self.setFilename];
...
NSDictionary *protection = [NSDictionary dictionaryWithObject:NSFileProtectionNone forKey:NSFileProtectionKey];
...
[[NSFileManager defaultManager] setAttributes:protection ofItemAtPath:filepath error:nil];
...
BOOL ok = [testToWrite writeToFile:filepath atomically:YES encoding:NSUnicodeStringEncoding error:&err];
...
...
filepath = [self.GetDocumentDirectory stringByAppendingPathComponent:self.setFilename];
...
NSData *textData = [textToWrite dataUsingEncoding:NSUnicodeStingEncoding];
...
BOOL ok = [textData writeToFile:filepath options:NSDataWritingFileProtectionNone error:&err];
...
NSFileManager
에서 NSFileManager
인스턴스와 연결된 Dictionary
의 NSFileProtectionKey
키 값으로 할당되는 상수로 정의됩니다. setAttributes(_:ofItemAtPath:)
, attributesOfItemAtPath(_:)
, createFileAtPath(_:contents:attributes:)
등의 NSFileManager
함수를 사용하면 파일을 만들거나 파일의 데이터 보호 클래스를 수정할 수 있습니다. 또한 NSDataWritingOptions
열거의 NSData
개체에 대해서도 해당하는 데이터 보호 상수가 정의됩니다. 이 상수는 NSData
함수에 대한 options
인수로 전달할 수 있으며, 이러한 함수로는
writeToFile(_:options:)
등이 있습니다. NSFileManager
및 NSData
에 지정되는 다양한 데이터 보호 클래스 상수의 정의는 다음과 같습니다.NSFileProtectionComplete
, NSDataWritingOptions.DataWritingFileProtectionComplete
:NSFileProtectionCompleteUnlessOpen
, NSDataWritingOptions.DataWritingFileProtectionCompleteUnlessOpen
:NSFileProtectionCompleteUntilFirstUserAuthentication
, NSDataWritingOptions.DataWritingFileProtectionCompleteUntilFirstUserAuthentication
:NSFileProtectionNone
, NSDataWritingOptions.DataWritingFileProtectionNone
:NSFileProtectionNone
을 지정하면 장치의 UID만을 토대로 파생된 키를 사용하여 암호화됩니다. 이렇게 되면 암호로 잠겨 있는 경우나 부팅할 때를 비롯해 장치가 켜져 있을 때는 언제든지 이러한 파일에 접근할 수 있게 됩니다. NSFileProtectionNone
을 이와 같이 사용하는 경우 신중하게 검토하여 더 엄격한 데이터 보호 클래스를 통한 추가 보호가 보증되는지를 확인해야 합니다.예제 2: 다음 예에서는 지정된 데이터가 보호되지 않습니다(장치가 켜져 있을 때는 언제든지 접근 가능).
...
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let filename = "\(documentsPath)/tmp_activeTrans.txt"
let protection = [NSFileProtectionKey: NSFileProtectionNone]
do {
try NSFileManager.defaultManager().setAttributes(protection, ofItemAtPath: filename)
} catch let error as NSError {
NSLog("Unable to change attributes: \(error.debugDescription)")
}
...
BOOL ok = textToWrite.writeToFile(filename, atomically:true)
...
...
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let filename = "\(documentsPath)/tmp_activeTrans.txt"
...
BOOL ok = textData.writeToFile(filepath, options: .DataWritingFileProtectionNone);
...