chroot()
操作的被提升的權限等級,應該在操作後馬上被丟棄。chroot()
) 時,它必須先取得 root
權限。當權限操作完成後,程式應該馬上丟棄 root
權限並且回傳呼叫它的使用者權限等級。chroot()
將應用程式限制到 APP_HOME
下的檔案系統子集,這是為了防止攻擊者使用程式對位於別處的檔案進行未經授權的存取。然後程式碼就會開啟使用者指定的檔案並處理檔案目錄。
...
chroot(APP_HOME);
chdir("/");
FILE* data = fopen(argv[1], "r+");
...
setuid()
的呼叫,意味著應用程式仍然繼續在使用沒有必要的 root
權限進行操作。只要攻擊者成功利用應用程式,就會引發權限提升攻擊,因為所有的惡意操作都將以超級使用者的權限來執行。如果應用程式把權限等級降低為非 root
使用者,那麼潛在的破壞立即會下降許多。
Page.EnableViewStateMac = false;
authorized_networks
區塊中將 value
設為 0.0.0.0/0
。/0
的 CIDR 區塊會接受來自 0.0.0.0 和 255.255.255.255 之間任何 IP 位址的連線。
resource "google_sql_database_instance" "db-demo" {
...
settings {
...
ip_configuration {
...
authorized_networks {
name = "any ip"
value = "0.0.0.0/0"
}
...
}
...
}
...
}
metadata
引數中將 serial-port-enable
設為 true
,來允許互動式序列主控台存取。
resource "google_compute_instance" "compute_instance_demo" {
...
metadata = {
serial-port-enable = true
...
}
...
}
main()
方法。雖然這在軟體產品的開發過程中是完全可接受的,但是屬於 J2EE 應用程式那部分的類別不應該定義 main()
。
...
var file:File = new File(directoryName + "\\" + fileName);
...
...
FileStream f = File.Create(directoryName + "\\" + fileName);
...
...
File file = new File(directoryName + "\\" + fileName);
...
...
os.open(directoryName + "\\" + fileName);
...
HttpRequest
類別以陣列存取形式 (例如 Request["myParam"]
) 提供對 QueryString
、Form
、Cookies
或 ServerVariables
集合中變數的程式化存取。存在多個名稱相同的變數時,.NET Framework 會傳回在集合中以下列順序搜尋時第一個出現的變數值:QueryString
、Form
、Cookies
,然後 ServerVariables
。因為 QueryString
依搜尋順序第一個出現,因此 QueryString
參數可以取代表單、Cookie 及伺服器變數的值。同樣地,表單值可以取代 Cookies
和 ServerVariables
集合中的變數,而 Cookies
集合的變數可取代 ServerVariables
的變數。
...
String toAddress = Request["email"]; //Expects cookie value
Double balance = GetBalance(userID);
SendAccountBalance(toAddress, balance);
...
http://www.example.com/GetBalance.aspx
時執行 Example 1
中的程式碼。若攻擊者能夠使通過驗證的使用者按下要求 http://www.example.com/GetBalance.aspx?email=evil%40evil.com
的連結,則含有使用者帳戶餘額的電子郵件將會送往 evil@evil.com
。HttpRequest
類別以陣列存取形式 (例如 Request["myParam"]
) 提供對 QueryString
、Form
、Cookies
或 ServerVariables
集合中變數的程式化存取。存在多個名稱相同的變數時,.NET Framework 會傳回在集合中以下列順序搜尋時第一個出現的變數值:QueryString
、Form
、Cookies
,然後 ServerVariables
。因為 QueryString
依搜尋順序第一個出現,因此 QueryString
參數可以取代表單、Cookie 及伺服器變數的值。同樣地,表單值可以取代 Cookies
和 ServerVariables
集合中的變數,而 Cookies
集合的變數可取代 ServerVariables
的變數。www.example.com
。
...
if (Request["HTTP_REFERER"].StartsWith("http://www.example.com"))
ServeContent();
else
Response.Redirect("http://www.example.com/");
...
http://www.example.com/ProtectedImages.aspx
時執行 Example 1
中的程式碼。若攻擊者對 URL 做一個直接的要求,則不會設定適當的 Referer 表頭,而要求將失敗。不過,若攻擊者以必要值提交偽造 HTTP_REFERER
參數 (如 http://www.example.com/ProtectedImages.aspx?HTTP_REFERER=http%3a%2f%2fwww.example.com
),則查詢將從 QueryString
傳回值,而不是 ServerVariables
,同時檢查也將成功。StreamReader
的 Finalize()
方法最終會呼叫 Close()
,但不確定何時會呼叫 Finalize()
方法。事實上,不確定是否會呼叫 Finalize()
。在忙碌的環境中,這可能會導致 VM 用盡它所有能使用的檔案控制碼。範例 2:在正常情況下,以下程式碼會執行資料庫查詢,處理資料庫傳回的結果並關閉分配的
private void processFile(string fName) {
StreamWriter sw = new StreamWriter(fName);
string line;
while ((line = sr.ReadLine()) != null)
processLine(line);
}
SqlConnection
物件。但是,如果在執行 SQL 或處理結果時發生異常,SqlConnection
物件將不會關閉。如果這種情況時常發生的話,那麼資料庫將會用盡可用指標,並且無法再執行任何 SQL 查詢。
...
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(queryString);
cmd.Connection = conn;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
HarvestResults(rdr);
conn.Connection.Close();
...
int decodeFile(char* fName)
{
char buf[BUF_SZ];
FILE* f = fopen(fName, "r");
if (!f) {
printf("cannot open %s\n", fName);
return DECODE_FAIL;
} else {
while (fgets(buf, BUF_SZ, f)) {
if (!checkChecksum(buf)) {
return DECODE_FAIL;
} else {
decodeBlock(buf);
}
}
}
fclose(f);
return DECODE_SUCCESS;
}
CALL "CBL_CREATE_FILE"
USING filename
access-mode
deny-mode
device
file-handle
END-CALL
IF return-code NOT = 0
DISPLAY "Error!"
GOBACK
ELSE
PERFORM write-data
IF ws-status-code NOT = 0
DISPLAY "Error!"
GOBACK
ELSE
DISPLAY "Success!"
END-IF
END-IF
CALL "CBL_CLOSE_FILE"
USING file-handle
END-CALL
GOBACK
.
New()
函數會建立與系統記錄常駐程式的新連線。它是 log.syslog 套件的一部分。每次寫入傳回的寫入器時,都會傳送一則含有指定優先順序 (系統記錄工具和嚴重性的組合) 和字首標籤的記錄訊息。因此,在繁忙的環境中,這可能會導致系統用盡其所有的通訊端。範例 2:在此範例中,
func TestNew() {
s, err := New(syslog.LOG_INFO|syslog.LOG_USER, "the_tag")
if err != nil {
if err.Error() == "Unix syslog delivery error" {
fmt.Println("skipping: syslogd not running")
}
fmt.Println("New() failed: %s", err)
}
}
net/smtp
套件的 Dial()
方法將傳回一個新用戶端,這個新用戶端會連線到位於 localhost 的 SMTP 伺服器。連線資源會被分配,但永遠不會透過呼叫 Close()
函數來釋放。
func testDial() {
client, _ := smtp.Dial("127.0.0.1")
client.Hello("")
}
Arena.ofConfined()
建立的資源沒有關閉。
...
Arena offHeap = Arena.ofConfined()
MemorySegment str = offHeap.allocateUtf8String("data");
...
//offHeap is never closed
BEGIN
...
F1 := UTL_FILE.FOPEN('user_dir','u12345.tmp','R',256);
UTL_FILE.GET_LINE(F1,V1,32767);
...
END;
DATA: result TYPE demo_update,
request TYPE REF TO IF_HTTP_REQUEST,
obj TYPE REF TO CL_SQL_CONNECTION.
TRY.
...
obj = cl_sql_connection=>get_connection( `R/3*my_conn`).
FINAL(sql) = NEW cl_sql_prepared_statement(
statement = `INSERT INTO demo_update VALUES( ?, ?, ?, ?, ?, ? )`).
CATCH cx_sql_exception INTO FINAL(exc).
...
ENDTRY.
SqlConnection
物件。但是,如果在執行 SQL 或處理結果時發生異常,SqlConnection
物件將不會關閉。如果這種情況時常發生的話,那麼資料庫將會用盡可用指標,並且無法再執行任何 SQL 查詢。
...
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(queryString);
cmd.Connection = conn;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
HarvestResults(rdr);
conn.Connection.Close();
...
- void insertUser:(NSString *)name {
...
sqlite3_stmt *insertStatement = nil;
NSString *insertSQL = [NSString stringWithFormat:@INSERT INTO users (name, age) VALUES (?, ?)];
const char *insert_stmt = [insertSQL UTF8String];
...
if ((result = sqlite3_prepare_v2(database, insert_stmt,-1, &insertStatement, NULL)) != SQLITE_OK) {
MyLog(@"%s: sqlite3_prepare error: %s (%d)", __FUNCTION__, sqlite3_errmsg(database), result);
return;
}
if ((result = sqlite3_step(insertStatement)) != SQLITE_DONE) {
MyLog(@"%s: step error: %s (%d)", __FUNCTION__, sqlite3_errmsg(database), result);
return;
}
...
}
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(CXN_SQL);
harvestResults(rs);
stmt.close();
func insertUser(name:String, age:int) {
let dbPath = URL(fileURLWithPath: Bundle.main.resourcePath ?? "").appendingPathComponent("test.sqlite").absoluteString
var db: OpaquePointer?
var stmt: OpaquePointer?
if sqlite3_open(dbPath, &db) != SQLITE_OK {
print("Error opening articles database.")
return
}
let queryString = "INSERT INTO users (name, age) VALUES (?,?)"
if sqlite3_prepare(db, queryString, -1, &stmt, nil) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
log("error preparing insert: \(errmsg)")
return
}
if sqlite3_bind_text(stmt, 1, name, -1, nil) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
log("failure binding name: \(errmsg)")
return
}
if sqlite3_bind_int(stmt, 2, age) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
log("failure binding name: \(errmsg)")
return
}
if sqlite3_step(stmt) != SQLITE_DONE {
let errmsg = String(cString: sqlite3_errmsg(db)!)
log("failure inserting user: \(errmsg)")
return
}
}
...
" Add Binary File to
CALL METHOD lr_abap_zip->add
EXPORTING
name = p_ifile
content = lv_bufferx.
" Read Binary File to
CALL METHOD lr_abap_zip->get
EXPORTING
name = p_ifile
IMPORTING
content = lv_bufferx2.
...
Example 1
中,沒有先驗證 p_ifile
,就對此項目中的資料執行讀/寫功能。如果 ZIP 檔案原本是放置在 Unix 機器的 "/tmp/
" 目錄中,ZIP 項目為 "../etc/hosts
",並根據必要的權限執行應用程式,將會覆寫系統 hosts
檔案。此舉轉而會允許從機器將流量送到攻擊者所要的任何位置,例如,返回攻擊者的機器。
public static void UnzipFile(ZipArchive archive, string destDirectory)
{
foreach (var entry in archive.Entries)
{
string file = entry.FullName;
if (!string.IsNullOrEmpty(file))
{
string destFileName = Path.Combine(destDirectory, file);
entry.ExtractToFile(destFileName, true);
}
}
}
Example 1
中,沒有先驗證 entry.FullName
,就對此項目中的資料執行讀/寫作業。如果 Zip 檔案原本是放置在「C:\TEMP
」目錄中,而 Zip 項目名稱包含「..\
片段」,且應用程式是在所需權限下執行,則會任意覆寫系統檔案。
func Unzip(src string, dest string) ([]string, error) {
var filenames []string
r, err := zip.OpenReader(src)
if err != nil {
return filenames, err
}
defer r.Close()
for _, f := range r.File {
// Store filename/path for returning and using later on
fpath := filepath.Join(dest, f.Name)
filenames = append(filenames, fpath)
if f.FileInfo().IsDir() {
// Make Folder
os.MkdirAll(fpath, os.ModePerm)
continue
}
// Make File
if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
return filenames, err
}
outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return filenames, err
}
rc, err := f.Open()
if err != nil {
return filenames, err
}
_, err = io.Copy(outFile, rc)
// Close the file without defer to close before next iteration of loop
outFile.Close()
rc.Close()
if err != nil {
return filenames, err
}
}
return filenames, nil
}
Example 1
中,沒有先驗證 f.Name
,就對此項目中的資料執行讀/寫功能。如果 Zip 檔案原本是放置在 Unix 機器的「/tmp/
」目錄中,Zip 項目為「../etc/hosts
」,並根據必要的權限執行應用程式,將會覆寫系統 hosts
檔案。此舉轉而會允許從機器將流量送到攻擊者所要的任何位置,例如,返回攻擊者的機器。
private static final int BUFSIZE = 512;
private static final int TOOBIG = 0x640000;
...
public final void unzip(String filename) throws IOException {
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry zipEntry = null;
int numOfEntries = 0;
long total = 0;
try {
while ((zipEntry = zis.getNextEntry()) != null) {
byte data[] = new byte[BUFSIZE];
int count = 0;
String outFileName = zipEntry.getName();
if (zipEntry.isDirectory()){
new File(outFileName).mkdir(); //create the new directory
continue;
}
FileOutputStream outFile = new FileOutputStream(outFileName);
BufferedOutputStream dest = new BufferedOutputStream(outFile, BUFSIZE);
//read data from Zip, but do not read huge entries
while (total + BUFSIZE <= TOOBIG && (count = zis.read(data, 0, BUFSIZE)) != -1) {
dest.write(data, 0, count);
total += count;
}
...
}
} finally{
zis.close();
}
}
...
Example 1
中,沒有先驗證 zipEntry.getName()
,就對此項目中的資料執行讀/寫功能。如果 Zip 檔案原本是放置在 Unix 機器的「/tmp/
」目錄中,Zip 項目為「../etc/hosts
」,並根據必要的權限執行應用程式,將會覆寫系統 hosts
檔案。此舉轉而會允許從機器將流量送到攻擊者所要的任何位置,例如,返回攻擊者的機器。
var unzipper = require('unzipper');
var fs = require('fs');
var untrusted_zip = getZipFromRequest();
fs.createReadStream(zipPath).pipe(unzipper.Extract({ path: 'out' }));
ZZArchive* archive = [ZZArchive archiveWithURL:[NSURL fileURLWithPath: zipPath] error:&error];
for (ZZArchiveEntry* entry in archive.entries) {
NSString *fullPath = [NSString stringWithFormat: @"%@/%@", destPath, [entry fileName]];
[[entry newDataWithError:nil] writeToFile:newFullPath atomically:YES];
}
Example 1
中,沒有先驗證 entry.fileName
,就對此項目中的資料執行讀/寫功能。如果 Zip 檔案原本是放置在 iOS 應用程式的「Documents/hot_patches
」目錄中,Zip 項目為「../js/page.js
」,將會覆寫 page.js
檔案。此舉進而會允許攻擊者插入可能會導致執行程式碼的惡意程式碼。
...
$zip = new ZipArchive();
$zip->open("userdefined.zip", ZipArchive::RDONLY);
$zpm = $zip->getNameIndex(0);
$zip->extractTo($zpm);
...
Example 1
中,沒有先驗證 f.Name
,就對此項目中的資料執行讀/寫功能。如果 Zip 檔案位於 Unix 機器的「/tmp/
」目錄中,Zip 項目為「../etc/hosts
」,並根據必要的權限執行應用程式,將會覆寫系統 hosts
檔案。此舉會允許從機器將流量送到攻擊者所要的任何位置,例如,返回攻擊者的機器。
import zipfile
import tarfile
def unzip(archive_name):
zf = zipfile.ZipFile(archive_name)
zf.extractall(".")
zf.close()
def untar(archive_name):
tf = tarfile.TarFile(archive_name)
tf.extractall(".")
tf.close()
範例 2:以下範例會從 Zip 檔案解壓縮檔案,然後以不安全的方式將檔案寫入磁碟。
import better.files._
...
val zipPath: File = getUntrustedZip()
val destinationPath = file"out/dest"
zipPath.unzipTo(destination = destinationPath)
import better.files._
...
val zipPath: File = getUntrustedZip()
val destinationPath = file"out/dest"
zipPath.newZipInputStream.mapEntries( (entry : ZipEntry) => {
entry.extractTo(destinationPath, new FileInputStream(entry.getName))
})
Example 2
中,沒有先驗證 entry.getName
,就對此項目中的資料執行讀/寫功能。如果 Zip 檔案原本是放置在 Unix 機器的「/tmp/
」目錄中,Zip 項目為「../etc/hosts
」,並根據必要的權限執行應用程式,將會覆寫系統 hosts
檔案。此舉轉而會允許從機器將流量送到攻擊者所要的任何位置,例如,返回攻擊者的機器。
let archive = try ZZArchive.init(url: URL(fileURLWithPath: zipPath))
for entry in archive.entries {
let fullPath = URL(fileURLWithPath: destPath + "/" + entry.fileName)
try entry.newData().write(to: fullPath)
}
Example 1
中,沒有先驗證 entry.fileName
,就對此項目中的資料執行讀/寫功能。如果 Zip 檔案原本是放置在 iOS 應用程式的「Documents/hot_patches
」目錄中,Zip 項目為「../js/page.js
」,將會覆寫 page.js
檔案。此舉進而會允許攻擊者插入可能會導致執行程式碼的惡意程式碼。latest
標籤會自動指示未使用摘要或唯一標籤為其提供版本的映像的版本層級。Docker 會自動指派 latest
標籤做為指向最新映像資訊清單檔案的機制。由於標籤是可變的,所以攻擊者可使用 latest
(或弱標籤,如imagename-lst, imagename-last, myimage
) 取代映像或階層。ubuntu
版本的基本映像。
FROM ubuntu:Latest
...
zypper
擷取指定套件的最新版本。
...
zypper install package
...
Example 2
中,如果儲存庫遭到入侵,攻擊者可能很容易便上傳符合動態標準的版本,使 zypper
下載相依項的惡意版本。enable_private_nodes
和 enable_private_endpoint
已設為 false
。
resource "google_container_cluster" "cluster-demo" {
...
private_cluster_config {
enable_private_endpoint = false
enable_private_nodes = false
}
...
}
NSFileManager
定義,而常數則應該被指派為與 NSFileManager
執行個體相關聯之 NSDictionary
中的 NSFileProtectionKey
金鑰值,以及可以透過使用 NSFileManager
函數 (包括 setAttributes:ofItemAtPath:error:
、attributesOfItemAtPath:error:
和 createFileAtPath:contents:attributes:
) 建立檔案或修改其資料保護類別。此外,相對應的資料保護常數會針對 NSData
物件定義為 NSDataWritingOptions
,以便可以做為 options
引數傳遞到 NSData
函數 writeToURL:options:error:
和 writeToFile:options:error:
。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
,而常數則應該被指派為與 NSFileManager
實例相關聯之 Dictionary
中的 NSFileProtectionKey
金鑰值,以及可以透過使用 NSFileManager
函數 (包括 setAttributes(_:ofItemAtPath:)
、attributesOfItemAtPath(_:)
和 createFileAtPath(_:contents:attributes:)
) 建立檔案或修改其資料保護類別。此外,相對應的資料保護常數會針對 NSDataWritingOptions
列舉中的 NSData
物件定義,以便可以做為 options
引數傳遞到 NSData
函數
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);
...
NSFileManager
定義,而常數則應該被指派為與 NSFileManager
執行個體相關聯之 NSDictionary
中的 NSFileProtectionKey
金鑰值,以及可以透過使用 NSFileManager
函數 (包括 setAttributes:ofItemAtPath:error:
、attributesOfItemAtPath:error:
和 createFileAtPath:contents:attributes:
) 建立檔案或修改其資料保護類別。此外,相對應的資料保護常數會針對 NSData
物件定義為 NSDataWritingOptions
,以便可以做為 options
引數傳遞到 NSData
函數 writeToURL:options:error:
和 writeToFile:options:error:
。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
金鑰值。可以透過使用 NSFileManager
函數 (包括 setAttributes(_:ofItemAtPath:)
、attributesOfItemAtPath(_:)
和 createFileAtPath(_:contents:attributes:)
) 建立檔案或修改其資料保護類別。此外,相對應的資料保護常數會針對 NSDataWritingOptions
列舉中的 NSData
物件定義,以便可以做為 options
引數傳遞到 NSData
函數,例如
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);
...
publicAccess
屬性設定為 Container
。這會允許匿名存取容器的所有 Blob 和資料。
{
"type": "Microsoft.Storage/storageAccounts/blobServices/containers",
"apiVersion": "2021-04-01",
"name": "[format('{0}/default/{1}', parameters('storageAccountName'), parameters('containerName'))]",
"properties":{
"publicAccess": "Container"
}
,
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]"
]
}
publicNetworkAccess
屬性且不建立任何 IP 限制來定義未限制網路存取的 Azure Container Registry。範例 2:以下範例範本透過指定廣泛的允許清單給
{
"name": "[variables('acrName')]",
"type": "Microsoft.ContainerRegistry/registries",
...
"properties": {
"publicNetworkAccess": "Enabled",
..
}
networkRuleSet
屬性來定義未限制網路存取的 Azure Container Registry。
{
"name": "[variables('acrName')]",
"type": "Microsoft.ContainerRegistry/registries",
...
"properties": {
"publicNetworkAccess": "Enabled",
"networkRuleSet":
{
"defaultAction": "Allow",
"ipRules":[{
"action": "Allow",
"value": "*"
}]
}
...
}