Impersonation on IIS 7.5 - fileaccess on network drive - System.UnauthorizedAccessException - vb.net

Environment: IIS 7.5, Windows 7 Pro, Visual Studio 2012, Webapp uses Framework 4.0
I tried to get a directory listing from a fileserver using path like \\server\share\directory by a webservice (asmx).
I use the following configuration in web.config:
<identity impersonate="true" />
<authentication mode="Windows" />
I check User.Identity.Name and Threading.Thread.CurrentPrincipal.Identity.Name and get the used Domain\Username for login. A "System.UnauthorizedAccessException" is thrown if i try to get a directory listing of "\\server\share\directory" .
I tried many things, even to use local system, local service or the domain administrator as identity for the application-pool.
When I change the configuration system.webServer/serverRuntime authenticatedUserOverride from UseAuthenticatedUser to UseWorkerProcessUser, i can reach the network share, but under the identity of the application-pool user and not of the user, that uses the webservice. In this configuration i cannot get Information about the login, that was used, instead i get as identity always the user for the application-pool.
Is possible to get the windows-login-user without impersonate?
Or what have to be done to get successfull access to networkfilesystem?
I think UAC is dissabled on my machine.

After trying a lot of things i found this solution (not perfect, but it works for me):
ADS/Domaincontroller:
Add a new user "IIS-User" to active directory
Add Group Domain Admins to "IIS-User"
set Domain Admins to primary Group
Edit/add attribute servicePrincipalName by the attribute-editor : http/[computername of iis]
save and close usereditor in ADS-Server-Manager
open usereditor -> new tab "delegation" -> Allowing user "IIS-User" the delegation of services
PC/Server with IIS:
open IIS-Manger
edit application-pool: set identity to new user for the application-pool, that is used for the webservice/asp-app
edit configuration with configuration editor of IIS-manger:
system.web/authentication mode=Windows
system.web/identity impersonate=True
system.webServer/security/authentication/windowsAuthentication enabled=True, useAppPoolCredebtials=True
system.webServer/serverRuntime authenticatedUserOverride=UseAuthenticatedUser
system.webServer/validation validateIntegratedModeConfiguration=false
Now the webservice can access the netshare with the rights of the new user ("IIS-User"), but the property User.Identity.Name returns the name of the login user. But now i can check, wether the login user has access to files/directory and show only for the user accessible files/directories.
Maybe there are some unnecessary configuration settings, but after searching many hours for a solution i'm glad to found a working solution.
Private Shared Function getSecId4User(user As IPrincipal) As SecurityIdentifier
Return getSecId4Username(user.Identity.Name)
End Function
Private Shared Function getSecId4Username(username As String) As SecurityIdentifier
Dim account As New NTAccount(username)
Return account.Translate(GetType(SecurityIdentifier))
End Function
Private Shared Function isVisible4User(di As DirectoryInfo, secId As SecurityIdentifier) As Boolean
Dim dirSec As DirectorySecurity = di.GetAccessControl
Dim authRules As AuthorizationRuleCollection = dirSec.GetAccessRules(True, True, GetType(SecurityIdentifier))
For Each ar As FileSystemAccessRule In authRules
If secId.Equals(CType(ar.IdentityReference, SecurityIdentifier)) Then
Dim fileSystemRights As FileSystemRights = ar.FileSystemRights
Select Case fileSystemRights
Case System.Security.AccessControl.FileSystemRights.FullControl
Return True
Case System.Security.AccessControl.FileSystemRights.AppendData
Return True
Case System.Security.AccessControl.FileSystemRights.ChangePermissions
Return True
Case System.Security.AccessControl.FileSystemRights.CreateDirectories
Return True
Case System.Security.AccessControl.FileSystemRights.CreateFiles
Return True
Case System.Security.AccessControl.FileSystemRights.Delete
Return True
Case System.Security.AccessControl.FileSystemRights.DeleteSubdirectoriesAndFiles
Return True
Case System.Security.AccessControl.FileSystemRights.ExecuteFile
Return True
Case System.Security.AccessControl.FileSystemRights.FullControl
Return True
Case System.Security.AccessControl.FileSystemRights.ListDirectory
Return True
Case System.Security.AccessControl.FileSystemRights.Modify
Return True
Case System.Security.AccessControl.FileSystemRights.Read
Return True
Case System.Security.AccessControl.FileSystemRights.ReadAndExecute
Return True
Case System.Security.AccessControl.FileSystemRights.ReadAttributes
Return True
Case System.Security.AccessControl.FileSystemRights.ReadData
Return True
Case System.Security.AccessControl.FileSystemRights.ReadExtendedAttributes
Return True
Case System.Security.AccessControl.FileSystemRights.ReadPermissions
Return True
Case System.Security.AccessControl.FileSystemRights.Synchronize
Return True
Case System.Security.AccessControl.FileSystemRights.TakeOwnership
Return True
Case System.Security.AccessControl.FileSystemRights.Traverse
Return True
Case System.Security.AccessControl.FileSystemRights.Write
Return True
Case System.Security.AccessControl.FileSystemRights.WriteAttributes
Return True
Case System.Security.AccessControl.FileSystemRights.WriteData
Return True
Case System.Security.AccessControl.FileSystemRights.WriteExtendedAttributes
Return True
Case Else
End Select
End If
Next
Return False
End Function
Private Shared Function isVisible4User(fi As FileInfo, secId As SecurityIdentifier) As Boolean
Dim filesec As FileSecurity = fi.GetAccessControl
Dim authRules As AuthorizationRuleCollection = filesec.GetAccessRules(True, True, GetType(SecurityIdentifier))
For Each ar As FileSystemAccessRule In authRules
If secId.CompareTo(CType(ar.IdentityReference, SecurityIdentifier)) = 0 Then
Dim fileSystemRights As FileSystemRights = ar.FileSystemRights
Select Case fileSystemRights
Case System.Security.AccessControl.FileSystemRights.FullControl
Return True
Case System.Security.AccessControl.FileSystemRights.AppendData
Return True
Case System.Security.AccessControl.FileSystemRights.ChangePermissions
Return True
Case System.Security.AccessControl.FileSystemRights.CreateDirectories
Return True
Case System.Security.AccessControl.FileSystemRights.CreateFiles
Return True
Case System.Security.AccessControl.FileSystemRights.Delete
Return True
Case System.Security.AccessControl.FileSystemRights.DeleteSubdirectoriesAndFiles
Return True
Case System.Security.AccessControl.FileSystemRights.ExecuteFile
Return True
Case System.Security.AccessControl.FileSystemRights.FullControl
Return True
Case System.Security.AccessControl.FileSystemRights.ListDirectory
Return True
Case System.Security.AccessControl.FileSystemRights.Modify
Return True
Case System.Security.AccessControl.FileSystemRights.Read
Return True
Case System.Security.AccessControl.FileSystemRights.ReadAndExecute
Return True
Case System.Security.AccessControl.FileSystemRights.ReadAttributes
Return True
Case System.Security.AccessControl.FileSystemRights.ReadData
Return True
Case System.Security.AccessControl.FileSystemRights.ReadExtendedAttributes
Return True
Case System.Security.AccessControl.FileSystemRights.ReadPermissions
Return True
Case System.Security.AccessControl.FileSystemRights.Synchronize
Return True
Case System.Security.AccessControl.FileSystemRights.TakeOwnership
Return True
Case System.Security.AccessControl.FileSystemRights.Traverse
Return True
Case System.Security.AccessControl.FileSystemRights.Write
Return True
Case System.Security.AccessControl.FileSystemRights.WriteAttributes
Return True
Case System.Security.AccessControl.FileSystemRights.WriteData
Return True
Case System.Security.AccessControl.FileSystemRights.WriteExtendedAttributes
Return True
Case Else
End Select
End If
Next
Return False
End Function
Checking of accessibility

