预防xml注入漏洞攻击

by Kurt

由库尔特

(Sherlock Holmes would have been a brilliant programmer)

(Bugs are inevitable.)

It is quite normal to spend more time debugging than you spend writing actual code. If you are learning to program and you absolutely hate debugging your own code, stop now.

与编写实际代码相比,花更多的时间进行调试是很正常的。 如果您正在学习编程,并且绝对不喜欢调试自己的代码,请立即停止 。

Find a new hobby or trade that you enjoy. Otherwise, you will soon discover the true definition of insanity: debugging another programmer’s legacy code, wondering what on earth they were thinking.

寻找您喜欢的新爱好或行业。 否则,您很快就会发现疯狂的真正定义:调试另一个程序员的遗留代码,想知道他们到底在想什么。

Alternatively, you could simply change your mindset and stop hating bugs.

或者,您可以简单地改变思维方式并停止讨厌的错误。

(Here are some of the reasons why I enjoy debugging…)
  1. It’s a challenge. To me, a bug is a puzzle to solve. I love puzzles, so it’s like the app is giving me an hour to play Sudoku. 这是一个挑战 。 对我来说,错误是一个难题。 我喜欢拼图,所以好像该应用程序给了我一个小时玩Sudoku。
  2. It makes me a better programmer. Debugging code is undeniably one of the best methods of learning. 它使我成为一个更好的程序员 。 无疑,调试代码是最好的学习方法之一。
  3. Sometimes it makes me laugh. To be a programmer, you need to have a good sense of humor. You also need to be able to laugh your own stupidity, or the humor of the situation. 有时它使我发笑 。 要成为一名程序员,您需要具有良好的幽默感。 您还需要能够嘲笑自己的愚蠢或情况的幽默。
  4. It is the best insight I can get into my users’ thoughts. Beyond your initial tests, you should never test your own applications — nor should another programmer. This is because you will never break your app the way your users will. The best tester I ever had was my boss’s 5-year-old son, who tested all of our iPad apps. If he couldn’t use the app, our users wouldn’t be able to either. The question when debugging doesn’t end at “How did the user do it?” but also expands to “Why did the user do it?” 这是我可以深入了解用户思想的最佳见解 。 除了最初的测试之外, 您永远不要测试自己的应用程序-也不应该再测试另一个程序员。 这是因为您将永远不会像用户那样破坏应用程序。 我曾经遇到过的最好的测试器是我老板的5岁儿子,他测试了我们所有的iPad应用程序。 如果他无法使用该应用程序,那么我们的用户也将无法使用。 调试时的问题不止于“用户是如何做到的?” 而且还会扩展为“用户为什么这样做?”

I found this pie chart on the ProgrammerHumor subreddit that perfectly sums up my average day:

我在ProgrammerHumor subreddit上找到了这个饼图,它完美地总结了我的平均一天:

Note that the majority of time is spent implementing safeguards. This is the definition of preventative programming.

请注意,大部分时间都花在了实施保障措施上。 这就是预防性编程的定义。

If your graph is the same, great. Maybe we can exchange tips. But if you’re probably like most of us, and spend the majority of you time wondering what the hell your user did to make a fixed variable undefined or turn a string into an integer.

如果您的图形相同,那就太好了。 也许我们可以交换技巧。 但是,如果您可能像我们大多数人一样,并花大量时间在想知道您的用户做了什么,使固定变量未定义或将字符串转换为整数。

Then this post may be particularly helpful to you.

然后,该帖子可能对您特别有帮助。

(Why Sherlock Holmes would have been an excellent programmer)

The first Sherlock Holmes book was written way back in 1887, long before computers were invented. All of these books are packed full of lessons that you can apply to programming.

第一本《福尔摩斯》(Sherlock Holmes)书是在1887年发明的,当时计算机发明还很早。 所有这些书都挤满了可以应用于编程的课程。

