· “Design patterns are recurring solutions to design problems you see over"(et. al., 1998).
· “Design patterns constitute a set of rules describing how to accomplish
certain tasks in the realm of software development.” (Pree, 1994)
· “Design patterns focus more on reuse of recurring architectural design
themes, while frameworks focus on detailed design… and
implementation.” (Coplien & Schmidt, 1995).
· “A pattern addresses a recurring design problem that arises in specific
design situations and presents a solution to it” (Buschmann, et. al. 1996)
· “Patterns identify and specify abstractions that are above the level of
single classes and instances, or of components.” (Gamma, et al., 1993)
Thursday, April 26, 2007
Coding levels
I think there are five coding levels:
Level 1: Workable
Level 2: Readable(or Manageable)
Level 3: Literal(Well document)
Level 4: Elegant
Level 5: Safe
Level 1: Workable
Level 2: Readable(or Manageable)
Level 3: Literal(Well document)
Level 4: Elegant
Level 5: Safe
网上热传:杨振宁妻子翁帆写下双语情书
翁帆所写“情书”
Cold here, icy cold there. You belong to neither, leaves have with ered.
Your face is pale and blue, a tearful smile. Some-thing in your eyes,whispers words of last good-bye. My heart sinks down,tears surge out.
Hot summer.Cheerful Cocktail. You took my hand. We fled into another world of band. You sat by my side, long hair tied behind,cool and killing.Smile floating on the lemonade,soft and smooth.How I was? amazed.Your face looked like the cover of the magazine.My head spin. You led my hand,danced along the crazy theme.
Light vied with wine, elegance mixed with fragrance,laughing covered by greetings, the crowed was busy at handshaking.You stoodthere, eyes on me. I trembled at the sparkles, centerer than the light. A masterpiece from God, I felt dizzy. We were not near, yet we were togeth-er.
Days ended. You said, you would wait for me at the Alps side.We would ski against snowflakes dancing in the sky. I gave no answer but a good-bye to ac-company your flight. Gone was the plane,I suddenly tasted my pain. I knew I had been silly and stupid,you were in my heart, I shouldn’t have hidden in the dark. I tried to forget your disappointment. I made be-lieve sometime someday,I would tell you, I feel all the same.
My thought struggled at confessing, somehow hesitation ended in flinching. I continued my role of a fool, clinched to my maiden pride, yet secretly in-dulged in your promise of the white land --snow measuring down to us, in your arms I am lifted up. The chiming of Christmas bell!
The bell died in the patter of rain, from hell came the laughing of Satan at my brain. Tearful smile, swal-lowed by the darkness.How could I trace your hair to wipe your tears? My hands reached out,catching nothing but a raindrop, on a leaf that had withered.
Snowflakes have melted into water, we are no more together.
网友译文(版本之一)
此处寒兮,彼处亦寒。
枯叶凋零兮,君当何人属欤?
君面惨淡忧郁兮,相看带笑泪眼。
君热泪盈盈复喃喃喁唧兮,别亦难。
沉落兮,泪涌似涛自难抑。
当忆酷夏兮,鸡尾酒会欢娱。
君执妾手兮,沉醉于二人世界里。
君坐妾之侧兮,髻发高束;英姿勃发兮,酷毙。
笑逐颜开兮,温润如玉。
讶君之面兮,再世吕布周郎。
心荡漾兮,手为君执;和曲起舞兮,癫狂。
灯盏相辉兮,芳雅相应;祝辞笑浪起伏兮,芸芸相送急。
君且立一旁兮,美目探妾。
妾莹灯下伫立兮,心动不已。
感帝之杰作兮,使妾沉迷。虽与君相隔远兮,心心相近。
旧日已逝兮,如梦。
会当临于阿尔卑斯山侧兮,滑雪于雪花飞舞之穹下。
欲说还休兮,惟祈安康。
航机渐逝兮,妾心将苦。
深知妾之愚钝兮,然君已窃妾心;妾当不可漠然兮,黯然彷徨。
妾亦尝忘君兮,恐失之交臂。
信有时兮,告君心迹。
挣于忏悔兮,退缩犹豫。
愚于处子之婚盟兮,窃纵意于君之诺。白雪皑皑兮,君挽妾身;妾意甚欢兮,聆圣诞钟鸣。
然钟声忽止于急雨兮,但闻撒旦之欢声笑语。
含泪倩笑兮,吞泯于暗黑。
欲将君之发?君之泪兮,可欤?伸手所触兮,惟一叶飘零一滴飘洒。观积雪融兮,叹与君各在天涯。
Cold here, icy cold there. You belong to neither, leaves have with ered.
Your face is pale and blue, a tearful smile. Some-thing in your eyes,whispers words of last good-bye. My heart sinks down,tears surge out.
Hot summer.Cheerful Cocktail. You took my hand. We fled into another world of band. You sat by my side, long hair tied behind,cool and killing.Smile floating on the lemonade,soft and smooth.How I was? amazed.Your face looked like the cover of the magazine.My head spin. You led my hand,danced along the crazy theme.
Light vied with wine, elegance mixed with fragrance,laughing covered by greetings, the crowed was busy at handshaking.You stoodthere, eyes on me. I trembled at the sparkles, centerer than the light. A masterpiece from God, I felt dizzy. We were not near, yet we were togeth-er.
Days ended. You said, you would wait for me at the Alps side.We would ski against snowflakes dancing in the sky. I gave no answer but a good-bye to ac-company your flight. Gone was the plane,I suddenly tasted my pain. I knew I had been silly and stupid,you were in my heart, I shouldn’t have hidden in the dark. I tried to forget your disappointment. I made be-lieve sometime someday,I would tell you, I feel all the same.
My thought struggled at confessing, somehow hesitation ended in flinching. I continued my role of a fool, clinched to my maiden pride, yet secretly in-dulged in your promise of the white land --snow measuring down to us, in your arms I am lifted up. The chiming of Christmas bell!
The bell died in the patter of rain, from hell came the laughing of Satan at my brain. Tearful smile, swal-lowed by the darkness.How could I trace your hair to wipe your tears? My hands reached out,catching nothing but a raindrop, on a leaf that had withered.
Snowflakes have melted into water, we are no more together.
网友译文(版本之一)
此处寒兮,彼处亦寒。
枯叶凋零兮,君当何人属欤?
君面惨淡忧郁兮,相看带笑泪眼。
君热泪盈盈复喃喃喁唧兮,别亦难。
沉落兮,泪涌似涛自难抑。
当忆酷夏兮,鸡尾酒会欢娱。
君执妾手兮,沉醉于二人世界里。
君坐妾之侧兮,髻发高束;英姿勃发兮,酷毙。
笑逐颜开兮,温润如玉。
讶君之面兮,再世吕布周郎。
心荡漾兮,手为君执;和曲起舞兮,癫狂。
灯盏相辉兮,芳雅相应;祝辞笑浪起伏兮,芸芸相送急。
君且立一旁兮,美目探妾。
妾莹灯下伫立兮,心动不已。
感帝之杰作兮,使妾沉迷。虽与君相隔远兮,心心相近。
旧日已逝兮,如梦。
会当临于阿尔卑斯山侧兮,滑雪于雪花飞舞之穹下。
欲说还休兮,惟祈安康。
航机渐逝兮,妾心将苦。
深知妾之愚钝兮,然君已窃妾心;妾当不可漠然兮,黯然彷徨。
妾亦尝忘君兮,恐失之交臂。
信有时兮,告君心迹。
挣于忏悔兮,退缩犹豫。
愚于处子之婚盟兮,窃纵意于君之诺。白雪皑皑兮,君挽妾身;妾意甚欢兮,聆圣诞钟鸣。
然钟声忽止于急雨兮,但闻撒旦之欢声笑语。
含泪倩笑兮,吞泯于暗黑。
欲将君之发?君之泪兮,可欤?伸手所触兮,惟一叶飘零一滴飘洒。观积雪融兮,叹与君各在天涯。
Wednesday, April 25, 2007
Potentially habitable planet found
WASHINGTON - For the first time astronomers have discovered a planet outside our solar system that is potentially habitable, with Earth-like temperatures, a find researchers described Tuesday as a big step in the search for "life in the universe."
The planet is just the right size, might have water in liquid form, and in galactic terms is relatively nearby at 120 trillion miles away. But the star it closely orbits, known as a "red dwarf," is much smaller, dimmer and cooler than our sun.
There's still a lot that is unknown about the new planet, which could be deemed inhospitable to life once more is known about it. And it's worth noting that scientists' requirements for habitability count Mars in that category: a size relatively similar to Earth's with temperatures that would permit liquid water. However, this is the first outside our solar system that meets those standards.
"It's a significant step on the way to finding possible life in the universe," said University of Geneva astronomer Michel Mayor, one of 11 European scientists on the team that found the planet. "It's a nice discovery. We still have a lot of questions."
The results of the discovery have not been published but have been submitted to the journal Astronomy and Astrophysics.
Alan Boss, who works at the Carnegie Institution of Washington where a U.S. team of astronomers competed in the hunt for an Earth-like planet, called it "a major milestone in this business."
The planet was discovered by the European Southern Observatory's telescope in La Silla, Chile, which has a special instrument that splits light to find wobbles in different wave lengths. Those wobbles can reveal the existence of other worlds.
What they revealed is a planet circling the red dwarf star, Gliese 581. Red dwarfs are low-energy, tiny stars that give off dim red light and last longer than stars like our sun. Until a few years ago, astronomers didn't consider these stars as possible hosts of planets that might sustain life.
The discovery of the new planet, named 581 c, is sure to fuel studies of planets circling similar dim stars. About 80 percent of the stars near Earth are red dwarfs.
The new planet is about five times heavier than Earth. Its discoverers aren't certain if it is rocky like Earth or if its a frozen ice ball with liquid water on the surface. If it is rocky like Earth, which is what the prevailing theory proposes, it has a diameter about 1 1/2 times bigger than our planet. If it is an iceball, as Mayor suggests, it would be even bigger.
Based on theory, 581 c should have an atmosphere, but what's in that atmosphere is still a mystery and if it's too thick that could make the planet's surface temperature too hot, Mayor said.
However, the research team believes the average temperature to be somewhere between 32 and 104 degrees and that set off celebrations among astronomers.
Until now, all 220 planets astronomers have found outside our solar system have had the "Goldilocks problem." They've been too hot, too cold or just plain too big and gaseous, like uninhabitable Jupiter.
The new planet seems just right ¡ª or at least that's what scientists think.
"This could be very important," said NASA astrobiology expert Chris McKay, who was not part of the discovery team. "It doesn't mean there is life, but it means it's an Earth-like planet in terms of potential habitability."
Eventually astronomers will rack up discoveries of dozens, maybe even hundreds of planets considered habitable, the astronomers said. But this one ¡ª simply called "c" by its discoverers when they talk among themselves ¡ª will go down in cosmic history as No. 1.
Besides having the right temperature, the new planet is probably full of liquid water, hypothesizes Stephane Udry, the discovery team's lead author and another Geneva astronomer. But that is based on theory about how planets form, not on any evidence, he said.
"Liquid water is critical to life as we know it," co-author Xavier Delfosse of Grenoble University in France, said in a statement. "Because of its temperature and relative proximity, this planet will most probably be a very important target of the future space missions dedicated to the search for extraterrestrial life. On the treasure map of the Universe, one would be tempted to mark this planet with an X."
Other astronomers cautioned it's too early to tell whether there is water.
"You need more work to say it's got water or it doesn't have water," said retired NASA astronomer Steve Maran, press officer for the American Astronomical Society. "You wouldn't send a crew there assuming that when you get there, they'll have enough water to get back."
The new planet's star system is a mere 20.5 light years away, making Gliese 581 one of the 100 closest stars to Earth. It's so dim, you can't see it without a telescope, but it's somewhere in the constellation Libra, which is low in the southeastern sky during the midevening in the Northern Hemisphere.
Before you book your extrastellar flight to 581 c, a few caveats about how alien that world probably is: Anyone sitting on the planet would get heavier quickly, and birthdays would add up fast since it orbits its star every 13 days.
Gravity is 1.6 times as strong as Earth's so a 150-pound person would feel like 240 pounds.
But oh, the view. The planet is 14 times closer to the star it orbits. Udry figures the red dwarf star would hang in the sky at a size 20 times larger than our moon. And it's likely, but still not known, that the planet doesn't rotate, so one side would always be sunlit and the other dark.
Distance is another problem. "We don't know how to get to those places in a human lifetime," Maran said.
Two teams of astronomers, one in Europe and one in the United States, have been racing to be the first to find a planet like 581 c outside the solar system.
The European team looked at 100 different stars using a tool called HARPS (High Accuracy Radial Velocity for Planetary Searcher) to find this one planet, said Xavier Bonfils of the Lisbon Observatory, one of the co-discoverers.
Much of the effort to find Earth-like planets has focused on stars like our sun with the challenge being to find a planet the right distance from the star it orbits. About 90 percent of the time, the European telescope focused its search more on sun-like stars, Udry said.
A few weeks before the European discovery earlier this month, a scientific paper in the journal Astrobiology theorized a few days that red dwarf stars were good candidates.
"Now we have the possibility to find many more," Bonfils said.
The planet is just the right size, might have water in liquid form, and in galactic terms is relatively nearby at 120 trillion miles away. But the star it closely orbits, known as a "red dwarf," is much smaller, dimmer and cooler than our sun.
There's still a lot that is unknown about the new planet, which could be deemed inhospitable to life once more is known about it. And it's worth noting that scientists' requirements for habitability count Mars in that category: a size relatively similar to Earth's with temperatures that would permit liquid water. However, this is the first outside our solar system that meets those standards.
"It's a significant step on the way to finding possible life in the universe," said University of Geneva astronomer Michel Mayor, one of 11 European scientists on the team that found the planet. "It's a nice discovery. We still have a lot of questions."
The results of the discovery have not been published but have been submitted to the journal Astronomy and Astrophysics.
Alan Boss, who works at the Carnegie Institution of Washington where a U.S. team of astronomers competed in the hunt for an Earth-like planet, called it "a major milestone in this business."
The planet was discovered by the European Southern Observatory's telescope in La Silla, Chile, which has a special instrument that splits light to find wobbles in different wave lengths. Those wobbles can reveal the existence of other worlds.
What they revealed is a planet circling the red dwarf star, Gliese 581. Red dwarfs are low-energy, tiny stars that give off dim red light and last longer than stars like our sun. Until a few years ago, astronomers didn't consider these stars as possible hosts of planets that might sustain life.
The discovery of the new planet, named 581 c, is sure to fuel studies of planets circling similar dim stars. About 80 percent of the stars near Earth are red dwarfs.
The new planet is about five times heavier than Earth. Its discoverers aren't certain if it is rocky like Earth or if its a frozen ice ball with liquid water on the surface. If it is rocky like Earth, which is what the prevailing theory proposes, it has a diameter about 1 1/2 times bigger than our planet. If it is an iceball, as Mayor suggests, it would be even bigger.
Based on theory, 581 c should have an atmosphere, but what's in that atmosphere is still a mystery and if it's too thick that could make the planet's surface temperature too hot, Mayor said.
However, the research team believes the average temperature to be somewhere between 32 and 104 degrees and that set off celebrations among astronomers.
Until now, all 220 planets astronomers have found outside our solar system have had the "Goldilocks problem." They've been too hot, too cold or just plain too big and gaseous, like uninhabitable Jupiter.
The new planet seems just right ¡ª or at least that's what scientists think.
"This could be very important," said NASA astrobiology expert Chris McKay, who was not part of the discovery team. "It doesn't mean there is life, but it means it's an Earth-like planet in terms of potential habitability."
Eventually astronomers will rack up discoveries of dozens, maybe even hundreds of planets considered habitable, the astronomers said. But this one ¡ª simply called "c" by its discoverers when they talk among themselves ¡ª will go down in cosmic history as No. 1.
Besides having the right temperature, the new planet is probably full of liquid water, hypothesizes Stephane Udry, the discovery team's lead author and another Geneva astronomer. But that is based on theory about how planets form, not on any evidence, he said.
"Liquid water is critical to life as we know it," co-author Xavier Delfosse of Grenoble University in France, said in a statement. "Because of its temperature and relative proximity, this planet will most probably be a very important target of the future space missions dedicated to the search for extraterrestrial life. On the treasure map of the Universe, one would be tempted to mark this planet with an X."
Other astronomers cautioned it's too early to tell whether there is water.
"You need more work to say it's got water or it doesn't have water," said retired NASA astronomer Steve Maran, press officer for the American Astronomical Society. "You wouldn't send a crew there assuming that when you get there, they'll have enough water to get back."
The new planet's star system is a mere 20.5 light years away, making Gliese 581 one of the 100 closest stars to Earth. It's so dim, you can't see it without a telescope, but it's somewhere in the constellation Libra, which is low in the southeastern sky during the midevening in the Northern Hemisphere.
Before you book your extrastellar flight to 581 c, a few caveats about how alien that world probably is: Anyone sitting on the planet would get heavier quickly, and birthdays would add up fast since it orbits its star every 13 days.
Gravity is 1.6 times as strong as Earth's so a 150-pound person would feel like 240 pounds.
But oh, the view. The planet is 14 times closer to the star it orbits. Udry figures the red dwarf star would hang in the sky at a size 20 times larger than our moon. And it's likely, but still not known, that the planet doesn't rotate, so one side would always be sunlit and the other dark.
Distance is another problem. "We don't know how to get to those places in a human lifetime," Maran said.
Two teams of astronomers, one in Europe and one in the United States, have been racing to be the first to find a planet like 581 c outside the solar system.
The European team looked at 100 different stars using a tool called HARPS (High Accuracy Radial Velocity for Planetary Searcher) to find this one planet, said Xavier Bonfils of the Lisbon Observatory, one of the co-discoverers.
Much of the effort to find Earth-like planets has focused on stars like our sun with the challenge being to find a planet the right distance from the star it orbits. About 90 percent of the time, the European telescope focused its search more on sun-like stars, Udry said.
A few weeks before the European discovery earlier this month, a scientific paper in the journal Astrobiology theorized a few days that red dwarf stars were good candidates.
"Now we have the possibility to find many more," Bonfils said.
Tuesday, April 24, 2007
Code Access Security (CAS) and Design Patterns
http://www.codeproject.com/gen/design/CASDesignPatterns.asp
Introduction
To be classified as a good developer is no longer characterized by merely writing manageable and well-documented code, but by today’s definition it also includes knowing how to write a secure code. This has priority over all other qualities assessed. Last year "Web Services" was the buzz in the technology field, but has since been replaced with "Security". Many job positions have been modified to include Security as a primary responsibility. On many levels of the Corporate Enterprise, changes are made to ensure that production systems are Secure and hackers cannot gain control of critical applications inside the businesses. When it comes to "Security", there are so many layers; it is like an onion in which every layer that is peeled away, reveals yet another layer and so on. It takes great effort and much invested time in order to expose the core of the onion and the same is true with Security. In today’s installment, I want to peel that initial layer from regarding the Security topic. I regret not being familiar with this technology a year ago, but have put forth much effort this year to learn, manipulate and implement solutions with this highly demanded skill. The outcome of my personal endeavor is my collective thoughts and learning’s that you will find below. My main goal was to decipher the complexity of Code Access Security (CAS for short) into simple, understandable English supplemented with colorful diagrams to reinforce the knowledge. A picture speaks a thousand words!
What is Code Access Security?
The world has drastically changed in these last few years. This week I was in Washington DC, our capital, and was shocked with the measures that have been taken through the city to ensure the security of the government and historical monuments. Even though some of the buildings were surrounded with huge flower pots, beautified barricades, I still felt a sense of exclusion as I walked through the streets. This is a perfect example of what security is all about. I looked up the meaning of the word "Security" and here is what I found: "Freedom from risk or danger". To be honest with you, I did not expect to see the word "freedom" anywhere in the definition of a word that at its core compromises freedom. After contemplating, it began to make sense after all. Traveling through airports a few years back did not require extensive scanning procedures on passengers and their luggage. Also, friends and family members still had the ability to say their last good-byes at the boarding gates. This is no longer the case; Security at airports has changed so dramatically. What we see here is countermeasures that have been taken by our government to prevent another 9/11 from happening. As developers and computer users, we’ve seen how a harmless computer virus can evolve into detrimental pieces of code targeted to steal our personal information, destroy systems and take over our computers. Of course, as our government and major software companies roll-out countermeasures for computer security, we developers need to be on top of the issue as well and this requires a proactive approach in the Security our own applications. Microsoft has launched the trustworthy initiative that includes not only developing secure code for their own products, but also a means for developers to write trustworthy code. In order to write secure code though, we need to be educated and the whole paradigm shift needs to fall into place before developers begin writing secure code. Is Microsoft doing a good job of educating us? You can answer this from your own perspective; surely there is much more that can be done. Recently, I attended the Security Summit where a number of tracks were presented. The reoccurring theme of the seminar was to engage developers to begin thinking about the actions needed to develop secure code. If security is a set of actions that ultimately prevents us from being exposed and vulnerable again and again, then we need to be aware of the techniques and tactics of the Hacker. Education is a critical role to make this fortification happen.
Role-Based security is at the heart of Microsoft Windows 2000/XP operating systems, but it isn’t enough to depend on the code itself and to neglect the skills and awareness of the user. This security model cares about user access secure resources and any code usually runs under the credentials of the logged on user. Here is a common scenario for Windows users: "John, the accountant, needs to file some information with the partner site, so he typed in the partners URL into the web browser. Next thing he knows, a message box pops up that reads: "In order to run this application we need to install ActiveX control on your machine, do you trust us? For John it means the following: "Do I want to be productive today?" Of course, he answers with a "Yes", which successfully installs this piece of the software, but John has no clue what secure resources this application has been granted to access it. This all happened just because he agreed to one pop-up message. What is wrong with this approach? Off the top of my head two things are wrong:
Installed ActiveX runs under John’s user security permission set or it can do pretty much anything with the system that John can. (Delete, update files, etc.)
John has no idea of what the ActiveX does and most likely it doesn’t cross his mind, but what matters to John is being productive and his computer being secure.
The recent virus "Sasser" does not require user interaction for the computer to get infected; simply plug an unprotected machine to the net and in a matter of minutes it becomes infected. So, Code Access Security picks up where Role-Based security falls short. It provides it with the mechanism of securing the code based on who wrote it and where it came from, or where it is executed (evidences). These evidences are mapped to the permissions (rights), which can be administered by four different policies, which correspond to the role user represents:
Domain Administrator – Enterprise Policy
Machine Administrator – Machine Policy
Actual User of the machine - User Policy
Developer - Application domain Policy
These policies are configurable after the application is deployed and can be modified at any point in time. One major concept was introduced with CAS - Partially trusted code is code that has been granted only access to the resources it needs to execute successfully and no more. Looking at the big picture, Code Access Security and Role-Based security both support the same Patterns, which I call "2AR" as demonstrated in the diagram below.
Security Identity Pattern "2AR" includes the process of determining the identity and then assigning it to a group, which corresponds to the permission set (rights), which can be performed on the secure resource. The key to this pattern is Reinforcement of the access to the secure resource. The process of reinforcement will not allow unauthorized access to the secure resource without going through the process of Authentication and Authorization. Common Language Runtime (CLR) accomplishes this by means of a Stack- Walk, which can be compared to the following scenario:
"Teenager Joe (19 years of age) wanted to drink some beer with his friends, but he could not legally go to the store to purchase it himself, so he asked his older friend if he could get it for him. Even though Bill (20 years of age) is older he is not old enough to purchase beer at the store, so he talks his dad into buying it for his friend. Bill’s dad knows he is breaking the law, but he still does it. The Store Clerk checks Bill’s driver license and finds he is over 21, so he sells a pack of beer to him."
The chain of request from Joe--> Bill --> Bill’s Dad to the clerk represents the software concept of the Stack-Walk.
In the real-world, the beer will be sold because there is only one ID check and all of the chain members of the request do not need to present proper ID to the clerk, just Bill’s dad. Joe and Bill represent partially trusted code and Bill’s dad represents fully trusted code as far as the system is concerned. That is exactly what is happening when viruses gain access to a secure resource by luring it to do its dirty work. In .NET Framework scenario CLR prevents a successful Stack-Walk from happening, because it requests proper ID on every level of the chain cell; therefore, if somebody in the chain does not have proper ID then it consequently rejects the requests on all levels. Thus, if CLR reinforcement rules were applied to a real-life scenario than Joe or Bill would never have the beer. The following scenario will fail by the time it reaches Bill. Realistically, some of the code that is partially trusted (does not have full access to the system) sometimes needs to have access to fully trusted resources and that is where modifications of the stack-walk comes into play.
In the diagram above the Clerk denies (Deny) anybody who does not have proper ID (evidence) to sell beer, but Bill’s dad permits (PermitOnly) his son and his son’s friend to drink beer because he has almost reached the legal age. Outsmarting the system neither makes it right nor legal, only possible. When Bill gets his beer he shares it with his friend (Assert or voucher) and they enjoy beer together on a sunny day. Code Access Security provides us with this flexibility, but we need to be aware that it also introduces greater security risk; therefore, design your systems in advance. I demonstrated how to use the Deny(), PermitOnly() and Assert() to modify Stack-Walk. This is not a complete list of modifiers. Please reference to .NET Framework SDK for more info (Overriding Security Checks). I just wanted to get your feet wet; the rest of the onion peeling is in your hands!!
This is as simple as it gets when it comes to Code Access Security and its patterns. Now, the complexity comes with understanding CAS terminology and the .NET Framework implementation of it.
Learning Code Access Security through ASP.NET implementation
This learning process usually starts with discovering how to use Code Access Security for the existing applications and then later applying it for your own projects. I have read a great deal of resources and nothing clicked for me, until I started working with Microsoft SharePoint 2004 that extends ASP.NET architecture and relies on CAS to secure its resources. Since not everyone is developing with SharePoint server just yet, Microsoft hopes to corner the portal market soon with this product. I chose to demonstrate and explain the main concepts of CAS through ASP.NET technology.
The most common scenario that demonstrates Code Access Security is smart client application. It has been downloaded over the intranet and has certain permissions (rights), but ASP.NET is installed on the machine and runs locally on the computer; thus, this scenario does not explain fully the CAS. We determine that code either can be executed by itself (smart client scenario) or hosted by Host Assembly or Unmanaged Code (IIS Filter). This is the main difference where the Evidences will come from.
Therefore, there are two ways an assembly can be loaded:
User clicks on executable and code executes
Host assembly loads your assembly by means of Reflection or unmanaged code initialized the CLR.
Most people do not realize that CLR is not native to Win32; therefore, it is hosted by unmanaged code. In the smart client scenario assembly executable runs by itself, so default evidence gathering process is invoked as demonstrated below:
CLR Policy evaluator will gather evidence automatically, and you can not supply your own evidences at this point. Application domain policy is optional. What has been gathered by the Policy Evaluator is a set of Evidences about the code. Policy Evaluator gathers evidence and grants a set of permission every time your code has been executed by JIT. There are 7 default evidence types, which can be split into two groups:
Assembly Evidence – answers the question "Who is the author of the Assembly" For example, all of Microsoft CLR classes signed with the same private/public key pair, which allows CLR to determine that Microsoft developers wrote the code and grantsfull trust (full control) to the system.
Host Evidence – answers the questions "Where did the Assembly come from?" If you started a smart client by referencing the URL location and than at a later date you move the executable to a local hard-drive, CLR does not track the history of its location.
Of course, like everything else it is possible to write your own Evidence class and provide custom Evidence object for your applications.
ASP.NET unmanaged IIS filter hosts managed ASP.NET process and passes needed information from unmanaged world into managed process. This scenario is an exception and most likely if you need to host an Assembly you will use managed code and use Reflection to load the assemblies. Rockford Lhotka business object framework has a nice utility (NetRun) for smart clients, which basically modifies machine polices for the hosted Smart Client Applications.
ASP.NET relies on the Application Domain policy to provide extra flexibility for configuring the applications. That is why I have ASP.NET and SharePoint on the slides above.
What is Policy? It is a configuration file containing information about what the code can do depending on the code evidence. There are four levels of configurations for the applications, which are based on administration needs. They are as follows:
Enterprise Policy – default setting allows all code to have full trust.
Machine Policy - configured by default to give the assemblies installed in Global Assembly Cache full trust and others.
User Policy – if the user wants he can restrict its machine based on these settings.
Application Domain Policy – security configuration for the application.
The process of evaluating permissions (rights) between different polices levels is known as "Intersection". Intersection is a complex algorithm to determine the final or Grant Set of Permissions. There are two things to remember about policies:
Policies are based on the hierarchy structure; thus, if the top layer of the policy grants no permissions (rights) to the code, then the policy below it cannot grant permissions either.
All of the policies have to agree on permission, before that permission can make a final grant permission set.
To demonstrate simply how Policies work together, I diagramed the following:
This diagram includes ASP.NET Application Domain policies levels that normal application does not have. There are 5 default ASP.NET Application policies:
Full
High
Medium
Low
Minimal
All policies correspond to a physical file, with the exception of Full, which has a built in policy (full control). I can create my own Policy file by simply adding an entry to the Machine.config as follows:
Did you know that ASP.NET by default runs under Full trust? You can change it by modifying trust level attribute of the Machine.Config file for the server or Web.Config for the virtual directory:
Here is a very simple scenario for you guys, to try out and learn about CAS.
Create a WebService on a local machine with IIS Server and add a simple method "SayHi" that returns a string "Hello World"
Create an ASP.NET application and Add Web Reference to your WebService
Add a button, wire the click event to call the WebService method for "SayHi" and display return value into the label.
Build and View in the Browser. It should work with no problem.
Add trust level attribute and set it to Minimal
Does it still work?
If you get a Security Permission Exception then you have done everything right. How can you fix it? The Policy contains information about what the code can do based on the evidence. By switching Application Domain Policy for ASP.NET from Full to Minimal we can change what the code can do and this is where the understanding of Code Groups --> Membership Conditions --> Permission Sets and Permissions begins.
All right, first things first; Code Groups are containers for Permissions (rights) that the code can have based on the Evidence, which are the XML elements within the policy configuration file. There are 7 defaults evidence types and they are mapped out on a one-to-one relationship to Membership Condition element of Code Group, plus one Membership Condition that maps all of the code.
Code can belong to a Code Group based on the Membership Condition, which reflects the evidence that has been collected or provided to a policy evaluator while assembly was loading. We know that in ASP.NET applications the code executes in the virtual directories; therefore we can create the following Code Group to match this condition.
Code Groups can contain child Code Groups; therefore, it is possible to create permissions across matched groups. Most commonly used Code Groups types are Union (AND) and First Match (stop when the match is found). It is also possible to use PolicyStatementAttribute to provide the mechanism to stop policy evaluator from calculating the remainder of the hierarchy of policies. Options are Exclusive or LevelFinal. Please refer to .NET Framework SDK for more info.
What is a Permission Set? A Permission Set is a combination of all the permissions (rights) that can be granted to the code. There are 6 Immutable (pre-built) Permission Sets that we can not modify, meaning we can add or delete them from the permissions collection:
If you noticed "Everything" and "ASP.NET "are Named Permission Sets but they are mutable and I can freely add or delete permissions to it. I also can create my own name for XML PermissionSet element and combined permissions if I want this Permission Set to have it.
Now, we are back to our earlier scenario with WebService. Do you still want to fix it or have you already given up on the idea?
Of course, you want to fix it. I know I did. What I found out was that in order for the WebServices calls to work properly we needed to allow WebHttpRequest/ WebHttpResponse classes to have WebPermission granted. If you look at web_minimal.config configuration file you will find the following entry for ASP.NET Permission set:
This Permission Set does not give much rights for my virtual directory code (ASP.NET application).
Microsoft always likes to gives us many options to do the same thing and works in our favor.
Our First option will be to find out which ASP.NET Application Domain Policy file contains the WebPermission. You can do it by simply looking through the Policy files. You will find that web_mediumtrust.config has WebPermission as a part of ASP.NET Permission Set:
So all you need to is modify your web.config file to the following
Now, when you run the application it should work without a hitch. OriginUrl is used to grant permissions to the specific web server. What if you had references to more then one server?
Then simply make the following entry in web_mediumtrust.config:
Our Second option involves creating a custom policy. For example, if I really wanted to lock down my server and only allow running under Minimal trust level, then I need to create a custom Policy based on Minimal trust level and then add permissions (rights) for WebService execution.
Here are the steps for creating ASP.NET Application Domain Policy, which has minimal trust level and allows calling WebServices:
Navigate to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG or the location where .NET Framework is installed on your machine.
Open Machine.config file and below default ASP.NET trust levels
Create a copy of web_minimaltrust.config and name it web_minimal_Web.config or what you desire your policy file to be named
Open web_minimal_Web.config and now we’re ready to make modifications needed to grant WebPermission to ASP.NET PermissionSet
Add reference to WebPermission assembly between Element:
Description="System.Net.WebPermission, System, Version=1.0.5000.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089" />
Navigate to ASP.NET Named Permission Set and add
Open your Web.Config file within ASP.NET application and add the following
Build and View it in the browser. It should work like a charm
if you followed all of the steps you were successful in creating a custom policy and running ASP.NET application with a Minimal Trust level (permissions that are requiring running the application and no more).
Let me summarize the whole process quickly for you. Unmanaged Code loads ASP.NET assembly and provides it with a set of Evidences. There are five ASP.NET Application Domain polices that configured by modifying trust attribute of the Machine.Config or Web.Config files. Policy Evaluator performs "intersection" on four polices (enterprise, machine, user, application domain) and maps Evidence to a membership condition of the Code Group that supply permissions (rights). If all the policies agree between different levels then permission set is included in the grant set.
Declarative vs. Imperative
The main difference is where the information is stored in an assembly as shown below:
Manifest stores Metadata information that can be read without running the assembly; therefore if you used Declarative security to enforce security than I can simply run command-line utility (Permview.exe) to view what Permission I need to have to run your code. In comparision, Imperative is more flexible and is stored as MSIL code, which will be compiled in JIT and given a Security Exception at run-time.
At this point, I did not cover the issue of using CAS in your own code. I tried my best to provide you with a slightly different angle on how Code Access Security is used or can be used. I barely scratched the surface with this article. There is so much more out there as far as configuring and developing techniques with CAS. In my next installment, I will be talking about how to configure Sandbox for your ASP.NET applications. I also will be kicking off a one day, hands-on workshop on CAS coming this June for more info contact me.
Stay tuned.
Copyright © 2003-2004 Maxim V. Karpov All rights reserved.
About Maxim V. Karpov
Introduction
To be classified as a good developer is no longer characterized by merely writing manageable and well-documented code, but by today’s definition it also includes knowing how to write a secure code. This has priority over all other qualities assessed. Last year "Web Services" was the buzz in the technology field, but has since been replaced with "Security". Many job positions have been modified to include Security as a primary responsibility. On many levels of the Corporate Enterprise, changes are made to ensure that production systems are Secure and hackers cannot gain control of critical applications inside the businesses. When it comes to "Security", there are so many layers; it is like an onion in which every layer that is peeled away, reveals yet another layer and so on. It takes great effort and much invested time in order to expose the core of the onion and the same is true with Security. In today’s installment, I want to peel that initial layer from regarding the Security topic. I regret not being familiar with this technology a year ago, but have put forth much effort this year to learn, manipulate and implement solutions with this highly demanded skill. The outcome of my personal endeavor is my collective thoughts and learning’s that you will find below. My main goal was to decipher the complexity of Code Access Security (CAS for short) into simple, understandable English supplemented with colorful diagrams to reinforce the knowledge. A picture speaks a thousand words!
What is Code Access Security?
The world has drastically changed in these last few years. This week I was in Washington DC, our capital, and was shocked with the measures that have been taken through the city to ensure the security of the government and historical monuments. Even though some of the buildings were surrounded with huge flower pots, beautified barricades, I still felt a sense of exclusion as I walked through the streets. This is a perfect example of what security is all about. I looked up the meaning of the word "Security" and here is what I found: "Freedom from risk or danger". To be honest with you, I did not expect to see the word "freedom" anywhere in the definition of a word that at its core compromises freedom. After contemplating, it began to make sense after all. Traveling through airports a few years back did not require extensive scanning procedures on passengers and their luggage. Also, friends and family members still had the ability to say their last good-byes at the boarding gates. This is no longer the case; Security at airports has changed so dramatically. What we see here is countermeasures that have been taken by our government to prevent another 9/11 from happening. As developers and computer users, we’ve seen how a harmless computer virus can evolve into detrimental pieces of code targeted to steal our personal information, destroy systems and take over our computers. Of course, as our government and major software companies roll-out countermeasures for computer security, we developers need to be on top of the issue as well and this requires a proactive approach in the Security our own applications. Microsoft has launched the trustworthy initiative that includes not only developing secure code for their own products, but also a means for developers to write trustworthy code. In order to write secure code though, we need to be educated and the whole paradigm shift needs to fall into place before developers begin writing secure code. Is Microsoft doing a good job of educating us? You can answer this from your own perspective; surely there is much more that can be done. Recently, I attended the Security Summit where a number of tracks were presented. The reoccurring theme of the seminar was to engage developers to begin thinking about the actions needed to develop secure code. If security is a set of actions that ultimately prevents us from being exposed and vulnerable again and again, then we need to be aware of the techniques and tactics of the Hacker. Education is a critical role to make this fortification happen.
Role-Based security is at the heart of Microsoft Windows 2000/XP operating systems, but it isn’t enough to depend on the code itself and to neglect the skills and awareness of the user. This security model cares about user access secure resources and any code usually runs under the credentials of the logged on user. Here is a common scenario for Windows users: "John, the accountant, needs to file some information with the partner site, so he typed in the partners URL into the web browser. Next thing he knows, a message box pops up that reads: "In order to run this application we need to install ActiveX control on your machine, do you trust us? For John it means the following: "Do I want to be productive today?" Of course, he answers with a "Yes", which successfully installs this piece of the software, but John has no clue what secure resources this application has been granted to access it. This all happened just because he agreed to one pop-up message. What is wrong with this approach? Off the top of my head two things are wrong:
Installed ActiveX runs under John’s user security permission set or it can do pretty much anything with the system that John can. (Delete, update files, etc.)
John has no idea of what the ActiveX does and most likely it doesn’t cross his mind, but what matters to John is being productive and his computer being secure.
The recent virus "Sasser" does not require user interaction for the computer to get infected; simply plug an unprotected machine to the net and in a matter of minutes it becomes infected. So, Code Access Security picks up where Role-Based security falls short. It provides it with the mechanism of securing the code based on who wrote it and where it came from, or where it is executed (evidences). These evidences are mapped to the permissions (rights), which can be administered by four different policies, which correspond to the role user represents:
Domain Administrator – Enterprise Policy
Machine Administrator – Machine Policy
Actual User of the machine - User Policy
Developer - Application domain Policy
These policies are configurable after the application is deployed and can be modified at any point in time. One major concept was introduced with CAS - Partially trusted code is code that has been granted only access to the resources it needs to execute successfully and no more. Looking at the big picture, Code Access Security and Role-Based security both support the same Patterns, which I call "2AR" as demonstrated in the diagram below.
Security Identity Pattern "2AR" includes the process of determining the identity and then assigning it to a group, which corresponds to the permission set (rights), which can be performed on the secure resource. The key to this pattern is Reinforcement of the access to the secure resource. The process of reinforcement will not allow unauthorized access to the secure resource without going through the process of Authentication and Authorization. Common Language Runtime (CLR) accomplishes this by means of a Stack- Walk, which can be compared to the following scenario:
"Teenager Joe (19 years of age) wanted to drink some beer with his friends, but he could not legally go to the store to purchase it himself, so he asked his older friend if he could get it for him. Even though Bill (20 years of age) is older he is not old enough to purchase beer at the store, so he talks his dad into buying it for his friend. Bill’s dad knows he is breaking the law, but he still does it. The Store Clerk checks Bill’s driver license and finds he is over 21, so he sells a pack of beer to him."
The chain of request from Joe--> Bill --> Bill’s Dad to the clerk represents the software concept of the Stack-Walk.
In the real-world, the beer will be sold because there is only one ID check and all of the chain members of the request do not need to present proper ID to the clerk, just Bill’s dad. Joe and Bill represent partially trusted code and Bill’s dad represents fully trusted code as far as the system is concerned. That is exactly what is happening when viruses gain access to a secure resource by luring it to do its dirty work. In .NET Framework scenario CLR prevents a successful Stack-Walk from happening, because it requests proper ID on every level of the chain cell; therefore, if somebody in the chain does not have proper ID then it consequently rejects the requests on all levels. Thus, if CLR reinforcement rules were applied to a real-life scenario than Joe or Bill would never have the beer. The following scenario will fail by the time it reaches Bill. Realistically, some of the code that is partially trusted (does not have full access to the system) sometimes needs to have access to fully trusted resources and that is where modifications of the stack-walk comes into play.
In the diagram above the Clerk denies (Deny) anybody who does not have proper ID (evidence) to sell beer, but Bill’s dad permits (PermitOnly) his son and his son’s friend to drink beer because he has almost reached the legal age. Outsmarting the system neither makes it right nor legal, only possible. When Bill gets his beer he shares it with his friend (Assert or voucher) and they enjoy beer together on a sunny day. Code Access Security provides us with this flexibility, but we need to be aware that it also introduces greater security risk; therefore, design your systems in advance. I demonstrated how to use the Deny(), PermitOnly() and Assert() to modify Stack-Walk. This is not a complete list of modifiers. Please reference to .NET Framework SDK for more info (Overriding Security Checks). I just wanted to get your feet wet; the rest of the onion peeling is in your hands!!
This is as simple as it gets when it comes to Code Access Security and its patterns. Now, the complexity comes with understanding CAS terminology and the .NET Framework implementation of it.
Learning Code Access Security through ASP.NET implementation
This learning process usually starts with discovering how to use Code Access Security for the existing applications and then later applying it for your own projects. I have read a great deal of resources and nothing clicked for me, until I started working with Microsoft SharePoint 2004 that extends ASP.NET architecture and relies on CAS to secure its resources. Since not everyone is developing with SharePoint server just yet, Microsoft hopes to corner the portal market soon with this product. I chose to demonstrate and explain the main concepts of CAS through ASP.NET technology.
The most common scenario that demonstrates Code Access Security is smart client application. It has been downloaded over the intranet and has certain permissions (rights), but ASP.NET is installed on the machine and runs locally on the computer; thus, this scenario does not explain fully the CAS. We determine that code either can be executed by itself (smart client scenario) or hosted by Host Assembly or Unmanaged Code (IIS Filter). This is the main difference where the Evidences will come from.
Therefore, there are two ways an assembly can be loaded:
User clicks on executable and code executes
Host assembly loads your assembly by means of Reflection or unmanaged code initialized the CLR.
Most people do not realize that CLR is not native to Win32; therefore, it is hosted by unmanaged code. In the smart client scenario assembly executable runs by itself, so default evidence gathering process is invoked as demonstrated below:
CLR Policy evaluator will gather evidence automatically, and you can not supply your own evidences at this point. Application domain policy is optional. What has been gathered by the Policy Evaluator is a set of Evidences about the code. Policy Evaluator gathers evidence and grants a set of permission every time your code has been executed by JIT. There are 7 default evidence types, which can be split into two groups:
Assembly Evidence – answers the question "Who is the author of the Assembly" For example, all of Microsoft CLR classes signed with the same private/public key pair, which allows CLR to determine that Microsoft developers wrote the code and grantsfull trust (full control) to the system.
Host Evidence – answers the questions "Where did the Assembly come from?" If you started a smart client by referencing the URL location and than at a later date you move the executable to a local hard-drive, CLR does not track the history of its location.
Of course, like everything else it is possible to write your own Evidence class and provide custom Evidence object for your applications.
ASP.NET unmanaged IIS filter hosts managed ASP.NET process and passes needed information from unmanaged world into managed process. This scenario is an exception and most likely if you need to host an Assembly you will use managed code and use Reflection to load the assemblies. Rockford Lhotka business object framework has a nice utility (NetRun) for smart clients, which basically modifies machine polices for the hosted Smart Client Applications.
ASP.NET relies on the Application Domain policy to provide extra flexibility for configuring the applications. That is why I have ASP.NET and SharePoint on the slides above.
What is Policy? It is a configuration file containing information about what the code can do depending on the code evidence. There are four levels of configurations for the applications, which are based on administration needs. They are as follows:
Enterprise Policy – default setting allows all code to have full trust.
Machine Policy - configured by default to give the assemblies installed in Global Assembly Cache full trust and others.
User Policy – if the user wants he can restrict its machine based on these settings.
Application Domain Policy – security configuration for the application.
The process of evaluating permissions (rights) between different polices levels is known as "Intersection". Intersection is a complex algorithm to determine the final or Grant Set of Permissions. There are two things to remember about policies:
Policies are based on the hierarchy structure; thus, if the top layer of the policy grants no permissions (rights) to the code, then the policy below it cannot grant permissions either.
All of the policies have to agree on permission, before that permission can make a final grant permission set.
To demonstrate simply how Policies work together, I diagramed the following:
This diagram includes ASP.NET Application Domain policies levels that normal application does not have. There are 5 default ASP.NET Application policies:
Full
High
Medium
Low
Minimal
All policies correspond to a physical file, with the exception of Full, which has a built in policy (full control). I can create my own Policy file by simply adding an entry to the Machine.config as follows:
Did you know that ASP.NET by default runs under Full trust? You can change it by modifying trust level attribute of the Machine.Config file for the server or Web.Config for the virtual directory:
Here is a very simple scenario for you guys, to try out and learn about CAS.
Create a WebService on a local machine with IIS Server and add a simple method "SayHi" that returns a string "Hello World"
Create an ASP.NET application and Add Web Reference to your WebService
Add a button, wire the click event to call the WebService method for "SayHi" and display return value into the label.
Build and View in the Browser. It should work with no problem.
Add trust level attribute and set it to Minimal
Does it still work?
If you get a Security Permission Exception then you have done everything right. How can you fix it? The Policy contains information about what the code can do based on the evidence. By switching Application Domain Policy for ASP.NET from Full to Minimal we can change what the code can do and this is where the understanding of Code Groups --> Membership Conditions --> Permission Sets and Permissions begins.
All right, first things first; Code Groups are containers for Permissions (rights) that the code can have based on the Evidence, which are the XML elements within the policy configuration file. There are 7 defaults evidence types and they are mapped out on a one-to-one relationship to Membership Condition element of Code Group, plus one Membership Condition that maps all of the code.
Code can belong to a Code Group based on the Membership Condition, which reflects the evidence that has been collected or provided to a policy evaluator while assembly was loading. We know that in ASP.NET applications the code executes in the virtual directories; therefore we can create the following Code Group to match this condition.
Code Groups can contain child Code Groups; therefore, it is possible to create permissions across matched groups. Most commonly used Code Groups types are Union (AND) and First Match (stop when the match is found). It is also possible to use PolicyStatementAttribute to provide the mechanism to stop policy evaluator from calculating the remainder of the hierarchy of policies. Options are Exclusive or LevelFinal. Please refer to .NET Framework SDK for more info.
What is a Permission Set? A Permission Set is a combination of all the permissions (rights) that can be granted to the code. There are 6 Immutable (pre-built) Permission Sets that we can not modify, meaning we can add or delete them from the permissions collection:
If you noticed "Everything" and "ASP.NET "are Named Permission Sets but they are mutable and I can freely add or delete permissions to it. I also can create my own name for XML PermissionSet element and combined permissions if I want this Permission Set to have it.
Now, we are back to our earlier scenario with WebService. Do you still want to fix it or have you already given up on the idea?
Of course, you want to fix it. I know I did. What I found out was that in order for the WebServices calls to work properly we needed to allow WebHttpRequest/ WebHttpResponse classes to have WebPermission granted. If you look at web_minimal.config configuration file you will find the following entry for ASP.NET Permission set:
This Permission Set does not give much rights for my virtual directory code (ASP.NET application).
Microsoft always likes to gives us many options to do the same thing and works in our favor.
Our First option will be to find out which ASP.NET Application Domain Policy file contains the WebPermission. You can do it by simply looking through the Policy files. You will find that web_mediumtrust.config has WebPermission as a part of ASP.NET Permission Set:
So all you need to is modify your web.config file to the following
Now, when you run the application it should work without a hitch. OriginUrl is used to grant permissions to the specific web server. What if you had references to more then one server?
Then simply make the following entry in web_mediumtrust.config:
Our Second option involves creating a custom policy. For example, if I really wanted to lock down my server and only allow running under Minimal trust level, then I need to create a custom Policy based on Minimal trust level and then add permissions (rights) for WebService execution.
Here are the steps for creating ASP.NET Application Domain Policy, which has minimal trust level and allows calling WebServices:
Navigate to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG or the location where .NET Framework is installed on your machine.
Open Machine.config file and
Create a copy of web_minimaltrust.config and name it web_minimal_Web.config or what you desire your policy file to be named
Open web_minimal_Web.config and now we’re ready to make modifications needed to grant WebPermission to ASP.NET PermissionSet
Add reference to WebPermission assembly between
Culture=neutral, PublicKeyToken=b77a5c561934e089" />
Navigate to ASP.NET Named Permission Set and add
Open your Web.Config file within ASP.NET application and add the following
Build and View it in the browser. It should work like a charm
if you followed all of the steps you were successful in creating a custom policy and running ASP.NET application with a Minimal Trust level (permissions that are requiring running the application and no more).
Let me summarize the whole process quickly for you. Unmanaged Code loads ASP.NET assembly and provides it with a set of Evidences. There are five ASP.NET Application Domain polices that configured by modifying trust attribute of the Machine.Config or Web.Config files. Policy Evaluator performs "intersection" on four polices (enterprise, machine, user, application domain) and maps Evidence to a membership condition of the Code Group that supply permissions (rights). If all the policies agree between different levels then permission set is included in the grant set.
Declarative vs. Imperative
The main difference is where the information is stored in an assembly as shown below:
Manifest stores Metadata information that can be read without running the assembly; therefore if you used Declarative security to enforce security than I can simply run command-line utility (Permview.exe) to view what Permission I need to have to run your code. In comparision, Imperative is more flexible and is stored as MSIL code, which will be compiled in JIT and given a Security Exception at run-time.
At this point, I did not cover the issue of using CAS in your own code. I tried my best to provide you with a slightly different angle on how Code Access Security is used or can be used. I barely scratched the surface with this article. There is so much more out there as far as configuring and developing techniques with CAS. In my next installment, I will be talking about how to configure Sandbox for your ASP.NET applications. I also will be kicking off a one day, hands-on workshop on CAS coming this June for more info contact me.
Stay tuned.
Copyright © 2003-2004 Maxim V. Karpov All rights reserved.
About Maxim V. Karpov
Tuesday, April 17, 2007
C++ Type Casting
Type Casting Published by Juan Soulie
Last update on Jan 26, 2007 at 2:47am
Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast:
Implicit conversion
Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:
short a=2000;
int b;
b=a;
Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.
Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. For example:
class A {};
class B { public: B (A a) {} };
A a;
B b=a;
Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed.
Explicit conversion
C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:
short a=2000;
int b;
b = (int) a; // c-like cast notation
b = int (a); // functional notation
The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors. For example, the following code is syntactically correct:
// class type-casting
#include
using namespace std;
class CDummy {
float i,j;
};
class CAddition {
int x,y;
public:
CAddition (int a, int b) { x=a; y=b; }
int result() { return x+y;}
};
int main () {
CDummy d;
CAddition * padd;
padd = (CAddition*) &d;
cout << padd->result();
return 0;
}
The program declares a pointer to CAddition, but then it assigns to it a reference to an object of another incompatible type using explicit type-casting:
padd = (CAddition*) &d;
Traditional explicit type-casting allows to convert any pointer into any other pointer type, independently of the types they point to. The subsequent call to member result will produce either a run-time error or a unexpected result.
In order to control these types of conversions between classes, we have four specific casting operators: dynamic_cast, reinterpret_cast, static_cast and const_cast. Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses.
dynamic_cast (expression)
reinterpret_cast (expression)
static_cast (expression)
const_cast (expression)
The traditional type-casting equivalents to these expressions would be:
(new_type) expression
new_type (expression)
but each one with its own special characteristics:
dynamic_cast
dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.
Therefore, dynamic_cast is always successful when we cast a class to one of its base classes:
class CBase { };
class CDerived: public CBase { };
CBase b; CBase* pb;
CDerived d; CDerived* pd;
pb = dynamic_cast(&d); // ok: derived-to-base
pd = dynamic_cast(&b); // wrong: base-to-derived
The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with dynamic_cast unless the base class is polymorphic.
When a class is polymorphic, dynamic_cast performs a special checking during runtime to ensure that the expression yields a valid complete object of the requested class:
// dynamic_cast
#include
#include
using namespace std;
class CBase { virtual void dummy() {} };
class CDerived: public CBase { int a; };
int main () {
try {
CBase * pba = new CDerived;
CBase * pbb = new CBase;
CDerived * pd;
pd = dynamic_cast(pba);
if (pd==0) cout << "Null pointer on first type-cast" << endl;
pd = dynamic_cast(pbb);
if (pd==0) cout << "Null pointer on second type-cast" << endl;
} catch (exception& e) {cout << "Exception: " << e.what();}
return 0;
}
Null pointer on second type-cast
Compatibility note: dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. This must be enabled for runtime type checking using dynamic_cast to work properly.
The code tries to perform two dynamic casts from pointer objects of type CBase* (pba and pbb) to a pointer object of type CDerived*, but only the first one is successful. Notice their respective initializations:
CBase * pba = new CDerived;
CBase * pbb = new CBase;
Even though both are pointers of type CBase*, pba points to an object of type CDerived, while pbb points to an object of type CBase. Thus, when their respective type-castings are performed using dynamic_cast, pba is pointing to a full object of class CDerived, whereas pbb is pointing to an object of class CBase, which is an incomplete object of class CDerived.
When dynamic_cast cannot cast a pointer because it is not a complete object of the required class -as in the second conversion in the previous example- it returns a null pointer to indicate the failure. If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_alloc is thrown instead.
dynamic_cast can also cast null pointers even between pointers to unrelated classes, and can also cast pointers of any type to void pointers (void*).
static_cast
static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided.
class CBase {};
class CDerived: public CBase {};
CBase * a = new CBase;
CDerived * b = static_cast(a);
This would be valid, although b would point to an incomplete object of the class and could lead to runtime errors if dereferenced.
static_cast can also be used to perform any other non-pointer conversion that could also be performed implicitly, like for example standard conversion between fundamental types:
double d=3.14159265;
int i = static_cast(d);
Or any conversion between classes with explicit constructors or operator functions as described in "implicit conversions" above.
reinterpret_cast
reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.
It can also cast pointers to or from integer types. The format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it, is granted to be able to be cast back to a valid pointer.
The conversions that can be performed by reinterpret_cast but not by static_cast have no specific uses in C++ are low-level operations, whose interpretation results in code which is generally system-specific, and thus non-portable. For example:
class A {};
class B {};
A * a = new A;
B * b = reinterpret_cast(a);
This is valid C++ code, although it does not make much sense, since now we have a pointer that points to an object of an incompatible class, and thus dereferencing it is unsafe.
const_cast
This type of casting manipulates the constness of an object, either to be set or to be removed. For example, in order to pass a const argument to a function that expects a non-constant parameter:
// const_cast
#include
using namespace std;
void print (char * str)
{
cout << str << endl;
}
int main () {
const char * c = "sample text";
print ( const_cast (c) );
return 0;
}
sample text
typeid
typeid allows to check the type of an expression:
typeid (expression)
This operator returns a reference to a constant object of type type_info that is defined in the standard header file. This returned value can be compared with another one using operators == and != or can serve to obtain a null-terminated character sequence representing the data type or class name by using its name() member.
// typeid
#include
#include
using namespace std;
int main () {
int * a,b;
a=0; b=0;
if (typeid(a) != typeid(b))
{
cout << "a and b are of different types:\n";
cout << "a is: " << typeid(a).name() << '\n';
cout << "b is: " << typeid(b).name() << '\n';
}
return 0;
}
a and b are of different types:
a is: int *
b is: int
When typeid is applied to classes typeid uses the RTTI to keep track of the type of dynamic objects. When typeid is applied to an expression whose type is a polymorphic class, the result is the type of the most derived complete object:
// typeid, polymorphic class
#include
#include
#include
using namespace std;
class CBase { virtual void f(){} };
class CDerived : public CBase {};
int main () {
try {
CBase* a = new CBase;
CBase* b = new CDerived;
cout << "a is: " << typeid(a).name() << '\n';
cout << "b is: " << typeid(b).name() << '\n';
cout << "*a is: " << typeid(*a).name() << '\n';
cout << "*b is: " << typeid(*b).name() << '\n';
} catch (exception& e) { cout << "Exception: " << e.what() << endl; }
return 0;
}
a is: class CBase *
b is: class CBase *
*a is: class CBase
*b is: class CDerived
Notice how the type that typeid considers for pointers is the pointer type itself (both a and b are of type class CBase *). However, when typeid is applied to objects (like *a and *b) typeid yields their dynamic type (i.e. the type of their most derived complete object).
If the type typeid evaluates is a pointer preceded by the dereference operator (*), and this pointer has a null value, typeid throws a bad_typeid exception.
Last update on Jan 26, 2007 at 2:47am
Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast:
Implicit conversion
Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:
short a=2000;
int b;
b=a;
Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.
Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. For example:
class A {};
class B { public: B (A a) {} };
A a;
B b=a;
Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed.
Explicit conversion
C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:
short a=2000;
int b;
b = (int) a; // c-like cast notation
b = int (a); // functional notation
The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors. For example, the following code is syntactically correct:
// class type-casting
#include
using namespace std;
class CDummy {
float i,j;
};
class CAddition {
int x,y;
public:
CAddition (int a, int b) { x=a; y=b; }
int result() { return x+y;}
};
int main () {
CDummy d;
CAddition * padd;
padd = (CAddition*) &d;
cout << padd->result();
return 0;
}
The program declares a pointer to CAddition, but then it assigns to it a reference to an object of another incompatible type using explicit type-casting:
padd = (CAddition*) &d;
Traditional explicit type-casting allows to convert any pointer into any other pointer type, independently of the types they point to. The subsequent call to member result will produce either a run-time error or a unexpected result.
In order to control these types of conversions between classes, we have four specific casting operators: dynamic_cast, reinterpret_cast, static_cast and const_cast. Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses.
dynamic_cast
reinterpret_cast
static_cast
const_cast
The traditional type-casting equivalents to these expressions would be:
(new_type) expression
new_type (expression)
but each one with its own special characteristics:
dynamic_cast
dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.
Therefore, dynamic_cast is always successful when we cast a class to one of its base classes:
class CBase { };
class CDerived: public CBase { };
CBase b; CBase* pb;
CDerived d; CDerived* pd;
pb = dynamic_cast
pd = dynamic_cast
The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with dynamic_cast unless the base class is polymorphic.
When a class is polymorphic, dynamic_cast performs a special checking during runtime to ensure that the expression yields a valid complete object of the requested class:
// dynamic_cast
#include
#include
using namespace std;
class CBase { virtual void dummy() {} };
class CDerived: public CBase { int a; };
int main () {
try {
CBase * pba = new CDerived;
CBase * pbb = new CBase;
CDerived * pd;
pd = dynamic_cast
if (pd==0) cout << "Null pointer on first type-cast" << endl;
pd = dynamic_cast
if (pd==0) cout << "Null pointer on second type-cast" << endl;
} catch (exception& e) {cout << "Exception: " << e.what();}
return 0;
}
Null pointer on second type-cast
Compatibility note: dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. This must be enabled for runtime type checking using dynamic_cast to work properly.
The code tries to perform two dynamic casts from pointer objects of type CBase* (pba and pbb) to a pointer object of type CDerived*, but only the first one is successful. Notice their respective initializations:
CBase * pba = new CDerived;
CBase * pbb = new CBase;
Even though both are pointers of type CBase*, pba points to an object of type CDerived, while pbb points to an object of type CBase. Thus, when their respective type-castings are performed using dynamic_cast, pba is pointing to a full object of class CDerived, whereas pbb is pointing to an object of class CBase, which is an incomplete object of class CDerived.
When dynamic_cast cannot cast a pointer because it is not a complete object of the required class -as in the second conversion in the previous example- it returns a null pointer to indicate the failure. If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_alloc is thrown instead.
dynamic_cast can also cast null pointers even between pointers to unrelated classes, and can also cast pointers of any type to void pointers (void*).
static_cast
static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided.
class CBase {};
class CDerived: public CBase {};
CBase * a = new CBase;
CDerived * b = static_cast
This would be valid, although b would point to an incomplete object of the class and could lead to runtime errors if dereferenced.
static_cast can also be used to perform any other non-pointer conversion that could also be performed implicitly, like for example standard conversion between fundamental types:
double d=3.14159265;
int i = static_cast
Or any conversion between classes with explicit constructors or operator functions as described in "implicit conversions" above.
reinterpret_cast
reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.
It can also cast pointers to or from integer types. The format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it, is granted to be able to be cast back to a valid pointer.
The conversions that can be performed by reinterpret_cast but not by static_cast have no specific uses in C++ are low-level operations, whose interpretation results in code which is generally system-specific, and thus non-portable. For example:
class A {};
class B {};
A * a = new A;
B * b = reinterpret_cast(a);
This is valid C++ code, although it does not make much sense, since now we have a pointer that points to an object of an incompatible class, and thus dereferencing it is unsafe.
const_cast
This type of casting manipulates the constness of an object, either to be set or to be removed. For example, in order to pass a const argument to a function that expects a non-constant parameter:
// const_cast
#include
using namespace std;
void print (char * str)
{
cout << str << endl;
}
int main () {
const char * c = "sample text";
print ( const_cast
return 0;
}
sample text
typeid
typeid allows to check the type of an expression:
typeid (expression)
This operator returns a reference to a constant object of type type_info that is defined in the standard header file
// typeid
#include
#include
using namespace std;
int main () {
int * a,b;
a=0; b=0;
if (typeid(a) != typeid(b))
{
cout << "a and b are of different types:\n";
cout << "a is: " << typeid(a).name() << '\n';
cout << "b is: " << typeid(b).name() << '\n';
}
return 0;
}
a and b are of different types:
a is: int *
b is: int
When typeid is applied to classes typeid uses the RTTI to keep track of the type of dynamic objects. When typeid is applied to an expression whose type is a polymorphic class, the result is the type of the most derived complete object:
// typeid, polymorphic class
#include
#include
#include
using namespace std;
class CBase { virtual void f(){} };
class CDerived : public CBase {};
int main () {
try {
CBase* a = new CBase;
CBase* b = new CDerived;
cout << "a is: " << typeid(a).name() << '\n';
cout << "b is: " << typeid(b).name() << '\n';
cout << "*a is: " << typeid(*a).name() << '\n';
cout << "*b is: " << typeid(*b).name() << '\n';
} catch (exception& e) { cout << "Exception: " << e.what() << endl; }
return 0;
}
a is: class CBase *
b is: class CBase *
*a is: class CBase
*b is: class CDerived
Notice how the type that typeid considers for pointers is the pointer type itself (both a and b are of type class CBase *). However, when typeid is applied to objects (like *a and *b) typeid yields their dynamic type (i.e. the type of their most derived complete object).
If the type typeid evaluates is a pointer preceded by the dereference operator (*), and this pointer has a null value, typeid throws a bad_typeid exception.
维州理工大学枪击案 死亡者已经达32人
据美国之音报导,美国维州理工大学校园枪击案死亡人数上升到32人,28人受伤。这是几十年来伤亡人数最多的校园枪击案。
受伤者当中的一些人伤势严重。丧生者中包括一些在教室里被打死的学生。据报导,枪手本人也已经死亡。
枪击先后发生在维州理工大学的一个学生宿舍和一座教学楼。维州理工大学的校长斯蒂格说,整个校园对这起惨剧感到震惊。他说,枪击是”丧失理性、不可饶恕“的行为。斯蒂格说,维州理工大学星期一和星期二将停课两天,并向受到惊吓的学生提供心理咨询服务。
警察已经封锁了维州理工大学的校园数小时,搜索可能存在的另一个枪手。这座大学的网站告诚学生待在室内,将房门锁上。
维州理工大学是州立大学,位于维州西南角,距离华盛顿386公里,有2万6千名学生。
尚未排除中国学生伤亡
BLACKSBURG, Va. — At least 32 people are confirmed dead and at least another 21 are wounded after a shooting at Virginia Tech University Monday morning, federal law enforcement officials told FOX News.
Campus police said there was only one shooter and he is now dead. They are unsure if the shooter was a student and it was unclear if he was shot by police or took his own life.
"The university was struck today with a tragedy of monumental proportions," Virginia Tech President Charles Steger said during a press conference shortly after noon. "The university is shocked and horrified that this would befall our campus ... I cannot begin to convey my own personal sense of loss over this senselessness of such an incomprehensible and heinous act."
It was the deadliest campus shooting in U.S. history.
Steger said school officials are notifying victims' next of kin, and state police and the FBI are still investigating the various crime scenes. They are still trying to identify all the victims. The university will set up counseling centers for students and faculty.
April 16: Injured occupants are carried out of Norris Hall at Virginia Tech in Blacksburg, Va., after shootings resulted in multiple fatalities.
April 16: An unidentified man is restrained during a manhunt on the Virginia Tech campus in Blacksburg, Va., following shootings that left around 20 people dead
April 16: Law enforcement officials carry an unidentified person out of Norris Hall at Virginia Tech in Blacksburg, Va., following a shooting spree on campus.
受伤者当中的一些人伤势严重。丧生者中包括一些在教室里被打死的学生。据报导,枪手本人也已经死亡。
枪击先后发生在维州理工大学的一个学生宿舍和一座教学楼。维州理工大学的校长斯蒂格说,整个校园对这起惨剧感到震惊。他说,枪击是”丧失理性、不可饶恕“的行为。斯蒂格说,维州理工大学星期一和星期二将停课两天,并向受到惊吓的学生提供心理咨询服务。
警察已经封锁了维州理工大学的校园数小时,搜索可能存在的另一个枪手。这座大学的网站告诚学生待在室内,将房门锁上。
维州理工大学是州立大学,位于维州西南角,距离华盛顿386公里,有2万6千名学生。
尚未排除中国学生伤亡
BLACKSBURG, Va. — At least 32 people are confirmed dead and at least another 21 are wounded after a shooting at Virginia Tech University Monday morning, federal law enforcement officials told FOX News.
Campus police said there was only one shooter and he is now dead. They are unsure if the shooter was a student and it was unclear if he was shot by police or took his own life.
"The university was struck today with a tragedy of monumental proportions," Virginia Tech President Charles Steger said during a press conference shortly after noon. "The university is shocked and horrified that this would befall our campus ... I cannot begin to convey my own personal sense of loss over this senselessness of such an incomprehensible and heinous act."
It was the deadliest campus shooting in U.S. history.
Steger said school officials are notifying victims' next of kin, and state police and the FBI are still investigating the various crime scenes. They are still trying to identify all the victims. The university will set up counseling centers for students and faculty.
April 16: Injured occupants are carried out of Norris Hall at Virginia Tech in Blacksburg, Va., after shootings resulted in multiple fatalities.
April 16: An unidentified man is restrained during a manhunt on the Virginia Tech campus in Blacksburg, Va., following shootings that left around 20 people dead
April 16: Law enforcement officials carry an unidentified person out of Norris Hall at Virginia Tech in Blacksburg, Va., following a shooting spree on campus.
Subscribe to:
Posts (Atom)