Related

Roblox - Call external GraphQL API

I would like to call an external graphql API (without authentication for the moment).
Here is my code :
local open_api = "https://graphqlzero.almansi.me/api"
local payload = '{"query": "query { post(id: 1) { id title body }}"}'
local headers = {
}
local function craftCall()
local response
local data
pcall(function ()
response = HttpService:PostAsync(open_api, payload, Enum.HttpContentType.ApplicationJson, false, headers)
data = HttpService:JSONDecode(response)
end)
if not data then return false end
print(data)
return false
end
if craftCall() then
print("Success")
else
print("Something went wrong")
end
I get always something went wrong. I need some help on what is going wrong... Specially I don't know if am I correctly formatting the Payload.
After your http call, you never return a success result. You've only outlined failure cases :
if not data then return false end
print(data)
return false
So your conditional, if craftCall() then always evaluates to false.
Why not make it return true or data after the print(data)? Then you'll know that it made it to the end of the call successfully.
local function craftCall()
local success, result = pcall(function()
local response = HttpService:PostAsync(open_api, payload, Enum.HttpContentType.ApplicationJson, false, headers)
return HttpService:JSONDecode(response)
end)
if not success then
warn("PostAsync failed with error : ", result)
return false
end
-- return the parsed data
return result
end

How do I Make a double jump Script that makes the power of the second Jump the Value of the players leader stat value

