怎樣提高Windows Azure Cloud Service中的WebRole的文件訪問權限

關鍵字:WebRole

1. 背景

Web應用程序需要讀取和寫入該項目下的文件的權限。

在默認情況下,W3wp.exe 和WaIISHost.exe的運行賬號是Network Service,而Network Service 的對文件的訪問權只有讀取權限。

image

image

所以要讀取和更改web站點下的文件,需要提升IIS對該文件的訪問權限,也就是提高Network Service賬號的訪問該文件的權限。

2. 解決辦法

首先我們會想到在ServiceDefinition.cscfg配置文件加上提升權限的配置。如:

<WebRole name="WebRole1" vmsize="Small">
        <Runtime executionContext="elevated"/>

這裏提升的是部署WebRole的權限。
但是要知道,不管怎麼提升,w3wp這個進程在webrole裏面始終以Network Service 來運行,所以這種配置是無效的。
http://technet.microsoft.com/en-us/library/cc771170(v=ws.10).aspx

從上述文檔中知道,

如果運行在一個具有很高權限的賬號下Application pool會有安全風險的

文章Startup Lifecycle of a Windows Azure Role告訴我們不能在部署Startup task中來更改Network Service的權限,因爲這個時候IIS Application Pool 還沒有生成。

我們可以更改文件的訪問權限,這個是跟IIS配置無關的。也就是上面貼圖中network service的權限列表。

1)編寫Startup.cmd

set filePath=%RoleRoot%\sitesroot\0\App_Data\mycompactdb.sdf

ModifyFileSecurity.exe "%filePath%" "NETWORK SERVICE"

EXIT /B 0

2)編寫ModifyFileSecurity

ModifyFileSecurity.exe

class Program

{

static void Main(string[] args)

{

if (args.Length == 2)

{

string fileName = args[0];

string account = args[1];

AddFileSecurity(fileName, account, FileSystemRights.Modify, AccessControlType.Allow);

}

}

public static void AddFileSecurity(string fileName, string account,

FileSystemRights rights, AccessControlType controlType)

{

// Get a FileSecurity object that represents the

// current security settings.

FileSecurity fSecurity = File.GetAccessControl(fileName);

// Add the FileSystemAccessRule to the security settings.

fSecurity.AddAccessRule(new FileSystemAccessRule(account,

rights, controlType));

// Set the new access settings.

File.SetAccessControl(fileName, fSecurity);

}

}

當然我們也可以編寫Powershell 命令SET-ACL來辯解訪問文件的訪問權限

參考:

http://technet.microsoft.com/en-us/library/hh849810.aspx
     http://technet.microsoft.com/en-us/library/ff730951.aspx
     http://blogs.msdn.com/b/johan/archive/2008/10/01/powershell-editing-permissions-on-a-file-or-folder.aspx
     How to update role code in startup task.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章