If this comes as a surprise to you, remember that data has existed as long as the written word has, and that the reason computers where invented was to handle data.

如果让您感到惊讶,请记住,只要文字就存在数据,并且发明计算机的原因是要处理数据。

Sherlock Holmes is most famous for using his “method of deduction”:

福尔摩斯(Sherlock Holmes)因使用“演绎法”而闻名:

When you have eliminated the impossible, whatever remains, however improbable, must be the truth. — Sherlock Holmes in The Sign of Four

当您消除了不可能的事情之后,无论多么不可能的事情,剩下的都是事实。 — 四个星座的福尔摩斯

If I had to apply this thinking to a function it would be something like…

如果我必须将此思想应用于某个功能,它将类似于……

When you have prevented everything a function shouldn’t do, it can only do what it should.

当您阻止了某个函数不应该做的所有事情时,它只能做应该做的事情。

Let’s dive into some simple habits that can help you save countless hours of debugging by applying this theory.

让我们潜入一些简单的习惯,这些习惯可以通过应用这种理论来帮助您节省大量的调试时间。

(How fix to bugs before they happen)

Take a look at the below function that searches an array and returns the value if found either as is or as the result of a callback function:

看一下下面的函数,该函数搜索数组并返回值(如果按原样或作为 回调函数的结果找到) :

function arraySearch(value, array, callback) {  callback = callback || false;  for (var i = 0; i < array.length; i++) {    if (array[i] == value) {      if (callback) {        return callback(value);      } else {        return value;      }    }  }}var result = arraySearch(4,[1,2,3,4],function(val){return val+val;});

At first glance it seems perfectly fine.

乍看之下似乎还不错。

But let’s take a step back and use a preventative approach and focus instead on what the function shouldn’t do.

但是,让我们退后一步,使用一种预防性方法 ,重点关注该函数不应该执行的操作 。

在本练习中,我们要解决四个问题 (There are four points that we want to address in this exercise)
  1. It shouldn’t break easily. If at all possible we want to prevent it from stopping on error. Instead it should return. 它不应该轻易破裂 。 如果可能的话,我们要防止它因错误而停止。 相反,它应该返回 。

2. It should never return undefined. We want it to return false instead.

2. 永远不要返回undefined 。 我们希望它返回false 。

3. It must never make implicit or “loose” match.

3. 绝不能进行隐式或“松散”匹配 。

4. When we must throw an error it should not be a generic error. We want something readable for both ourselves and the poor programmer who needs to work on this code after us.

4. 当我们必须抛出错误时,它不应是一般性错误 。 我们想要我们自己和需要在我们之后处理此代码的可怜的程序员都可读的东西。

(Getting Started)

Point 1 seems like it’s asking a lot but in essence we just want it to fail gracefully and return a predictable value like false instead of stopping the bus.

点1似乎要求很高,但从本质上讲,我们只希望它正常运行并返回诸如false 的可预测值,而不是停止总线。

First off, it absolutely must have an inputted value and array to run. So lets modify the function with this in mind.

首先,它绝对必须具有输入值和数组才能运行。 因此,请牢记这一点来修改功能。

function arraySearch(value, array, callback) {  if (value === undefined || array === undefined) {    return false;  }  callback = callback || false;  for (var i = 0; i < array.length; i++) {    if (array[i] == value) {      if (callback) {        return callback(value);      }      else {        return value;      }    }  }}

Great, that’s sorted. By checking if the arguments are undefined we are ensuring that values have been passed to them.

很好,已排序。 通过检查参数是否未定义 我们正在确保价值观已经传递给他们。

Our callback already has a default value, so that is taken care of. But what if our array is not an array? Or in the same breath what if our callback is not a function?

我们的回调已经具有默认值,因此可以解决。 但是,如果我们的数组不是数组怎么办? 或者如果我们的回调不是函数怎么办?

Let’s take care of this next…

接下来,让我们照顾一下……