I made this code thinking it would allow the player to jump Twice and the second Jump be the power of its leader stat but Instead it doesn't even allow the player to Jump a second time.
local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local character
local humanoid
local canDoubleJump = false
local hasDoubleJumped = false
local oldPower
local time_delay = 0.2
local jump_multiplier = player.leaderstats.JumpBoost.Value
function onJumpRequest()
if not character or not humanoid or not
character:IsDescendantOf(workspace) or humanoid:GetState() ==
Enum.HumanoidStateType.Dead then
return
end
if canDoubleJump and not hasDoubleJumped then
hasDoubleJumped = true
humanoid.JumpPower = oldPower * jump_multiplier
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
end
local function characterAdded(new)
character = new
humanoid = new:WaitForChild("Humanoid")
hasDoubleJumped = false
canDoubleJump = false
oldPower = humanoid.JumpPower
humanoid.StateChanged:connect(function(old, new)
if new == Enum.HumanoidStateType.Landed then
canDoubleJump = false
hasDoubleJumped = false
humanoid.JumpPower = oldPower
elseif new == Enum.HumanoidStateType.Freefall then
wait(time_delay)
canDoubleJump = true
end
end)
end
if player.Character then
characterAdded(player.Character)
end
player.CharacterAdded:connect(characterAdded)
UIS.JumpRequest:connect(onJumpRequest)
I expected the player to Jump Twice with the second Jump having the power of the leader stat(I only put that and this because it says it wants more detail)
LocalScripts do not execute in game.Workspace: they only run on clients, hence the term 'local'; Scripts, on the other hand, are server-side.
You could use a Script to place your double-jump script--a LocalScript--into incoming players' character models.
-- Server-side Script
local players = game:GetService("Players")
local jumpScript = script:WaitForChild("JumpScript") -- Assume the double-jump script is a LocalScript called 'JumpScript'.
players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(char)
-- Check to make sure the character model does not already contain the double-jump script, just in case.
local clone = char:FindFirstChild("JumpScript")
if (not clone) then
clone = jumpScript:Clone()
clone.Parent = char
end
end)
end)
As a note, it is good practice to put server-side scripts like this into ServerScriptStorage instead of workspace or Lighting. (You can read about the safety of ServerScriptStoragehere.)

Command permissions Discord.net

user type : "test",
if user have role "vip" then message show up "you have permission"
else "you dont have permission"
my code :
Public Async Function onMsg(message As SocketMessage) As Task
If message.Source = MessageSource.Bot Then
Else
If message.Content.Contains("test") Then
Dim userName As SocketGuildUser
Dim user = TryCast(message.Author, SocketGuildUser)
Dim role = (TryCast(user, IGuildUser)).Guild.Roles.FirstOrDefault(Function(x) x.Name = "vip")
If Not userName.Roles.Contains(role) Then
Await message.Channel.SendMessageAsync("you have permission")
Else
Await message.Channel.SendMessageAsync("you dont have permission")
End If
End If
End Function
First off, for creating commands in general, you should consider using the Command Service that's provided in Discord.Net, instead of If/Else checks in your message received event handler.
There's also an error in your code. You declare a userName variable, but never actually assign anything to it. Yet you attempt to do userName.Roles
Solution:
If message.Source = MessageSource.Bot Then
Return
ElseIf message.Content.Contains("test") Then
Dim user = TryCast(message.Author, SocketGuildUser)
'If casting the user to a SocketGuildUser was not successful, then exit
If user Is Nothing Then Return 'This can occur if a user message the bot via Direct Messages
'Using "Any" returns true if a match is found, false otherwise
If user.Roles.Any(Function(role) role.Name.Equals("VIP", StringComparison.OrdinalIgnoreCase)) Then
Await message.Channel.SendMessageAsync("you have permission")
Else
Await message.Channel.SendMessageAsync("you dont have permission")
End If
End If
a simply trick, if your vip's member can count as not many member's you can select them id's to let them permission.
If message.Content.Contains("test") Then
If message.Author.Mention = "<#!ID>" Then 'vip's permission |OrElse statement
Await message.Channel.SendMessageAsync("you have permission")
Else
Await message.Channel.SendMessageAsync("you dont have permission")
End If