function arraySearch(value, array, callback) {  if (value === undefined || array === undefined || (array instanceof Array) === false) {    return false;  }  callback = callback || false;  if (callback !== false && typeof callback !== 'function') {    throw 'Callback to arraySearch is not a function';    return false;  }  for (var i = 0; i < array.length; i++) {    if (array[i] == value) {      if (callback) {        return callback(value);      }      else {        return value;      }    }  }}

Awesome. Now by checking the typeof the callback we are sure that the callback is a valid function and by checking that the array is an instanceof the Array object we are also sure that the array is an Array.

太棒了 现在通过检查的typeof 回调 ,我们相信,回调是一个有效的功能 ,并通过检查阵列是的instanceof 对于Array对象,我们还可以确定该数组是Array 。

So let’s move onto point 2 — “It should never return undefined”.

因此,让我们进入第2点- “它永远不会返回undefined” 。

Well for starters our function does not have a default return value for when there is no match. Equally important, is the fact that we have no way of knowing what the callback function will return.

对于初学者来说,当没有匹配项时,我们的函数没有默认的返回值 。 同样重要的是,我们没有办法知道回调函数将返回什么。

We can fix this by making the function return a variable so that we only need to check if it is undefined or null once.

我们可以通过使函数返回变量来解决此问题,从而只需要检查一次它是否未定义或为null 。

function arraySearch(value, array, callback) {  if (value === undefined || array === undefined || (array instanceof Array) === false) {    return false;  }  callback = callback || false;  var result = null;  if (callback !== false && typeof callback !== 'function') {    throw 'Callback to arraySearch is not a function';    return false;  }  for (var i = 0; i < array.length; i++) {    if (array[i] == value) {      if (callback) {        result = callback(value);      }      else {        result = value;      }    }  }  return result || false;}

Sorted. Setting the value of result to either the match or to the result of the callback function allows us to return either the result or false, should the result be undefined or null.

排序。 将result的值设置为match或callback函数的result可以使我们返回result或false,如果结果是undefined或null 。

Point 3. An implicit or loose match can be described as being relatively equal i.e. false == 0 or ‘4’ == 4 etc.

点3。 隐式或松散匹配可以描述为相对相等,即false == 0或'4'== 4等。

We want to avoid this. What if we are searching for false in an Array containing Zero?

我们要避免这种情况。 如果我们在包含零的数组中搜索false怎么办?

We can fix this by changing the below line:

我们可以通过更改以下行来解决此问题:

if (array[i] == value) {//must change to  if (array[i] === value) {

“===” means exactly equal to. Always do an explicit match when checking values. This habit will save you countless hours of time in the long run because you won’t be trying to debug statement that is evaluating as true.

“ === ”表示完全等于 。 检查值时,请务必进行明确匹配。 从长远来看,这种习惯将节省您无数小时的时间,因为您不会尝试调试评估为true的语句 。

Now for the last point.

现在最后一点。

When throwing an error we want it to be friendly. This functionality is already demonstrated when passing an invalid callback function, but what if a valid callback function throws an error?

抛出错误时,我们希望它是友好的。 传递无效的回调函数时已经演示了此功能,但是如果有效的回调函数引发错误怎么办?

Anonymous functions can be a pain to debug, so let’s try and make debugging a little less painful:

匿名函数调试起来很麻烦,所以让我们尝试减少调试的麻烦:

function arraySearch(value, array, callback) {  if (value === undefined || array === undefined || (array instanceof Array) === false) {    return false;  }  callback = callback || false;  var result = null;  if (callback !== false && typeof callback !== 'function') {    throw 'Callback to arraySearch is not a function';    return false;  }  for (var i = 0; i < array.length; i++) {    if (array[i] === value) {      if (callback) {        try{          result = callback(value);        }catch(e){          throw 'Callback function in arraySearch threw the error : '+e.message;        }      }      else {        result = value;      }    }  }  return result || false;}

There we have it.

那里有。

To solve the issue we use a simple try / catch statement and then re-throw the error with a custom message. Now if a callback function fails we will immediately know that it was the callback function that failed and not our arraySearch function.

为了解决这个问题,我们使用了一个简单的try / catch语句,然后使用自定义消息 重新抛出该错误 。 现在,如果回调函数失败,我们将立即知道失败的是回调函数 ,而不是我们的arraySearch函数。

(Summary)

All in all, we now have a function that should give us minimal hassles in the future. And if it does have an issue, it should be fast and easy to correct.

总而言之,我们现在拥有的功能应在将来给我们带来最小的麻烦。 如果确实有问题,则应该快速且容易地纠正。

The basics of my tips on preventative programming can be summed up in 6 points…

我关于预防性编程的技巧的基础可以归纳为6点…

  1. Check that your input values exist and set default values where necessary. 检查您的输入值是否存在,并在必要时设置默认值。
  2. Always make sure your input is of the same type as you are looking for. Never assume that an Array will be an Array or that an Integer will be an Integer. 始终确保输入的内容与您要查找的相同 。 永远不要假设Array将是Array或Integer将是Integer 。
  3. Always do an explicit match when comparing values (===). 比较值( === )时,请始终进行显式匹配 。
  4. Write functions that return predictable values i.e. return false when failed or false or return the expected result when true. 失败或假或真时返回预期的结果时返回预测的值写入功能 ,即返回FALSE。
  5. Try to write pure functions. A pure function is a function that always returns an expected value, and does not modify the original variables passed to it in any way. 尝试编写纯函数 。 纯函数是始终返回期望值,并且不会以任何方式修改传递给它的原始变量的函数。
  6. Throw custom errors where needed especially when executing callbacks and anonymous functions. You won’t remember exactly what your code does in 8 month’s time, so do yourself a favor and throw a clear error message while you still know what your code does. 在需要时 抛出 自定义错误,尤其是在执行回调和匿名函数时 。 您将不会完全记得您的代码在8个月的时间内所执行的操作,因此请帮自己一个忙,并在您仍然知道自己的代码执行情况的同时发出清晰的错误消息。

(I’ll leave you with some great quotes from Sherlock Holmes)

(Moral : Do not make assumptions before collecting data)

It is a capital mistake to theorize before you have all the evidence. It biases the judgment. — A Study in Scarlet

在获得所有证据之前先进行理论分析是一个重大错误。 它使判断有偏差。 - 血字的研究

It is a capital mistake to theorize before one has data. Insensibly one begins to twist facts to suit theories, instead of theories to suit facts. -A Scandal in Bohemia

在获得数据之前先进行理论分析是一个重大错误。 荒谬的是,人们开始扭曲事实以适合理论,而不是理论以适合事实。 -波西米亚的丑闻

Still, it is an error to argue in front of your data. You can find yourself insensibly twisting them round to suit your theories. -The Adventure of Wisteria Lodge

尽管如此,在数据面前争论仍然是一个错误。 您会发现自己无所适从地将它们扭曲成适合您的理论。 -紫藤小屋历险记

Let me run over the principal steps. We approached the case, you remember, with an absolutely blank mind, which is always an advantage. We had formed no theories. We were simply there to observe and to draw inferences from our observations. -The Adventure of the Cardboard Box

让我回顾一下主要步骤。 您记得,我们以绝对空白的态度处理此案,这始终是一个优势。 我们没有形成任何理论。 我们只是在那里观察并从我们的观察中得出推论。 -纸箱历险记

“Data! Data! Data!” he cried impatiently. “I can’t make bricks without clay. -The Adventure of the Copper Beeches

“数据! 数据! 数据!” 他不耐烦地哭了。 “如果没有粘土,我无法制造砖头。 -铜山毛榉历险记

(Moral : Don’t let your emotions override logic)

Detection is, or ought to be, an exact science, and should be treated in the same cold and unemotional manner.-The Sign of Four

检测是或应该是一门精确的科学,应该以同样冷淡和无情的方式对待。-四个星座

The emotional qualities are antagonistic to clear reasoning. -The Sign of Four

情感特质与明确的推理背道而驰。 -四个的标志

(Moral : Focus on core feature’s and use-cases)

It is of the highest importance in the art of detection to be able to recognize, out of a number of facts, which are incidental and which vital. Otherwise your energy and attention must be dissipated instead of being concentrated. -The Reigate Puzzle

在检测领域中,最重要的是能够从许多事实中识别出偶然的和至关重要的事实。 否则,您的精力和注意力必须消散而不是集中精力。 -拼图难题

(And a few more that you can take your own lesson from)

Nothing clears up a case so much as stating it to another person. -Silver Blaze

没有什么比将案件说给他人更能清除案件了。 -银色烈焰

I have already explained to you that what is out of the common is usually a guide rather” than a hindrance. -A Study in Scarlet

我已经向您解释了,与众不同之处通常是指导而不是障碍。 -血字的研究

‘The more outre’ and grotesque an incident is the more carefully it deserves to be examined, and the very point which appears to complicate a case is, when duly considered and scientifically handled, the one which is most likely to elucidate it. -The Hound of the Baskervilles

“越是荒唐”和怪诞的事件,就越应予以仔细检查,而如果经过适当考虑和科学处理,似乎使案件复杂化的一点就是最有可能阐明这一事件的地方。 -巴斯克维尔的猎犬

Any truth is better than indefinite doubt. -The Yellow Face

任何真理都比不确定性强。 -黄脸

I never guess. It is a shocking habit — destructive to the logical faculty -The Sign of Four

我没猜到 这是一个令人震惊的习惯-破坏了逻辑能力-四个星座

That’s all I have for this post. If you enjoyed reading it and would like to read another technical post take a look at:

这就是我所拥有的全部内容。 如果您喜欢阅读它,并且想阅读其他技术文章,请查看:

How to write a jQuery like library in 71 lines of code — Learn about the DOMJavaScript frameworks are all the rage. Chances are that any JavaScript related news feed you open will be littered…medium.com

如何用71行代码编写类似jQuery的库—了解有关DOM JavaScript框架的所有信息。 您打开的任何与JavaScript相关的新闻提要都有可能会乱丢垃圾… medium.com

Alternatively if the code hurt your brain and made you tired here’s some non-technical posts that I’ve written…

另外,如果代码伤了您的大脑并使您感到疲倦,这是我写的一些非技术性的帖子……

5 Things to Remember When You’re Learning to ProgramLearning to program is challenging. Aside from choosing a language or setting up a development environment that you…medium.comTurning code to cash — How to make money as a Web Developer and live to tell the tale.So you just learnt to code. You’re eager and anyone who can’t code thinks you’re a genius, word gets out and all of a…medium.comHow I Became a Programmer. And When I Started Calling Myself OneI’ve wanted to start blogging about programming for months now and like so many others before me I set off full of…medium.comMaking it rain code — Matrix StyleAn introduction to HTML 5 canvas animationsmedium.com

学习编程时要记住的5件事 学习编程是一项挑战。 除了选择一种语言或建立一个开发环境外,您还可以… medium.com 将代码转换为现金-如何以Web开发人员的身份赚钱并活在故事中。 因此,您刚刚学习编码。 您很热衷,任何无法编写代码的人都认为您是个天才,无言以对,一切都... medium.com 我如何成为一名程序员。 而当我开始称自己为一个 我想开始写博客之前,我现在和很多人一样编程的几个月里,我掀起全... medium.com 的 让降雨码-矩阵式 的介绍HTML 5画布动画中.com

翻译自: https://www.freecodecamp.org/news/preventative-programming-how-fix-to-bugs-before-they-happen-9df82cf215c5/

预防xml注入漏洞攻击