Testing for false with the Twitter Gem in rails 3

I'm using the Twitter gem, and I want to take a list of users from my Friend model and test to see if they're being following a Twitter user, then ... unfollow if the Twitter API returns false. Trouble is, it seems the code I'm using below never evaluates as false, even when the API returns false so it's always reverting to the else section.
I've tried variations like if ret == 'false' and it's not worked.
ret = #t.friendship?(#id_str, f.screen_name)
if ret == false
#t.unfollow(f.screen_name)
puts "#{f.screen_name} has been unfollowed."
self.update_unfollowed_column(f.id, false)
else
self.update_following_column(f.id)
end
In the console, though, if I do:
r = t.friendship?('user1', 'user2')
=> false
And then, I can do:
r == false
=> true
So, I'm not sure exactly what I'm doing wrong with the code in my Friend model.
Before the if statement, try debugging what the result is from the friendship? method:
logger.info ret.class.name # => FalseClass if it's actually false,
# => String if it's 'false'
logger.info ret.inspect # => "false" if it's false.
logger.info((ret == false).inspect) # => Should be "true"

Check if a file exists with Lua

How can I check if a file exists using Lua?
Try
function file_exists(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
but note that this code only tests whether the file can be opened for reading.
Using plain Lua, the best you can do is see if a file can be opened for read, as per LHF. This is almost always good enough. But if you want more, load the Lua POSIX library and check if posix.stat(path) returns non-nil.
Lua 5.1:
function file_exists(name)
local f = io.open(name, "r")
return f ~= nil and io.close(f)
end
I will quote myself from here
I use these (but I actually check for the error):
require("lfs")
-- no function checks for errors.
-- you should check for them
function isFile(name)
if type(name)~="string" then return false end
if not isDir(name) then
return os.rename(name,name) and true or false
-- note that the short evaluation is to
-- return false instead of a possible nil
end
return false
end
function isFileOrDir(name)
if type(name)~="string" then return false end
return os.rename(name, name) and true or false
end
function isDir(name)
if type(name)~="string" then return false end
local cd = lfs.currentdir()
local is = lfs.chdir(name) and true or false
lfs.chdir(cd)
return is
end
os.rename(name1, name2) will rename name1 to name2. Use the same name and nothing should change (except there is a badass error). If everything worked out good it returns true, else it returns nil and the errormessage. If you dont want to use lfs you cant differentiate between files and directories without trying to open the file (which is a bit slow but ok).
So without LuaFileSystem
-- no require("lfs")
function exists(name)
if type(name)~="string" then return false end
return os.rename(name,name) and true or false
end
function isFile(name)
if type(name)~="string" then return false end
if not exists(name) then return false end
local f = io.open(name)
if f then
f:close()
return true
end
return false
end
function isDir(name)
return (exists(name) and not isFile(name))
end
It looks shorter, but takes longer...
Also open a file is a it risky
Have fun coding!
If you're using Premake and LUA version 5.3.4:
if os.isfile(path) then
...
end
For sake of completeness: You may also just try your luck with path.exists(filename). I'm not sure which Lua distributions actually have this path namespace (update: Penlight), but at least it is included in Torch:
$ th
______ __ | Torch7
/_ __/__ ________/ / | Scientific computing for Lua.
/ / / _ \/ __/ __/ _ \ | Type ? for help
/_/ \___/_/ \__/_//_/ | https://github.com/torch
| http://torch.ch
th> path.exists(".gitignore")
.gitignore
th> path.exists("non-existing")
false
debug.getinfo(path.exists) tells me that its source is in torch/install/share/lua/5.1/pl/path.lua and it is implemented as follows:
--- does a path exist?.
-- #string P A file path
-- #return the file path if it exists, nil otherwise
function path.exists(P)
assert_string(1,P)
return attrib(P,'mode') ~= nil and P
end
If you are willing to use lfs, you can use lfs.attributes. It will return nil in case of error:
require "lfs"
if lfs.attributes("non-existing-file") then
print("File exists")
else
print("Could not get attributes")
end
Although it can return nil for other errors other than a non-existing file, if it doesn't return nil, the file certainly exists.
An answer which is windows only checks for files and folders, and also requires no additional packages. It returns true or false.
io.popen("if exist "..PathToFileOrFolder.." (echo 1)"):read'*l'=='1'
io.popen(...):read'*l' - executes a command in the command prompt and reads the result from the CMD stdout
if exist - CMD command to check if an object exists
(echo 1) - prints 1 to stdout of the command prompt
An answer which is windows only checks for files and folders, and also requires no additional packages. It returns true or false.
You can also use the 'paths' package. Here's the link to the package
Then in Lua do:
require 'paths'
if paths.filep('your_desired_file_path') then
print 'it exists'
else
print 'it does not exist'
end
Not necessarily the most ideal as I do not know your specific purpose for this or if you have a desired implementation in mind, but you can simply open the file to check for its existence.
local function file_exists(filename)
local file = io.open(filename, "r")
if (file) then
-- Obviously close the file if it did successfully open.
file:close()
return true
end
return false
end
io.open returns nil if it fails to open the file. As a side note, this is why it is often used with assert to produce a helpful error message if it is unable to open the given file. For instance:
local file = assert(io.open("hello.txt"))
If the file hello.txt does not exist, you should get an error similar to stdin:1: hello.txt: No such file or directory.
For library solution, you can use either paths or path.
From the official document of paths:
paths.filep(path)
Return a boolean indicating whether path refers to an existing file.
paths.dirp(path)
Return a boolean indicating whether path refers to an existing directory.
Although the names are a little bit strange, you can certainly use paths.filep() to check whether a path exists and it is a file. Use paths.dirp() to check whether it exists and it is a directory. Very convenient.
If you prefer path rather than paths, you can use path.exists() with assert() to check the existence of a path, getting its value at the same time. Useful when you are building up path from pieces.
prefix = 'some dir'
filename = assert(path.exist(path.join(prefix, 'data.csv')), 'data.csv does not exist!')
If you just want to check the boolean result, use path.isdir() and path.isfile(). Their purposes are well-understood from their names.
If you use LOVE, you can use the function love.filesystem.exists('NameOfFile'), replacing NameOfFile with the file name.
This returns a Boolean value.
How about doing something like this?
function exist(file)
local isExist = io.popen(
'[[ -e '.. tostring(file) ..' ]] && { echo "true"; }')
local isIt = isExist:read("*a")
isExist:close()
isIt = string.gsub(isIt, '^%s*(.-)%s*$', '%1')
if isIt == "true" then
return true
end
return false
end
if exist("myfile") then
print("hi, file exists")
else
print("bye, file does not exist")
end
if you are like me exclusively on Linux, BSD any UNIX type you can use this:
function isDir(name)
if type(name)~="string" then return false end
return os.execute('if [ -d "'..name..'" ]; then exit 0; else exit 1; fi')
end
function isFile(name)
if type(name)~="string" then return false end
return os.execute('if [ -f "'..name..'" ]; then exit 0; else exit 1; fi')
end
Actually this looks even better:
function isDir(name)
if type(name)~="string" then return false end
return os.execute('test -d '..name)
end
function isFile(name)
if type(name)~="string" then return false end
return os.execute('test -f '..name)
end
function exists(name)
if type(name)~="string" then return false end
return os.execute('test -e '..name)
end
IsFile = function(path)
print(io.open(path or '','r')~=nil and 'File exists' or 'No file exists on this path: '..(path=='' and 'empty path entered!' or (path or 'arg "path" wasn\'t define to function call!')))
end
IsFile()
IsFile('')
IsFIle('C:/Users/testuser/testfile.txt')
Looks good for testing your way. :)