acme.sh 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166
  1. #!/usr/bin/env sh
  2. VER=2.6.1
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_INSTALL_HOME="$HOME/.$PROJECT_NAME"
  7. _SCRIPT_="$0"
  8. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  9. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"
  10. DEFAULT_USER_AGENT="$PROJECT_ENTRY client v$VER : $PROJECT"
  11. DEFAULT_ACCOUNT_EMAIL=""
  12. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  13. VTYPE_HTTP="http-01"
  14. VTYPE_DNS="dns-01"
  15. VTYPE_TLS="tls-sni-01"
  16. VTYPE_TLS2="tls-sni-02"
  17. LOCAL_ANY_ADDRESS="0.0.0.0"
  18. MAX_RENEW=60
  19. DEFAULT_DNS_SLEEP=120
  20. NO_VALUE="no"
  21. W_TLS="tls"
  22. STATE_VERIFIED="verified_ok"
  23. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  24. END_CSR="-----END CERTIFICATE REQUEST-----"
  25. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  26. END_CERT="-----END CERTIFICATE-----"
  27. RENEW_SKIP=2
  28. ECC_SEP="_"
  29. ECC_SUFFIX="${ECC_SEP}ecc"
  30. LOG_LEVEL_1=1
  31. LOG_LEVEL_2=2
  32. LOG_LEVEL_3=3
  33. DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
  34. _DEBUG_WIKI="https://github.com/Neilpang/acme.sh/wiki/How-to-debug-acme.sh"
  35. __INTERACTIVE=""
  36. if [ -t 1 ] ; then
  37. __INTERACTIVE="1"
  38. fi
  39. __green() {
  40. if [ "$__INTERACTIVE" ] ; then
  41. printf '\033[1;31;32m'
  42. fi
  43. printf -- "$1"
  44. if [ "$__INTERACTIVE" ] ; then
  45. printf '\033[0m'
  46. fi
  47. }
  48. __red() {
  49. if [ "$__INTERACTIVE" ] ; then
  50. printf '\033[1;31;40m'
  51. fi
  52. printf -- "$1"
  53. if [ "$__INTERACTIVE" ] ; then
  54. printf '\033[0m'
  55. fi
  56. }
  57. _printargs() {
  58. if [ -z "$2" ] ; then
  59. printf -- "[$(date)] $1"
  60. else
  61. printf -- "[$(date)] $1='$2'"
  62. fi
  63. printf "\n"
  64. }
  65. _log() {
  66. [ -z "$LOG_FILE" ] && return
  67. _printargs "$@" >> $LOG_FILE
  68. }
  69. _info() {
  70. _log "$@"
  71. _printargs "$@"
  72. }
  73. _err() {
  74. _log "$@"
  75. printf -- "[$(date)] " >&2
  76. if [ -z "$2" ] ; then
  77. __red "$1" >&2
  78. else
  79. __red "$1='$2'" >&2
  80. fi
  81. printf "\n" >&2
  82. return 1
  83. }
  84. _usage() {
  85. __red "$@" >&2
  86. printf "\n" >&2
  87. }
  88. _debug() {
  89. if [ -z "$LOG_LEVEL" ] || [ "$LOG_LEVEL" -ge "$LOG_LEVEL_1" ] ; then
  90. _log "$@"
  91. fi
  92. if [ -z "$DEBUG" ] ; then
  93. return
  94. fi
  95. _printargs "$@" >&2
  96. }
  97. _debug2() {
  98. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_2" ] ; then
  99. _log "$@"
  100. fi
  101. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  102. _debug "$@"
  103. fi
  104. }
  105. _debug3() {
  106. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_3" ] ; then
  107. _log "$@"
  108. fi
  109. if [ "$DEBUG" ] && [ "$DEBUG" -ge "3" ] ; then
  110. _debug "$@"
  111. fi
  112. }
  113. _startswith(){
  114. _str="$1"
  115. _sub="$2"
  116. echo "$_str" | grep "^$_sub" >/dev/null 2>&1
  117. }
  118. _endswith(){
  119. _str="$1"
  120. _sub="$2"
  121. echo "$_str" | grep -- "$_sub\$" >/dev/null 2>&1
  122. }
  123. _contains(){
  124. _str="$1"
  125. _sub="$2"
  126. echo "$_str" | grep -- "$_sub" >/dev/null 2>&1
  127. }
  128. _hasfield() {
  129. _str="$1"
  130. _field="$2"
  131. _sep="$3"
  132. if [ -z "$_field" ] ; then
  133. _usage "Usage: str field [sep]"
  134. return 1
  135. fi
  136. if [ -z "$_sep" ] ; then
  137. _sep=","
  138. fi
  139. for f in $(echo "$_str" | tr ',' ' ') ; do
  140. if [ "$f" = "$_field" ] ; then
  141. _debug2 "'$_str' contains '$_field'"
  142. return 0 #contains ok
  143. fi
  144. done
  145. _debug2 "'$_str' does not contain '$_field'"
  146. return 1 #not contains
  147. }
  148. _getfield(){
  149. _str="$1"
  150. _findex="$2"
  151. _sep="$3"
  152. if [ -z "$_findex" ] ; then
  153. _usage "Usage: str field [sep]"
  154. return 1
  155. fi
  156. if [ -z "$_sep" ] ; then
  157. _sep=","
  158. fi
  159. _ffi=$_findex
  160. while [ "$_ffi" -gt "0" ]
  161. do
  162. _fv="$(echo "$_str" | cut -d $_sep -f $_ffi)"
  163. if [ "$_fv" ] ; then
  164. printf -- "%s" "$_fv"
  165. return 0
  166. fi
  167. _ffi="$(_math $_ffi - 1)"
  168. done
  169. printf -- "%s" "$_str"
  170. }
  171. _exists(){
  172. cmd="$1"
  173. if [ -z "$cmd" ] ; then
  174. _usage "Usage: _exists cmd"
  175. return 1
  176. fi
  177. if type command >/dev/null 2>&1 ; then
  178. command -v "$cmd" >/dev/null 2>&1
  179. else
  180. type "$cmd" >/dev/null 2>&1
  181. fi
  182. ret="$?"
  183. _debug3 "$cmd exists=$ret"
  184. return $ret
  185. }
  186. #a + b
  187. _math(){
  188. expr "$@"
  189. }
  190. _h_char_2_dec() {
  191. _ch=$1
  192. case "${_ch}" in
  193. a|A)
  194. printf "10"
  195. ;;
  196. b|B)
  197. printf "11"
  198. ;;
  199. c|C)
  200. printf "12"
  201. ;;
  202. d|D)
  203. printf "13"
  204. ;;
  205. e|E)
  206. printf "14"
  207. ;;
  208. f|F)
  209. printf "15"
  210. ;;
  211. *)
  212. printf "%s" "$_ch"
  213. ;;
  214. esac
  215. }
  216. _URGLY_PRINTF=""
  217. if [ "$(printf '\x41')" != 'A' ] ; then
  218. _URGLY_PRINTF=1
  219. fi
  220. _h2b() {
  221. hex=$(cat)
  222. i=1
  223. j=2
  224. if _exists let ; then
  225. uselet="1"
  226. fi
  227. _debug3 uselet "$uselet"
  228. _debug3 _URGLY_PRINTF "$_URGLY_PRINTF"
  229. while true ; do
  230. if [ -z "$_URGLY_PRINTF" ] ; then
  231. h="$(printf $hex | cut -c $i-$j)"
  232. if [ -z "$h" ] ; then
  233. break;
  234. fi
  235. printf "\x$h"
  236. else
  237. ic="$(printf $hex | cut -c $i)"
  238. jc="$(printf $hex | cut -c $j)"
  239. if [ -z "$ic$jc" ] ; then
  240. break;
  241. fi
  242. ic="$(_h_char_2_dec "$ic")"
  243. jc="$(_h_char_2_dec "$jc")"
  244. printf '\'"$(printf %o "$(_math $ic \* 16 + $jc)")"
  245. fi
  246. if [ "$uselet" ] ; then
  247. let "i+=2" >/dev/null
  248. let "j+=2" >/dev/null
  249. else
  250. i="$(_math $i + 2)"
  251. j="$(_math $j + 2)"
  252. fi
  253. done
  254. }
  255. #options file
  256. _sed_i() {
  257. options="$1"
  258. filename="$2"
  259. if [ -z "$filename" ] ; then
  260. _usage "Usage:_sed_i options filename"
  261. return 1
  262. fi
  263. _debug2 options "$options"
  264. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  265. _debug "Using sed -i"
  266. sed -i "$options" "$filename"
  267. else
  268. _debug "No -i support in sed"
  269. text="$(cat "$filename")"
  270. echo "$text" | sed "$options" > "$filename"
  271. fi
  272. }
  273. _egrep_o() {
  274. if _contains "$(egrep -o 2>&1)" "egrep: illegal option -- o" ; then
  275. sed -n 's/.*\('"$1"'\).*/\1/p'
  276. else
  277. egrep -o "$1"
  278. fi
  279. }
  280. #Usage: file startline endline
  281. _getfile() {
  282. filename="$1"
  283. startline="$2"
  284. endline="$3"
  285. if [ -z "$endline" ] ; then
  286. _usage "Usage: file startline endline"
  287. return 1
  288. fi
  289. i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
  290. if [ -z "$i" ] ; then
  291. _err "Can not find start line: $startline"
  292. return 1
  293. fi
  294. i="$(_math "$i" + 1)"
  295. _debug i "$i"
  296. j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
  297. if [ -z "$j" ] ; then
  298. _err "Can not find end line: $endline"
  299. return 1
  300. fi
  301. j="$(_math "$j" - 1)"
  302. _debug j "$j"
  303. sed -n "$i,${j}p" "$filename"
  304. }
  305. #Usage: multiline
  306. _base64() {
  307. if [ "$1" ] ; then
  308. openssl base64 -e
  309. else
  310. openssl base64 -e | tr -d '\r\n'
  311. fi
  312. }
  313. #Usage: multiline
  314. _dbase64() {
  315. if [ "$1" ] ; then
  316. openssl base64 -d -A
  317. else
  318. openssl base64 -d
  319. fi
  320. }
  321. #Usage: hashalg [outputhex]
  322. #Output Base64-encoded digest
  323. _digest() {
  324. alg="$1"
  325. if [ -z "$alg" ] ; then
  326. _usage "Usage: _digest hashalg"
  327. return 1
  328. fi
  329. outputhex="$2"
  330. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ]; then
  331. if [ "$outputhex" ] ; then
  332. openssl dgst -$alg -hex | cut -d = -f 2 | tr -d ' '
  333. else
  334. openssl dgst -$alg -binary | _base64
  335. fi
  336. else
  337. _err "$alg is not supported yet"
  338. return 1
  339. fi
  340. }
  341. #Usage: keyfile hashalg
  342. #Output: Base64-encoded signature value
  343. _sign() {
  344. keyfile="$1"
  345. alg="$2"
  346. if [ -z "$alg" ] ; then
  347. _usage "Usage: _sign keyfile hashalg"
  348. return 1
  349. fi
  350. if [ "$alg" = "sha256" ] ; then
  351. openssl dgst -sha256 -sign "$keyfile" | _base64
  352. else
  353. _err "$alg is not supported yet"
  354. return 1
  355. fi
  356. }
  357. #keylength
  358. _isEccKey() {
  359. _length="$1"
  360. if [ -z "$_length" ] ;then
  361. return 1
  362. fi
  363. [ "$_length" != "1024" ] \
  364. && [ "$_length" != "2048" ] \
  365. && [ "$_length" != "3072" ] \
  366. && [ "$_length" != "4096" ] \
  367. && [ "$_length" != "8192" ]
  368. }
  369. # _createkey 2048|ec-256 file
  370. _createkey() {
  371. length="$1"
  372. f="$2"
  373. eccname="$length"
  374. if _startswith "$length" "ec-" ; then
  375. length=$(printf $length | cut -d '-' -f 2-100)
  376. if [ "$length" = "256" ] ; then
  377. eccname="prime256v1"
  378. fi
  379. if [ "$length" = "384" ] ; then
  380. eccname="secp384r1"
  381. fi
  382. if [ "$length" = "521" ] ; then
  383. eccname="secp521r1"
  384. fi
  385. fi
  386. if [ -z "$length" ] ; then
  387. length=2048
  388. fi
  389. _debug "Use length $length"
  390. if _isEccKey "$length" ; then
  391. _debug "Using ec name: $eccname"
  392. openssl ecparam -name $eccname -genkey 2>/dev/null > "$f"
  393. else
  394. _debug "Using RSA: $length"
  395. openssl genrsa $length 2>/dev/null > "$f"
  396. fi
  397. if [ "$?" != "0" ] ; then
  398. _err "Create key error."
  399. return 1
  400. fi
  401. }
  402. #domain
  403. _is_idn() {
  404. _is_idn_d="$1"
  405. _debug2 _is_idn_d "$_is_idn_d"
  406. _idn_temp=$(printf "%s" "$_is_idn_d" | tr -d "[0-9a-zA-Z.,-]")
  407. _debug2 _idn_temp "$_idn_temp"
  408. [ "$_idn_temp" ]
  409. }
  410. #aa.com
  411. #aa.com,bb.com,cc.com
  412. _idn() {
  413. __idn_d="$1"
  414. if ! _is_idn "$__idn_d" ; then
  415. printf "%s" "$__idn_d"
  416. return 0
  417. fi
  418. if _exists idn ; then
  419. if _contains "$__idn_d" ',' ; then
  420. _i_first="1"
  421. for f in $(echo "$__idn_d" | tr ',' ' ') ; do
  422. [ -z "$f" ] && continue
  423. if [ -z "$_i_first" ] ; then
  424. printf "%s" ","
  425. else
  426. _i_first=""
  427. fi
  428. idn "$f" | tr -d "\r\n"
  429. done
  430. else
  431. idn "$__idn_d" | tr -d "\r\n"
  432. fi
  433. else
  434. _err "Please install idn to process IDN names."
  435. fi
  436. }
  437. #_createcsr cn san_list keyfile csrfile conf
  438. _createcsr() {
  439. _debug _createcsr
  440. domain="$1"
  441. domainlist="$2"
  442. csrkey="$3"
  443. csr="$4"
  444. csrconf="$5"
  445. _debug2 domain "$domain"
  446. _debug2 domainlist "$domainlist"
  447. _debug2 csrkey "$csrkey"
  448. _debug2 csr "$csr"
  449. _debug2 csrconf "$csrconf"
  450. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\n\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment" > "$csrconf"
  451. if [ -z "$domainlist" ] || [ "$domainlist" = "$NO_VALUE" ]; then
  452. #single domain
  453. _info "Single domain" "$domain"
  454. else
  455. domainlist="$(_idn $domainlist)"
  456. _debug2 domainlist "$domainlist"
  457. if _contains "$domainlist" "," ; then
  458. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  459. else
  460. alt="DNS:$domainlist"
  461. fi
  462. #multi
  463. _info "Multi domain" "$alt"
  464. printf -- "\nsubjectAltName=$alt" >> "$csrconf"
  465. fi
  466. if [ "$Le_OCSP_Stable" ] ; then
  467. _savedomainconf Le_OCSP_Stable "$Le_OCSP_Stable"
  468. printf -- "\nbasicConstraints = CA:FALSE\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >> "$csrconf"
  469. fi
  470. _csr_cn="$(_idn "$domain")"
  471. _debug2 _csr_cn "$_csr_cn"
  472. openssl req -new -sha256 -key "$csrkey" -subj "/CN=$_csr_cn" -config "$csrconf" -out "$csr"
  473. }
  474. #_signcsr key csr conf cert
  475. _signcsr() {
  476. key="$1"
  477. csr="$2"
  478. conf="$3"
  479. cert="$4"
  480. _debug "_signcsr"
  481. _msg="$(openssl x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
  482. _ret="$?"
  483. _debug "$_msg"
  484. return $_ret
  485. }
  486. #_csrfile
  487. _readSubjectFromCSR() {
  488. _csrfile="$1"
  489. if [ -z "$_csrfile" ] ; then
  490. _usage "_readSubjectFromCSR mycsr.csr"
  491. return 1
  492. fi
  493. openssl req -noout -in "$_csrfile" -subject | _egrep_o "CN=.*" | cut -d = -f 2 | cut -d / -f 1 | tr -d '\n'
  494. }
  495. #_csrfile
  496. #echo comma separated domain list
  497. _readSubjectAltNamesFromCSR() {
  498. _csrfile="$1"
  499. if [ -z "$_csrfile" ] ; then
  500. _usage "_readSubjectAltNamesFromCSR mycsr.csr"
  501. return 1
  502. fi
  503. _csrsubj="$(_readSubjectFromCSR "$_csrfile")"
  504. _debug _csrsubj "$_csrsubj"
  505. _dnsAltnames="$(openssl req -noout -text -in "$_csrfile" | grep "^ *DNS:.*" | tr -d ' \n')"
  506. _debug _dnsAltnames "$_dnsAltnames"
  507. if _contains "$_dnsAltnames," "DNS:$_csrsubj," ; then
  508. _debug "AltNames contains subject"
  509. _dnsAltnames="$(printf "%s" "$_dnsAltnames," | sed "s/DNS:$_csrsubj,//g")"
  510. else
  511. _debug "AltNames doesn't contain subject"
  512. fi
  513. printf "%s" "$_dnsAltnames" | sed "s/DNS://g"
  514. }
  515. #_csrfile
  516. _readKeyLengthFromCSR() {
  517. _csrfile="$1"
  518. if [ -z "$_csrfile" ] ; then
  519. _usage "_readKeyLengthFromCSR mycsr.csr"
  520. return 1
  521. fi
  522. _outcsr="$(openssl req -noout -text -in "$_csrfile")"
  523. if _contains "$_outcsr" "Public Key Algorithm: id-ecPublicKey" ; then
  524. _debug "ECC CSR"
  525. echo "$_outcsr" | _egrep_o "^ *ASN1 OID:.*" | cut -d ':' -f 2 | tr -d ' '
  526. else
  527. _debug "RSA CSR"
  528. echo "$_outcsr" | _egrep_o "^ *Public-Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1
  529. fi
  530. }
  531. _ss() {
  532. _port="$1"
  533. if _exists "ss" ; then
  534. _debug "Using: ss"
  535. ss -ntpl | grep ":$_port "
  536. return 0
  537. fi
  538. if _exists "netstat" ; then
  539. _debug "Using: netstat"
  540. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  541. #for windows version netstat tool
  542. netstat -an -p tcp | grep "LISTENING" | grep ":$_port "
  543. else
  544. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  545. netstat -an -p tcp | grep LISTEN | grep ":$_port "
  546. elif netstat -help 2>&1 | grep -- '-P protocol' >/dev/null ; then
  547. #for solaris
  548. netstat -an -P tcp | grep "\.$_port " | grep "LISTEN"
  549. else
  550. netstat -ntpl | grep ":$_port "
  551. fi
  552. fi
  553. return 0
  554. fi
  555. return 1
  556. }
  557. #domain [password] [isEcc]
  558. toPkcs() {
  559. domain="$1"
  560. pfxPassword="$2"
  561. if [ -z "$domain" ] ; then
  562. _usage "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  563. return 1
  564. fi
  565. _isEcc="$3"
  566. _initpath "$domain" "$_isEcc"
  567. if [ "$pfxPassword" ] ; then
  568. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  569. else
  570. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  571. fi
  572. if [ "$?" = "0" ] ; then
  573. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  574. fi
  575. }
  576. #[2048]
  577. createAccountKey() {
  578. _info "Creating account key"
  579. if [ -z "$1" ] ; then
  580. _usage "Usage: $PROJECT_ENTRY --createAccountKey --accountkeylength 2048"
  581. return
  582. fi
  583. length=$1
  584. if _isEccKey "$length" ; then
  585. length=2048
  586. fi
  587. if [ -z "$length" ] || [ "$length" = "$NO_VALUE" ] ; then
  588. _debug "Use default length 2048"
  589. length=2048
  590. fi
  591. _debug length "$length"
  592. _initpath
  593. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  594. _info "Account key exists, skip"
  595. return
  596. else
  597. #generate account key
  598. _createkey "$length" "$ACCOUNT_KEY_PATH"
  599. fi
  600. }
  601. #domain [length]
  602. createDomainKey() {
  603. _info "Creating domain key"
  604. if [ -z "$1" ] ; then
  605. _usage "Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]"
  606. return
  607. fi
  608. domain=$1
  609. length=$2
  610. _initpath $domain "$length"
  611. if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
  612. _createkey "$length" "$CERT_KEY_PATH"
  613. else
  614. if [ "$IS_RENEW" ] ; then
  615. _info "Domain key exists, skip"
  616. return 0
  617. else
  618. _err "Domain key exists, do you want to overwrite the key?"
  619. _err "Add '--force', and try again."
  620. return 1
  621. fi
  622. fi
  623. }
  624. # domain domainlist isEcc
  625. createCSR() {
  626. _info "Creating csr"
  627. if [ -z "$1" ] ; then
  628. _usage "Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]"
  629. return
  630. fi
  631. domain="$1"
  632. domainlist="$2"
  633. _isEcc="$3"
  634. _initpath "$domain" "$_isEcc"
  635. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  636. _info "CSR exists, skip"
  637. return
  638. fi
  639. if [ ! -f "$CERT_KEY_PATH" ] ; then
  640. _err "The key file is not found: $CERT_KEY_PATH"
  641. _err "Please create the key file first."
  642. return 1
  643. fi
  644. _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
  645. }
  646. _urlencode() {
  647. __n=$(cat)
  648. echo $__n | tr '/+' '_-' | tr -d '= '
  649. }
  650. _time2str() {
  651. #BSD
  652. if date -u -d@$1 2>/dev/null ; then
  653. return
  654. fi
  655. #Linux
  656. if date -u -r $1 2>/dev/null ; then
  657. return
  658. fi
  659. #Soaris
  660. if _exists adb ; then
  661. echo $(echo "0t${1}=Y" | adb)
  662. fi
  663. }
  664. _normalizeJson() {
  665. sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
  666. }
  667. _stat() {
  668. #Linux
  669. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  670. return
  671. fi
  672. #BSD
  673. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  674. return
  675. fi
  676. return 1; #error, 'stat' not found
  677. }
  678. #keyfile
  679. _calcjwk() {
  680. keyfile="$1"
  681. if [ -z "$keyfile" ] ; then
  682. _usage "Usage: _calcjwk keyfile"
  683. return 1
  684. fi
  685. EC_SIGN=""
  686. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  687. _debug "RSA key"
  688. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  689. if [ "${#pub_exp}" = "5" ] ; then
  690. pub_exp=0$pub_exp
  691. fi
  692. _debug3 pub_exp "$pub_exp"
  693. e=$(echo $pub_exp | _h2b | _base64)
  694. _debug3 e "$e"
  695. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  696. _debug3 modulus "$modulus"
  697. n="$(printf "%s" "$modulus"| _h2b | _base64 | _urlencode )"
  698. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  699. _debug3 jwk "$jwk"
  700. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  701. HEADERPLACE_PART1='{"nonce": "'
  702. HEADERPLACE_PART2='", "alg": "RS256", "jwk": '$jwk'}'
  703. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  704. _debug "EC key"
  705. EC_SIGN="1"
  706. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  707. _debug3 crv "$crv"
  708. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  709. pubi=$(_math $pubi + 1)
  710. _debug3 pubi "$pubi"
  711. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  712. pubj=$(_math $pubj + 1)
  713. _debug3 pubj "$pubj"
  714. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  715. _debug3 pubtext "$pubtext"
  716. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  717. xlen=$(_math $xlen / 4)
  718. _debug3 xlen "$xlen"
  719. xend=$(_math "$xend" + 1)
  720. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  721. _debug3 x "$x"
  722. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  723. _debug3 x64 "$x64"
  724. xend=$(_math "$xend" + 1)
  725. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  726. _debug3 y "$y"
  727. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  728. _debug3 y64 "$y64"
  729. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  730. _debug3 jwk "$jwk"
  731. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  732. HEADERPLACE_PART1='{"nonce": "'
  733. HEADERPLACE_PART2='", "alg": "ES256", "jwk": '$jwk'}'
  734. else
  735. _err "Only RSA or EC key is supported."
  736. return 1
  737. fi
  738. _debug3 HEADER "$HEADER"
  739. }
  740. _time() {
  741. date -u "+%s"
  742. }
  743. _mktemp() {
  744. if _exists mktemp ; then
  745. if mktemp 2>/dev/null ; then
  746. return
  747. elif _contains "$(mktemp 2>&1)" "-t prefix" && mktemp -t "$PROJECT_NAME" 2>/dev/null ; then
  748. #for Mac osx
  749. return
  750. fi
  751. fi
  752. if [ -d "/tmp" ] ; then
  753. echo "/tmp/${PROJECT_NAME}wefADf24sf.$(_time).tmp"
  754. return 0
  755. fi
  756. _err "Can not create temp file."
  757. }
  758. _inithttp() {
  759. if [ -z "$HTTP_HEADER" ] || ! touch "$HTTP_HEADER" ; then
  760. HTTP_HEADER="$(_mktemp)"
  761. _debug2 HTTP_HEADER "$HTTP_HEADER"
  762. fi
  763. if [ -z "$CURL" ] ; then
  764. CURL="curl -L --silent --dump-header $HTTP_HEADER "
  765. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  766. _CURL_DUMP="$(_mktemp)"
  767. CURL="$CURL --trace-ascii $_CURL_DUMP "
  768. fi
  769. if [ "$CA_BUNDLE" ] ; then
  770. CURL="$CURL --cacert $CA_BUNDLE "
  771. fi
  772. if [ "$HTTPS_INSECURE" ] ; then
  773. CURL="$CURL --insecure "
  774. fi
  775. fi
  776. if [ -z "$WGET" ] ; then
  777. WGET="wget -q"
  778. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  779. WGET="$WGET -d "
  780. fi
  781. if [ "$CA_BUNDLE" ] ; then
  782. WGET="$WGET --ca-certificate $CA_BUNDLE "
  783. fi
  784. if [ "$HTTPS_INSECURE" ] ; then
  785. WGET="$WGET --no-check-certificate "
  786. fi
  787. fi
  788. }
  789. # body url [needbase64] [POST|PUT]
  790. _post() {
  791. body="$1"
  792. url="$2"
  793. needbase64="$3"
  794. httpmethod="$4"
  795. if [ -z "$httpmethod" ] ; then
  796. httpmethod="POST"
  797. fi
  798. _debug $httpmethod
  799. _debug "url" "$url"
  800. _debug2 "body" "$body"
  801. _inithttp
  802. if _exists "curl" ; then
  803. _CURL="$CURL"
  804. _debug "_CURL" "$_CURL"
  805. if [ "$needbase64" ] ; then
  806. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url" | _base64)"
  807. else
  808. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url" )"
  809. fi
  810. _ret="$?"
  811. if [ "$_ret" != "0" ] ; then
  812. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  813. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  814. _err "Here is the curl dump log:"
  815. _err "$(cat "$_CURL_DUMP")"
  816. fi
  817. fi
  818. elif _exists "wget" ; then
  819. _debug "WGET" "$WGET"
  820. if [ "$needbase64" ] ; then
  821. if [ "$httpmethod" = "POST" ] ; then
  822. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  823. else
  824. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  825. fi
  826. else
  827. if [ "$httpmethod" = "POST" ] ; then
  828. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER")"
  829. else
  830. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER")"
  831. fi
  832. fi
  833. _ret="$?"
  834. if [ "$_ret" = "8" ] ; then
  835. _ret=0
  836. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  837. fi
  838. if [ "$_ret" != "0" ] ; then
  839. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  840. fi
  841. _sed_i "s/^ *//g" "$HTTP_HEADER"
  842. else
  843. _ret="$?"
  844. _err "Neither curl nor wget is found, can not do $httpmethod."
  845. fi
  846. _debug "_ret" "$_ret"
  847. printf "%s" "$response"
  848. return $_ret
  849. }
  850. # url getheader timeout
  851. _get() {
  852. _debug GET
  853. url="$1"
  854. onlyheader="$2"
  855. t="$3"
  856. _debug url $url
  857. _debug "timeout" "$t"
  858. _inithttp
  859. if _exists "curl" ; then
  860. _CURL="$CURL"
  861. if [ "$t" ] ; then
  862. _CURL="$_CURL --connect-timeout $t"
  863. fi
  864. _debug "_CURL" "$_CURL"
  865. if [ "$onlyheader" ] ; then
  866. $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" $url
  867. else
  868. $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" $url
  869. fi
  870. ret=$?
  871. if [ "$ret" != "0" ] ; then
  872. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
  873. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  874. _err "Here is the curl dump log:"
  875. _err "$(cat "$_CURL_DUMP")"
  876. fi
  877. fi
  878. elif _exists "wget" ; then
  879. _WGET="$WGET"
  880. if [ "$t" ] ; then
  881. _WGET="$_WGET --timeout=$t"
  882. fi
  883. _debug "_WGET" "$_WGET"
  884. if [ "$onlyheader" ] ; then
  885. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  886. else
  887. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - $url
  888. fi
  889. ret=$?
  890. if [ "$_ret" = "8" ] ; then
  891. _ret=0
  892. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  893. fi
  894. if [ "$ret" != "0" ] ; then
  895. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
  896. fi
  897. else
  898. ret=$?
  899. _err "Neither curl nor wget is found, can not do GET."
  900. fi
  901. _debug "ret" "$ret"
  902. return $ret
  903. }
  904. _head_n() {
  905. head -n $1
  906. }
  907. _tail_n() {
  908. if ! tail -n $1 2>/dev/null ; then
  909. #fix for solaris
  910. tail -$1
  911. fi
  912. }
  913. # url payload needbase64 keyfile
  914. _send_signed_request() {
  915. url=$1
  916. payload=$2
  917. needbase64=$3
  918. keyfile=$4
  919. if [ -z "$keyfile" ] ; then
  920. keyfile="$ACCOUNT_KEY_PATH"
  921. fi
  922. _debug url $url
  923. _debug payload "$payload"
  924. if ! _calcjwk "$keyfile" ; then
  925. return 1
  926. fi
  927. payload64=$(printf "%s" "$payload" | _base64 | _urlencode)
  928. _debug3 payload64 $payload64
  929. nonceurl="$API/directory"
  930. _headers="$(_get $nonceurl "onlyheader")"
  931. if [ "$?" != "0" ] ; then
  932. _err "Can not connect to $nonceurl to get nonce."
  933. return 1
  934. fi
  935. _debug3 _headers "$_headers"
  936. nonce="$( echo "$_headers" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  937. _debug3 nonce "$nonce"
  938. protected="$HEADERPLACE_PART1$nonce$HEADERPLACE_PART2"
  939. _debug3 protected "$protected"
  940. protected64="$(printf "$protected" | _base64 | _urlencode)"
  941. _debug3 protected64 "$protected64"
  942. sig=$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  943. _debug3 sig "$sig"
  944. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  945. _debug3 body "$body"
  946. response="$(_post "$body" $url "$needbase64")"
  947. if [ "$?" != "0" ] ; then
  948. _err "Can not post to $url"
  949. return 1
  950. fi
  951. _debug2 original "$response"
  952. response="$( echo "$response" | _normalizeJson )"
  953. responseHeaders="$(cat $HTTP_HEADER)"
  954. _debug2 responseHeaders "$responseHeaders"
  955. _debug2 response "$response"
  956. code="$(grep "^HTTP" $HTTP_HEADER | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n" )"
  957. _debug code $code
  958. }
  959. #setopt "file" "opt" "=" "value" [";"]
  960. _setopt() {
  961. __conf="$1"
  962. __opt="$2"
  963. __sep="$3"
  964. __val="$4"
  965. __end="$5"
  966. if [ -z "$__opt" ] ; then
  967. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  968. return
  969. fi
  970. if [ ! -f "$__conf" ] ; then
  971. touch "$__conf"
  972. fi
  973. if grep -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  974. _debug3 OK
  975. if _contains "$__val" "&" ; then
  976. __val="$(echo $__val | sed 's/&/\\&/g')"
  977. fi
  978. text="$(cat $__conf)"
  979. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  980. elif grep -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  981. if _contains "$__val" "&" ; then
  982. __val="$(echo $__val | sed 's/&/\\&/g')"
  983. fi
  984. text="$(cat $__conf)"
  985. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  986. else
  987. _debug3 APP
  988. echo "$__opt$__sep$__val$__end" >> "$__conf"
  989. fi
  990. _debug2 "$(grep -n "^$__opt$__sep" $__conf)"
  991. }
  992. #_savedomainconf key value
  993. #save to domain.conf
  994. _savedomainconf() {
  995. _sdkey="$1"
  996. _sdvalue="$2"
  997. if [ "$DOMAIN_CONF" ] ; then
  998. _setopt "$DOMAIN_CONF" "$_sdkey" "=" "\"$_sdvalue\""
  999. else
  1000. _err "DOMAIN_CONF is empty, can not save $_sdkey=$_sdvalue"
  1001. fi
  1002. }
  1003. #_cleardomainconf key
  1004. _cleardomainconf() {
  1005. _sdkey="$1"
  1006. if [ "$DOMAIN_CONF" ] ; then
  1007. _sed_i "s/^$_sdkey.*$//" "$DOMAIN_CONF"
  1008. else
  1009. _err "DOMAIN_CONF is empty, can not save $_sdkey=$value"
  1010. fi
  1011. }
  1012. #_readdomainconf key
  1013. _readdomainconf() {
  1014. _sdkey="$1"
  1015. if [ "$DOMAIN_CONF" ] ; then
  1016. (
  1017. eval $(grep "^$_sdkey *=" "$DOMAIN_CONF")
  1018. eval "printf \"%s\" \"\$$_sdkey\""
  1019. )
  1020. else
  1021. _err "DOMAIN_CONF is empty, can not read $_sdkey"
  1022. fi
  1023. }
  1024. #_saveaccountconf key value
  1025. _saveaccountconf() {
  1026. _sckey="$1"
  1027. _scvalue="$2"
  1028. if [ "$ACCOUNT_CONF_PATH" ] ; then
  1029. _setopt "$ACCOUNT_CONF_PATH" "$_sckey" "=" "\"$_scvalue\""
  1030. else
  1031. _err "ACCOUNT_CONF_PATH is empty, can not save $_sckey=$_scvalue"
  1032. fi
  1033. }
  1034. #_clearaccountconf key
  1035. _clearaccountconf() {
  1036. _scvalue="$1"
  1037. if [ "$ACCOUNT_CONF_PATH" ] ; then
  1038. _sed_i "s/^$_scvalue.*$//" "$ACCOUNT_CONF_PATH"
  1039. else
  1040. _err "ACCOUNT_CONF_PATH is empty, can not clear $_scvalue"
  1041. fi
  1042. }
  1043. # content localaddress
  1044. _startserver() {
  1045. content="$1"
  1046. ncaddr="$2"
  1047. _debug "ncaddr" "$ncaddr"
  1048. _debug "startserver: $$"
  1049. nchelp="$(nc -h 2>&1)"
  1050. _debug Le_HTTPPort "$Le_HTTPPort"
  1051. _debug Le_Listen_V4 "$Le_Listen_V4"
  1052. _debug Le_Listen_V6 "$Le_Listen_V6"
  1053. _NC="nc"
  1054. if [ "$Le_Listen_V4" ] ; then
  1055. _NC="$_NC -4"
  1056. elif [ "$Le_Listen_V6" ] ; then
  1057. _NC="$_NC -6"
  1058. fi
  1059. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  1060. _NC="$_NC -q 1 -l $ncaddr"
  1061. else
  1062. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  1063. _NC="$_NC -c -l $ncaddr"
  1064. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  1065. _NC="$_NC -N -l $ncaddr"
  1066. else
  1067. _NC="$_NC -l $ncaddr"
  1068. fi
  1069. fi
  1070. _debug "_NC" "$_NC"
  1071. #for centos ncat
  1072. if _contains "$nchelp" "nmap.org" ; then
  1073. _debug "Using ncat: nmap.org"
  1074. if [ "$DEBUG" ] ; then
  1075. if printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort ; then
  1076. return
  1077. fi
  1078. else
  1079. if printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1; then
  1080. return
  1081. fi
  1082. fi
  1083. _err "ncat listen error."
  1084. fi
  1085. # while true ; do
  1086. if [ "$DEBUG" ] ; then
  1087. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort ; then
  1088. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort ;
  1089. fi
  1090. else
  1091. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
  1092. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
  1093. fi
  1094. fi
  1095. if [ "$?" != "0" ] ; then
  1096. _err "nc listen error."
  1097. exit 1
  1098. fi
  1099. # done
  1100. }
  1101. _stopserver(){
  1102. pid="$1"
  1103. _debug "pid" "$pid"
  1104. if [ -z "$pid" ] ; then
  1105. return
  1106. fi
  1107. _debug2 "Le_HTTPPort" "$Le_HTTPPort"
  1108. if [ "$Le_HTTPPort" ] ; then
  1109. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ] ; then
  1110. _get "http://localhost:$Le_HTTPPort" "" 1
  1111. else
  1112. _get "http://localhost:$Le_HTTPPort" "" 1 >/dev/null 2>&1
  1113. fi
  1114. fi
  1115. _debug2 "Le_TLSPort" "$Le_TLSPort"
  1116. if [ "$Le_TLSPort" ] ; then
  1117. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ] ; then
  1118. _get "https://localhost:$Le_TLSPort" "" 1
  1119. _get "https://localhost:$Le_TLSPort" "" 1
  1120. else
  1121. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1122. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1123. fi
  1124. fi
  1125. }
  1126. # sleep sec
  1127. _sleep() {
  1128. _sleep_sec="$1"
  1129. if [ "$__INTERACTIVE" ] ; then
  1130. _sleep_c="$_sleep_sec"
  1131. while [ "$_sleep_c" -ge "0" ] ;
  1132. do
  1133. printf "\r \r"
  1134. __green "$_sleep_c"
  1135. _sleep_c="$(_math $_sleep_c - 1)"
  1136. sleep 1
  1137. done
  1138. printf "\r"
  1139. else
  1140. sleep "$_sleep_sec"
  1141. fi
  1142. }
  1143. # _starttlsserver san_a san_b port content _ncaddr
  1144. _starttlsserver() {
  1145. _info "Starting tls server."
  1146. san_a="$1"
  1147. san_b="$2"
  1148. port="$3"
  1149. content="$4"
  1150. opaddr="$5"
  1151. _debug san_a "$san_a"
  1152. _debug san_b "$san_b"
  1153. _debug port "$port"
  1154. #create key TLS_KEY
  1155. if ! _createkey "2048" "$TLS_KEY" ; then
  1156. _err "Create tls validation key error."
  1157. return 1
  1158. fi
  1159. #create csr
  1160. alt="$san_a"
  1161. if [ "$san_b" ] ; then
  1162. alt="$alt,$san_b"
  1163. fi
  1164. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" ; then
  1165. _err "Create tls validation csr error."
  1166. return 1
  1167. fi
  1168. #self signed
  1169. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT" ; then
  1170. _err "Create tls validation cert error."
  1171. return 1
  1172. fi
  1173. __S_OPENSSL="openssl s_server -cert $TLS_CERT -key $TLS_KEY "
  1174. if [ "$opaddr" ] ; then
  1175. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  1176. else
  1177. __S_OPENSSL="$__S_OPENSSL -accept $port"
  1178. fi
  1179. _debug Le_Listen_V4 "$Le_Listen_V4"
  1180. _debug Le_Listen_V6 "$Le_Listen_V6"
  1181. if [ "$Le_Listen_V4" ] ; then
  1182. __S_OPENSSL="$__S_OPENSSL -4"
  1183. elif [ "$Le_Listen_V6" ] ; then
  1184. __S_OPENSSL="$__S_OPENSSL -6"
  1185. fi
  1186. #start openssl
  1187. _debug "$__S_OPENSSL"
  1188. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  1189. (printf "HTTP/1.1 200 OK\r\n\r\n$content" | $__S_OPENSSL -tlsextdebug ) &
  1190. else
  1191. (printf "HTTP/1.1 200 OK\r\n\r\n$content" | $__S_OPENSSL >/dev/null 2>&1) &
  1192. fi
  1193. serverproc="$!"
  1194. sleep 2
  1195. _debug serverproc $serverproc
  1196. }
  1197. #file
  1198. _readlink() {
  1199. _rf="$1"
  1200. if ! readlink -f "$_rf" 2>/dev/null; then
  1201. if _startswith "$_rf" "\./$PROJECT_ENTRY" ; then
  1202. printf -- "%s" "$(pwd)/$PROJECT_ENTRY"
  1203. return 0
  1204. fi
  1205. readlink "$_rf"
  1206. fi
  1207. }
  1208. __initHome() {
  1209. if [ -z "$_SCRIPT_HOME" ] ; then
  1210. if _exists readlink && _exists dirname ; then
  1211. _debug "Lets find script dir."
  1212. _debug "_SCRIPT_" "$_SCRIPT_"
  1213. _script="$(_readlink "$_SCRIPT_")"
  1214. _debug "_script" "$_script"
  1215. _script_home="$(dirname "$_script")"
  1216. _debug "_script_home" "$_script_home"
  1217. if [ -d "$_script_home" ] ; then
  1218. _SCRIPT_HOME="$_script_home"
  1219. else
  1220. _err "It seems the script home is not correct:$_script_home"
  1221. fi
  1222. fi
  1223. fi
  1224. if [ -z "$LE_WORKING_DIR" ] ; then
  1225. if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ] ; then
  1226. _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  1227. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1228. else
  1229. LE_WORKING_DIR="$_SCRIPT_HOME"
  1230. fi
  1231. fi
  1232. if [ -z "$LE_WORKING_DIR" ] ; then
  1233. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  1234. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1235. fi
  1236. export LE_WORKING_DIR
  1237. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  1238. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  1239. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ] ; then
  1240. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  1241. fi
  1242. fi
  1243. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  1244. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  1245. fi
  1246. DEFAULT_LOG_FILE="$LE_WORKING_DIR/$PROJECT_NAME.log"
  1247. DEFAULT_CA_HOME="$LE_WORKING_DIR/ca"
  1248. }
  1249. #[domain] [keylength]
  1250. _initpath() {
  1251. __initHome
  1252. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  1253. . "$ACCOUNT_CONF_PATH"
  1254. fi
  1255. if [ "$IN_CRON" ] ; then
  1256. if [ ! "$_USER_PATH_EXPORTED" ] ; then
  1257. _USER_PATH_EXPORTED=1
  1258. export PATH="$USER_PATH:$PATH"
  1259. fi
  1260. fi
  1261. if [ -z "$CA_HOME" ] ; then
  1262. CA_HOME="$DEFAULT_CA_HOME"
  1263. fi
  1264. if [ -z "$API" ] ; then
  1265. if [ -z "$STAGE" ] ; then
  1266. API="$DEFAULT_CA"
  1267. else
  1268. API="$STAGE_CA"
  1269. _info "Using stage api:$API"
  1270. fi
  1271. fi
  1272. _API_HOST="$(echo "$API" | cut -d : -f 2 | tr -d '/')"
  1273. CA_DIR="$CA_HOME/$_API_HOST"
  1274. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  1275. if [ -z "$CA_CONF" ] ; then
  1276. CA_CONF="$_DEFAULT_CA_CONF"
  1277. fi
  1278. if [ -f "$CA_CONF" ] ; then
  1279. . "$CA_CONF"
  1280. fi
  1281. if [ -z "$ACME_DIR" ] ; then
  1282. ACME_DIR="/home/.acme"
  1283. fi
  1284. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  1285. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  1286. fi
  1287. if [ -z "$USER_AGENT" ] ; then
  1288. USER_AGENT="$DEFAULT_USER_AGENT"
  1289. fi
  1290. if [ -z "$HTTP_HEADER" ] ; then
  1291. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  1292. fi
  1293. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  1294. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  1295. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  1296. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  1297. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  1298. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  1299. fi
  1300. if [ -z "$ACCOUNT_JSON_PATH" ] ; then
  1301. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  1302. fi
  1303. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  1304. if [ -z "$CERT_HOME" ] ; then
  1305. CERT_HOME="$_DEFAULT_CERT_HOME"
  1306. fi
  1307. if [ -z "$1" ] ; then
  1308. return 0
  1309. fi
  1310. mkdir -p "$CA_DIR"
  1311. domain="$1"
  1312. _ilength="$2"
  1313. if [ -z "$DOMAIN_PATH" ] ; then
  1314. domainhome="$CERT_HOME/$domain"
  1315. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  1316. DOMAIN_PATH="$domainhome"
  1317. if _isEccKey "$_ilength" ; then
  1318. DOMAIN_PATH="$domainhomeecc"
  1319. else
  1320. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ] ; then
  1321. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  1322. fi
  1323. fi
  1324. _debug DOMAIN_PATH "$DOMAIN_PATH"
  1325. fi
  1326. if [ ! -d "$DOMAIN_PATH" ] ; then
  1327. if ! mkdir -p "$DOMAIN_PATH" ; then
  1328. _err "Can not create domain path: $DOMAIN_PATH"
  1329. return 1
  1330. fi
  1331. fi
  1332. if [ -z "$DOMAIN_CONF" ] ; then
  1333. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  1334. fi
  1335. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  1336. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  1337. fi
  1338. if [ -z "$CSR_PATH" ] ; then
  1339. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  1340. fi
  1341. if [ -z "$CERT_KEY_PATH" ] ; then
  1342. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  1343. fi
  1344. if [ -z "$CERT_PATH" ] ; then
  1345. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  1346. fi
  1347. if [ -z "$CA_CERT_PATH" ] ; then
  1348. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  1349. fi
  1350. if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
  1351. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  1352. fi
  1353. if [ -z "$CERT_PFX_PATH" ] ; then
  1354. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  1355. fi
  1356. if [ -z "$TLS_CONF" ] ; then
  1357. TLS_CONF="$DOMAIN_PATH/tls.valdation.conf"
  1358. fi
  1359. if [ -z "$TLS_CERT" ] ; then
  1360. TLS_CERT="$DOMAIN_PATH/tls.valdation.cert"
  1361. fi
  1362. if [ -z "$TLS_KEY" ] ; then
  1363. TLS_KEY="$DOMAIN_PATH/tls.valdation.key"
  1364. fi
  1365. if [ -z "$TLS_CSR" ] ; then
  1366. TLS_CSR="$DOMAIN_PATH/tls.valdation.csr"
  1367. fi
  1368. }
  1369. _apachePath() {
  1370. _APACHECTL="apachectl"
  1371. if ! _exists apachectl ; then
  1372. if _exists apache2ctl ; then
  1373. _APACHECTL="apache2ctl"
  1374. else
  1375. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  1376. _err "Please use webroot mode to try again."
  1377. return 1
  1378. fi
  1379. fi
  1380. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  1381. _debug httpdconfname "$httpdconfname"
  1382. if _startswith "$httpdconfname" '/' ; then
  1383. httpdconf="$httpdconfname"
  1384. httpdconfname="$(basename $httpdconfname)"
  1385. else
  1386. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  1387. _debug httpdroot "$httpdroot"
  1388. httpdconf="$httpdroot/$httpdconfname"
  1389. httpdconfname="$(basename $httpdconfname)"
  1390. fi
  1391. _debug httpdconf "$httpdconf"
  1392. _debug httpdconfname "$httpdconfname"
  1393. if [ ! -f "$httpdconf" ] ; then
  1394. _err "Apache Config file not found" "$httpdconf"
  1395. return 1
  1396. fi
  1397. return 0
  1398. }
  1399. _restoreApache() {
  1400. if [ -z "$usingApache" ] ; then
  1401. return 0
  1402. fi
  1403. _initpath
  1404. if ! _apachePath ; then
  1405. return 1
  1406. fi
  1407. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  1408. _debug "No config file to restore."
  1409. return 0
  1410. fi
  1411. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" > "$httpdconf"
  1412. _debug "Restored: $httpdconf."
  1413. if ! $_APACHECTL -t >/dev/null 2>&1 ; then
  1414. _err "Sorry, restore apache config error, please contact me."
  1415. return 1;
  1416. fi
  1417. _debug "Restored successfully."
  1418. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1419. return 0
  1420. }
  1421. _setApache() {
  1422. _initpath
  1423. if ! _apachePath ; then
  1424. return 1
  1425. fi
  1426. #test the conf first
  1427. _info "Checking if there is an error in the apache config file before starting."
  1428. _msg="$($_APACHECTL -t 2>&1 )"
  1429. if [ "$?" != "0" ] ; then
  1430. _err "Sorry, apache config file has error, please fix it first, then try again."
  1431. _err "Don't worry, there is nothing changed to your system."
  1432. _err "$_msg"
  1433. return 1;
  1434. else
  1435. _info "OK"
  1436. fi
  1437. #backup the conf
  1438. _debug "Backup apache config file" "$httpdconf"
  1439. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/" ; then
  1440. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  1441. _err "This might be a bug of $PROJECT_NAME , pleae report issue: $PROJECT"
  1442. return 1
  1443. fi
  1444. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1445. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  1446. _info "The backup file will be deleted on sucess, just forget it."
  1447. #add alias
  1448. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  1449. _debug "apacheVer" "$apacheVer"
  1450. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  1451. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  1452. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ] ; then
  1453. echo "
  1454. Alias /.well-known/acme-challenge $ACME_DIR
  1455. <Directory $ACME_DIR >
  1456. Require all granted
  1457. </Directory>
  1458. " >> "$httpdconf"
  1459. else
  1460. echo "
  1461. Alias /.well-known/acme-challenge $ACME_DIR
  1462. <Directory $ACME_DIR >
  1463. Order allow,deny
  1464. Allow from all
  1465. </Directory>
  1466. " >> "$httpdconf"
  1467. fi
  1468. _msg="$($_APACHECTL -t 2>&1 )"
  1469. if [ "$?" != "0" ] ; then
  1470. _err "Sorry, apache config error"
  1471. if _restoreApache ; then
  1472. _err "The apache config file is restored."
  1473. else
  1474. _err "Sorry, The apache config file can not be restored, please report bug."
  1475. fi
  1476. return 1;
  1477. fi
  1478. if [ ! -d "$ACME_DIR" ] ; then
  1479. mkdir -p "$ACME_DIR"
  1480. chmod 755 "$ACME_DIR"
  1481. fi
  1482. if ! $_APACHECTL graceful ; then
  1483. _err "Sorry, $_APACHECTL graceful error, please contact me."
  1484. _restoreApache
  1485. return 1;
  1486. fi
  1487. usingApache="1"
  1488. return 0
  1489. }
  1490. _clearup() {
  1491. _stopserver $serverproc
  1492. serverproc=""
  1493. _restoreApache
  1494. if [ -z "$DEBUG" ] ; then
  1495. rm -f "$TLS_CONF"
  1496. rm -f "$TLS_CERT"
  1497. rm -f "$TLS_KEY"
  1498. rm -f "$TLS_CSR"
  1499. fi
  1500. }
  1501. # webroot removelevel tokenfile
  1502. _clearupwebbroot() {
  1503. __webroot="$1"
  1504. if [ -z "$__webroot" ] ; then
  1505. _debug "no webroot specified, skip"
  1506. return 0
  1507. fi
  1508. _rmpath=""
  1509. if [ "$2" = '1' ] ; then
  1510. _rmpath="$__webroot/.well-known"
  1511. elif [ "$2" = '2' ] ; then
  1512. _rmpath="$__webroot/.well-known/acme-challenge"
  1513. elif [ "$2" = '3' ] ; then
  1514. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  1515. else
  1516. _debug "Skip for removelevel:$2"
  1517. fi
  1518. if [ "$_rmpath" ] ; then
  1519. if [ "$DEBUG" ] ; then
  1520. _debug "Debugging, skip removing: $_rmpath"
  1521. else
  1522. rm -rf "$_rmpath"
  1523. fi
  1524. fi
  1525. return 0
  1526. }
  1527. _on_before_issue() {
  1528. _debug _on_before_issue
  1529. if _hasfield "$Le_Webroot" "$NO_VALUE" ; then
  1530. if ! _exists "nc" ; then
  1531. _err "Please install netcat(nc) tools first."
  1532. return 1
  1533. fi
  1534. elif ! _hasfield "$Le_Webroot" "$W_TLS" ; then
  1535. #no need to check anymore
  1536. return 0
  1537. fi
  1538. _debug Le_LocalAddress "$Le_LocalAddress"
  1539. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  1540. _index=1
  1541. _currentRoot=""
  1542. _addrIndex=1
  1543. for d in $alldomains
  1544. do
  1545. _debug "Check for domain" $d
  1546. _currentRoot="$(_getfield "$Le_Webroot" $_index)"
  1547. _debug "_currentRoot" "$_currentRoot"
  1548. _index=$(_math $_index + 1)
  1549. _checkport=""
  1550. if [ "$_currentRoot" = "$NO_VALUE" ] ; then
  1551. _info "Standalone mode."
  1552. if [ -z "$Le_HTTPPort" ] ; then
  1553. Le_HTTPPort=80
  1554. else
  1555. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  1556. fi
  1557. _checkport="$Le_HTTPPort"
  1558. elif [ "$_currentRoot" = "$W_TLS" ] ; then
  1559. _info "Standalone tls mode."
  1560. if [ -z "$Le_TLSPort" ] ; then
  1561. Le_TLSPort=443
  1562. else
  1563. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  1564. fi
  1565. _checkport="$Le_TLSPort"
  1566. fi
  1567. if [ "$_checkport" ] ; then
  1568. _debug _checkport "$_checkport"
  1569. _checkaddr="$(_getfield "$Le_LocalAddress" $_addrIndex)"
  1570. _debug _checkaddr "$_checkaddr"
  1571. _addrIndex="$(_math $_addrIndex + 1)"
  1572. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  1573. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  1574. if [ -z "$netprc" ] ; then
  1575. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  1576. fi
  1577. if [ "$netprc" ] ; then
  1578. _err "$netprc"
  1579. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  1580. _err "Please stop it first"
  1581. return 1
  1582. fi
  1583. fi
  1584. done
  1585. if _hasfield "$Le_Webroot" "apache" ; then
  1586. if ! _setApache ; then
  1587. _err "set up apache error. Report error to me."
  1588. return 1
  1589. fi
  1590. else
  1591. usingApache=""
  1592. fi
  1593. #run pre hook
  1594. if [ "$Le_PreHook" ] ; then
  1595. _info "Run pre hook:'$Le_PreHook'"
  1596. if ! (
  1597. cd "$DOMAIN_PATH" && eval "$Le_PreHook"
  1598. ) ; then
  1599. _err "Error when run pre hook."
  1600. return 1
  1601. fi
  1602. fi
  1603. }
  1604. _on_issue_err() {
  1605. _debug _on_issue_err
  1606. if [ "$LOG_FILE" ] ; then
  1607. _err "Please check log file for more details: $LOG_FILE"
  1608. else
  1609. _err "Please use add '--debug' or '--log' to check more details."
  1610. _err "See: $_DEBUG_WIKI"
  1611. fi
  1612. #run the post hook
  1613. if [ "$Le_PostHook" ] ; then
  1614. _info "Run post hook:'$Le_PostHook'"
  1615. if ! (
  1616. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1617. ) ; then
  1618. _err "Error when run post hook."
  1619. return 1
  1620. fi
  1621. fi
  1622. }
  1623. _on_issue_success() {
  1624. _debug _on_issue_success
  1625. #run the post hook
  1626. if [ "$Le_PostHook" ] ; then
  1627. _info "Run post hook:'$Le_PostHook'"
  1628. if ! (
  1629. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1630. ) ; then
  1631. _err "Error when run post hook."
  1632. return 1
  1633. fi
  1634. fi
  1635. #run renew hook
  1636. if [ "$IS_RENEW" ] && [ "$Le_RenewHook" ] ; then
  1637. _info "Run renew hook:'$Le_RenewHook'"
  1638. if ! (
  1639. cd "$DOMAIN_PATH" && eval "$Le_RenewHook"
  1640. ) ; then
  1641. _err "Error when run renew hook."
  1642. return 1
  1643. fi
  1644. fi
  1645. }
  1646. updateaccount() {
  1647. _initpath
  1648. _regAccount
  1649. }
  1650. registeraccount() {
  1651. _initpath
  1652. _regAccount
  1653. }
  1654. _regAccount() {
  1655. _initpath
  1656. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  1657. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  1658. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  1659. fi
  1660. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  1661. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  1662. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  1663. fi
  1664. if [ ! -f "$ACCOUNT_KEY_PATH" ] ; then
  1665. _acck="no"
  1666. if [ "$Le_Keylength" ] ; then
  1667. _acck="$Le_Keylength"
  1668. fi
  1669. if ! createAccountKey "$_acck" ; then
  1670. _err "Create account key error."
  1671. return 1
  1672. fi
  1673. fi
  1674. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  1675. return 1
  1676. fi
  1677. _updateTos=""
  1678. _reg_res="new-reg"
  1679. while true ;
  1680. do
  1681. _debug AGREEMENT "$AGREEMENT"
  1682. accountkey_json=$(printf "%s" "$jwk" | tr -d ' ' )
  1683. thumbprint=$(printf "%s" "$accountkey_json" | _digest "sha256" | _urlencode)
  1684. regjson='{"resource": "'$_reg_res'", "agreement": "'$AGREEMENT'"}'
  1685. if [ "$ACCOUNT_EMAIL" ] ; then
  1686. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  1687. fi
  1688. if [ -z "$_updateTos" ] ; then
  1689. _info "Registering account"
  1690. if ! _send_signed_request "$API/acme/new-reg" "$regjson" ; then
  1691. _err "Register account Error: $response"
  1692. return 1
  1693. fi
  1694. if [ "$code" = "" ] || [ "$code" = '201' ] ; then
  1695. echo "$response" > $ACCOUNT_JSON_PATH
  1696. _info "Registered"
  1697. elif [ "$code" = '409' ] ; then
  1698. _info "Already registered"
  1699. else
  1700. _err "Register account Error: $response"
  1701. return 1
  1702. fi
  1703. _accUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2| tr -d "\r\n")"
  1704. _debug "_accUri" "$_accUri"
  1705. _tos="$(echo "$responseHeaders" | grep "^Link:.*rel=\"terms-of-service\"" | _head_n 1 | _egrep_o "<.*>" | tr -d '<>')"
  1706. _debug "_tos" "$_tos"
  1707. if [ -z "$_tos" ] ; then
  1708. _debug "Use default tos: $DEFAULT_AGREEMENT"
  1709. _tos="$DEFAULT_AGREEMENT"
  1710. fi
  1711. if [ "$_tos" != "$AGREEMENT" ]; then
  1712. _updateTos=1
  1713. AGREEMENT="$_tos"
  1714. _reg_res="reg"
  1715. continue
  1716. fi
  1717. else
  1718. _debug "Update tos: $_tos"
  1719. if ! _send_signed_request "$_accUri" "$regjson" ; then
  1720. _err "Update tos error."
  1721. return 1
  1722. fi
  1723. if [ "$code" = '202' ] ; then
  1724. _info "Update success."
  1725. else
  1726. _err "Update error."
  1727. return 1
  1728. fi
  1729. fi
  1730. return 0
  1731. done
  1732. }
  1733. #webroot, domain domainlist keylength
  1734. issue() {
  1735. if [ -z "$2" ] ; then
  1736. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  1737. return 1
  1738. fi
  1739. Le_Webroot="$1"
  1740. Le_Domain="$2"
  1741. Le_Alt="$3"
  1742. Le_Keylength="$4"
  1743. Le_RealCertPath="$5"
  1744. Le_RealKeyPath="$6"
  1745. Le_RealCACertPath="$7"
  1746. Le_ReloadCmd="$8"
  1747. Le_RealFullChainPath="$9"
  1748. Le_PreHook="${10}"
  1749. Le_PostHook="${11}"
  1750. Le_RenewHook="${12}"
  1751. Le_LocalAddress="${13}"
  1752. #remove these later.
  1753. if [ "$Le_Webroot" = "dns-cf" ] ; then
  1754. Le_Webroot="dns_cf"
  1755. fi
  1756. if [ "$Le_Webroot" = "dns-dp" ] ; then
  1757. Le_Webroot="dns_dp"
  1758. fi
  1759. if [ "$Le_Webroot" = "dns-cx" ] ; then
  1760. Le_Webroot="dns_cx"
  1761. fi
  1762. _debug "Using api: $API"
  1763. if [ ! "$IS_RENEW" ] ; then
  1764. _initpath $Le_Domain "$Le_Keylength"
  1765. mkdir -p "$DOMAIN_PATH"
  1766. fi
  1767. if [ -f "$DOMAIN_CONF" ] ; then
  1768. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  1769. _debug Le_NextRenewTime "$Le_NextRenewTime"
  1770. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ $(_time) -lt $Le_NextRenewTime ] ; then
  1771. _saved_domain=$(_readdomainconf Le_Domain)
  1772. _debug _saved_domain "$_saved_domain"
  1773. _saved_alt=$(_readdomainconf Le_Alt)
  1774. _debug _saved_alt "$_saved_alt"
  1775. if [ "$_saved_domain,$_saved_alt" = "$Le_Domain,$Le_Alt" ] ; then
  1776. _info "Domains not changed."
  1777. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  1778. _info "Add '$(__red '--force')' to force to renew."
  1779. return $RENEW_SKIP
  1780. else
  1781. _info "Domains have changed."
  1782. fi
  1783. fi
  1784. fi
  1785. _savedomainconf "Le_Domain" "$Le_Domain"
  1786. _savedomainconf "Le_Alt" "$Le_Alt"
  1787. _savedomainconf "Le_Webroot" "$Le_Webroot"
  1788. _savedomainconf "Le_PreHook" "$Le_PreHook"
  1789. _savedomainconf "Le_PostHook" "$Le_PostHook"
  1790. _savedomainconf "Le_RenewHook" "$Le_RenewHook"
  1791. _savedomainconf "Le_LocalAddress" "$Le_LocalAddress"
  1792. Le_API="$API"
  1793. _savedomainconf "Le_API" "$Le_API"
  1794. if [ "$Le_Alt" = "$NO_VALUE" ] ; then
  1795. Le_Alt=""
  1796. fi
  1797. if [ "$Le_Keylength" = "$NO_VALUE" ] ; then
  1798. Le_Keylength=""
  1799. fi
  1800. if ! _on_before_issue ; then
  1801. _err "_on_before_issue."
  1802. return 1
  1803. fi
  1804. if ! _regAccount ; then
  1805. _on_issue_err
  1806. return 1
  1807. fi
  1808. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ] ; then
  1809. _info "Signing from existing CSR."
  1810. else
  1811. _key=$(_readdomainconf Le_Keylength)
  1812. _debug "Read key length:$_key"
  1813. if [ ! -f "$CERT_KEY_PATH" ] || [ "$Le_Keylength" != "$_key" ] ; then
  1814. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  1815. _err "Create domain key error."
  1816. _clearup
  1817. _on_issue_err
  1818. return 1
  1819. fi
  1820. fi
  1821. if ! _createcsr "$Le_Domain" "$Le_Alt" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF" ; then
  1822. _err "Create CSR error."
  1823. _clearup
  1824. _on_issue_err
  1825. return 1
  1826. fi
  1827. fi
  1828. _savedomainconf "Le_Keylength" "$Le_Keylength"
  1829. vlist="$Le_Vlist"
  1830. # verify each domain
  1831. _info "Verify each domain"
  1832. sep='#'
  1833. if [ -z "$vlist" ] ; then
  1834. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  1835. _index=1
  1836. _currentRoot=""
  1837. for d in $alldomains
  1838. do
  1839. _info "Getting webroot for domain" $d
  1840. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  1841. _info _w "$_w"
  1842. if [ "$_w" ] ; then
  1843. _currentRoot="$_w"
  1844. fi
  1845. _debug "_currentRoot" "$_currentRoot"
  1846. _index=$(_math $_index + 1)
  1847. vtype="$VTYPE_HTTP"
  1848. if _startswith "$_currentRoot" "dns" ; then
  1849. vtype="$VTYPE_DNS"
  1850. fi
  1851. if [ "$_currentRoot" = "$W_TLS" ] ; then
  1852. vtype="$VTYPE_TLS"
  1853. fi
  1854. _info "Getting new-authz for domain" $d
  1855. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$d")\"}}" ; then
  1856. _err "Can not get domain token."
  1857. _clearup
  1858. _on_issue_err
  1859. return 1
  1860. fi
  1861. if [ ! -z "$code" ] && [ ! "$code" = '201' ] ; then
  1862. _err "new-authz error: $response"
  1863. _clearup
  1864. _on_issue_err
  1865. return 1
  1866. fi
  1867. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  1868. _debug entry "$entry"
  1869. if [ -z "$entry" ] ; then
  1870. _err "Error, can not get domain token $d"
  1871. _clearup
  1872. _on_issue_err
  1873. return 1
  1874. fi
  1875. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  1876. _debug token $token
  1877. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  1878. _debug uri $uri
  1879. keyauthorization="$token.$thumbprint"
  1880. _debug keyauthorization "$keyauthorization"
  1881. if printf "$response" | grep '"status":"valid"' >/dev/null 2>&1 ; then
  1882. _info "$d is already verified, skip."
  1883. keyauthorization=$STATE_VERIFIED
  1884. _debug keyauthorization "$keyauthorization"
  1885. fi
  1886. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  1887. _debug dvlist "$dvlist"
  1888. vlist="$vlist$dvlist,"
  1889. done
  1890. #add entry
  1891. dnsadded=""
  1892. ventries=$(echo "$vlist" | tr ',' ' ' )
  1893. for ventry in $ventries
  1894. do
  1895. d=$(echo $ventry | cut -d $sep -f 1)
  1896. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1897. vtype=$(echo $ventry | cut -d $sep -f 4)
  1898. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1899. if [ "$keyauthorization" = "$STATE_VERIFIED" ] ; then
  1900. _info "$d is already verified, skip $vtype."
  1901. continue
  1902. fi
  1903. if [ "$vtype" = "$VTYPE_DNS" ] ; then
  1904. dnsadded='0'
  1905. txtdomain="_acme-challenge.$d"
  1906. _debug txtdomain "$txtdomain"
  1907. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _urlencode)"
  1908. _debug txt "$txt"
  1909. #dns
  1910. #1. check use api
  1911. d_api=""
  1912. if [ -f "$LE_WORKING_DIR/$d/$_currentRoot" ] ; then
  1913. d_api="$LE_WORKING_DIR/$d/$_currentRoot"
  1914. elif [ -f "$LE_WORKING_DIR/$d/$_currentRoot.sh" ] ; then
  1915. d_api="$LE_WORKING_DIR/$d/$_currentRoot.sh"
  1916. elif [ -f "$LE_WORKING_DIR/$_currentRoot" ] ; then
  1917. d_api="$LE_WORKING_DIR/$_currentRoot"
  1918. elif [ -f "$LE_WORKING_DIR/$_currentRoot.sh" ] ; then
  1919. d_api="$LE_WORKING_DIR/$_currentRoot.sh"
  1920. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot" ] ; then
  1921. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot"
  1922. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot.sh" ] ; then
  1923. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot.sh"
  1924. fi
  1925. _debug d_api "$d_api"
  1926. if [ "$d_api" ] ; then
  1927. _info "Found domain api file: $d_api"
  1928. else
  1929. _err "Add the following TXT record:"
  1930. _err "Domain: '$(__green $txtdomain)'"
  1931. _err "TXT value: '$(__green $txt)'"
  1932. _err "Please be aware that you prepend _acme-challenge. before your domain"
  1933. _err "so the resulting subdomain will be: $txtdomain"
  1934. continue
  1935. fi
  1936. (
  1937. if ! . $d_api ; then
  1938. _err "Load file $d_api error. Please check your api file and try again."
  1939. return 1
  1940. fi
  1941. addcommand="${_currentRoot}_add"
  1942. if ! _exists $addcommand ; then
  1943. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  1944. return 1
  1945. fi
  1946. if ! $addcommand $txtdomain $txt ; then
  1947. _err "Error add txt for domain:$txtdomain"
  1948. return 1
  1949. fi
  1950. )
  1951. if [ "$?" != "0" ] ; then
  1952. _clearup
  1953. _on_issue_err
  1954. return 1
  1955. fi
  1956. dnsadded='1'
  1957. fi
  1958. done
  1959. if [ "$dnsadded" = '0' ] ; then
  1960. _savedomainconf "Le_Vlist" "$vlist"
  1961. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  1962. _err "Please add the TXT records to the domains, and retry again."
  1963. _clearup
  1964. _on_issue_err
  1965. return 1
  1966. fi
  1967. fi
  1968. if [ "$dnsadded" = '1' ] ; then
  1969. if [ -z "$Le_DNSSleep" ] ; then
  1970. Le_DNSSleep=$DEFAULT_DNS_SLEEP
  1971. else
  1972. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  1973. fi
  1974. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  1975. _sleep $Le_DNSSleep
  1976. fi
  1977. _debug "ok, let's start to verify"
  1978. _ncIndex=1
  1979. ventries=$(echo "$vlist" | tr ',' ' ' )
  1980. for ventry in $ventries
  1981. do
  1982. d=$(echo $ventry | cut -d $sep -f 1)
  1983. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1984. uri=$(echo $ventry | cut -d $sep -f 3)
  1985. vtype=$(echo $ventry | cut -d $sep -f 4)
  1986. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1987. if [ "$keyauthorization" = "$STATE_VERIFIED" ] ; then
  1988. _info "$d is already verified, skip $vtype."
  1989. continue
  1990. fi
  1991. _info "Verifying:$d"
  1992. _debug "d" "$d"
  1993. _debug "keyauthorization" "$keyauthorization"
  1994. _debug "uri" "$uri"
  1995. removelevel=""
  1996. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  1997. _debug "_currentRoot" "$_currentRoot"
  1998. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  1999. if [ "$_currentRoot" = "$NO_VALUE" ] ; then
  2000. _info "Standalone mode server"
  2001. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex" )"
  2002. _ncIndex="$(_math $_ncIndex + 1)"
  2003. _startserver "$keyauthorization" "$_ncaddr" &
  2004. if [ "$?" != "0" ] ; then
  2005. _clearup
  2006. _on_issue_err
  2007. return 1
  2008. fi
  2009. serverproc="$!"
  2010. sleep 2
  2011. _debug serverproc $serverproc
  2012. else
  2013. if [ "$_currentRoot" = "apache" ] ; then
  2014. wellknown_path="$ACME_DIR"
  2015. else
  2016. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  2017. if [ ! -d "$_currentRoot/.well-known" ] ; then
  2018. removelevel='1'
  2019. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ] ; then
  2020. removelevel='2'
  2021. else
  2022. removelevel='3'
  2023. fi
  2024. fi
  2025. _debug wellknown_path "$wellknown_path"
  2026. _debug "writing token:$token to $wellknown_path/$token"
  2027. mkdir -p "$wellknown_path"
  2028. printf "%s" "$keyauthorization" > "$wellknown_path/$token"
  2029. if [ ! "$usingApache" ] ; then
  2030. if webroot_owner=$(_stat $_currentRoot) ; then
  2031. _debug "Changing owner/group of .well-known to $webroot_owner"
  2032. chown -R $webroot_owner "$_currentRoot/.well-known"
  2033. else
  2034. _debug "not chaning owner/group of webroot";
  2035. fi
  2036. fi
  2037. fi
  2038. elif [ "$vtype" = "$VTYPE_TLS" ] ; then
  2039. #create A
  2040. #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
  2041. #_debug2 _hash_A "$_hash_A"
  2042. #_x="$(echo $_hash_A | cut -c 1-32)"
  2043. #_debug2 _x "$_x"
  2044. #_y="$(echo $_hash_A | cut -c 33-64)"
  2045. #_debug2 _y "$_y"
  2046. #_SAN_A="$_x.$_y.token.acme.invalid"
  2047. #_debug2 _SAN_A "$_SAN_A"
  2048. #create B
  2049. _hash_B="$(printf "%s" $keyauthorization | _digest "sha256" "hex" )"
  2050. _debug2 _hash_B "$_hash_B"
  2051. _x="$(echo $_hash_B | cut -c 1-32)"
  2052. _debug2 _x "$_x"
  2053. _y="$(echo $_hash_B | cut -c 33-64)"
  2054. _debug2 _y "$_y"
  2055. #_SAN_B="$_x.$_y.ka.acme.invalid"
  2056. _SAN_B="$_x.$_y.acme.invalid"
  2057. _debug2 _SAN_B "$_SAN_B"
  2058. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex" )"
  2059. _ncIndex="$(_math $_ncIndex + 1)"
  2060. if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" "$_ncaddr"; then
  2061. _err "Start tls server error."
  2062. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2063. _clearup
  2064. _on_issue_err
  2065. return 1
  2066. fi
  2067. fi
  2068. if ! _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}" ; then
  2069. _err "$d:Can not get challenge: $response"
  2070. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2071. _clearup
  2072. _on_issue_err
  2073. return 1
  2074. fi
  2075. if [ ! -z "$code" ] && [ ! "$code" = '202' ] ; then
  2076. _err "$d:Challenge error: $response"
  2077. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2078. _clearup
  2079. _on_issue_err
  2080. return 1
  2081. fi
  2082. waittimes=0
  2083. if [ -z "$MAX_RETRY_TIMES" ] ; then
  2084. MAX_RETRY_TIMES=30
  2085. fi
  2086. while true ; do
  2087. waittimes=$(_math $waittimes + 1)
  2088. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ] ; then
  2089. _err "$d:Timeout"
  2090. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2091. _clearup
  2092. _on_issue_err
  2093. return 1
  2094. fi
  2095. _debug "sleep 5 secs to verify"
  2096. sleep 5
  2097. _debug "checking"
  2098. response="$(_get $uri)"
  2099. if [ "$?" != "0" ] ; then
  2100. _err "$d:Verify error:$response"
  2101. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2102. _clearup
  2103. _on_issue_err
  2104. return 1
  2105. fi
  2106. _debug2 original "$response"
  2107. response="$(echo "$response" | _normalizeJson )"
  2108. _debug2 response "$response"
  2109. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  2110. if [ "$status" = "valid" ] ; then
  2111. _info "Success"
  2112. _stopserver $serverproc
  2113. serverproc=""
  2114. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2115. break;
  2116. fi
  2117. if [ "$status" = "invalid" ] ; then
  2118. error="$(echo "$response" | tr -d "\r\n" | _egrep_o '"error":\{[^\}]*')"
  2119. _debug2 error "$error"
  2120. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  2121. _debug2 errordetail "$errordetail"
  2122. if [ "$errordetail" ] ; then
  2123. _err "$d:Verify error:$errordetail"
  2124. else
  2125. _err "$d:Verify error:$error"
  2126. fi
  2127. if [ "$DEBUG" ] ; then
  2128. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  2129. _debug "Debug: get token url."
  2130. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  2131. fi
  2132. fi
  2133. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2134. _clearup
  2135. _on_issue_err
  2136. return 1;
  2137. fi
  2138. if [ "$status" = "pending" ] ; then
  2139. _info "Pending"
  2140. else
  2141. _err "$d:Verify error:$response"
  2142. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2143. _clearup
  2144. _on_issue_err
  2145. return 1
  2146. fi
  2147. done
  2148. done
  2149. _clearup
  2150. _info "Verify finished, start to sign."
  2151. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  2152. if ! _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64" ; then
  2153. _err "Sign failed."
  2154. _on_issue_err
  2155. return 1
  2156. fi
  2157. _rcert="$response"
  2158. Le_LinkCert="$(grep -i '^Location.*$' $HTTP_HEADER | _head_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  2159. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  2160. if [ "$Le_LinkCert" ] ; then
  2161. echo "$BEGIN_CERT" > "$CERT_PATH"
  2162. if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  2163. _debug "Get cert failed. Let's try last response."
  2164. printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  2165. fi
  2166. echo "$END_CERT" >> "$CERT_PATH"
  2167. _info "$(__green "Cert success.")"
  2168. cat "$CERT_PATH"
  2169. _info "Your cert is in $( __green " $CERT_PATH ")"
  2170. if [ -f "$CERT_KEY_PATH" ] ; then
  2171. _info "Your cert key is in $( __green " $CERT_KEY_PATH ")"
  2172. fi
  2173. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  2174. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ] ; then
  2175. USER_PATH="$PATH"
  2176. _saveaccountconf "USER_PATH" "$USER_PATH"
  2177. fi
  2178. fi
  2179. if [ -z "$Le_LinkCert" ] ; then
  2180. response="$(echo $response | _dbase64 "multiline" | _normalizeJson )"
  2181. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  2182. _on_issue_err
  2183. return 1
  2184. fi
  2185. _cleardomainconf "Le_Vlist"
  2186. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | _head_n 1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  2187. if ! _contains "$Le_LinkIssuer" ":" ; then
  2188. Le_LinkIssuer="$API$Le_LinkIssuer"
  2189. fi
  2190. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  2191. if [ "$Le_LinkIssuer" ] ; then
  2192. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  2193. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  2194. echo "$END_CERT" >> "$CA_CERT_PATH"
  2195. _info "The intermediate CA cert is in $( __green " $CA_CERT_PATH ")"
  2196. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  2197. _info "And the full chain certs is there: $( __green " $CERT_FULLCHAIN_PATH ")"
  2198. fi
  2199. Le_CertCreateTime=$(_time)
  2200. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  2201. Le_CertCreateTimeStr=$(date -u )
  2202. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  2203. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ] ; then
  2204. Le_RenewalDays=$MAX_RENEW
  2205. else
  2206. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  2207. fi
  2208. if [ "$CA_BUNDLE" ] ; then
  2209. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  2210. else
  2211. _clearaccountconf "CA_BUNDLE"
  2212. fi
  2213. if [ "$HTTPS_INSECURE" ] ; then
  2214. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  2215. else
  2216. _clearaccountconf "HTTPS_INSECURE"
  2217. fi
  2218. if [ "$Le_Listen_V4" ] ; then
  2219. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  2220. _cleardomainconf Le_Listen_V6
  2221. elif [ "$Le_Listen_V6" ] ; then
  2222. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  2223. _cleardomainconf Le_Listen_V4
  2224. fi
  2225. Le_NextRenewTime=$(_math $Le_CertCreateTime + $Le_RenewalDays \* 24 \* 60 \* 60)
  2226. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  2227. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  2228. Le_NextRenewTime=$(_math $Le_NextRenewTime - 86400)
  2229. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  2230. _on_issue_success
  2231. if [ "$Le_RealCertPath$Le_RealKeyPath$Le_RealCACertPath$Le_ReloadCmd$Le_RealFullChainPath" ] ; then
  2232. _installcert
  2233. fi
  2234. }
  2235. #domain [isEcc]
  2236. renew() {
  2237. Le_Domain="$1"
  2238. if [ -z "$Le_Domain" ] ; then
  2239. _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
  2240. return 1
  2241. fi
  2242. _isEcc="$2"
  2243. _initpath $Le_Domain "$_isEcc"
  2244. _info "$(__green "Renew: '$Le_Domain'")"
  2245. if [ ! -f "$DOMAIN_CONF" ] ; then
  2246. _info "'$Le_Domain' is not a issued domain, skip."
  2247. return 0;
  2248. fi
  2249. if [ "$Le_RenewalDays" ] ; then
  2250. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  2251. fi
  2252. . "$DOMAIN_CONF"
  2253. if [ "$Le_API" ] ; then
  2254. API="$Le_API"
  2255. fi
  2256. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ] ; then
  2257. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  2258. _info "Add '$(__red '--force')' to force to renew."
  2259. return $RENEW_SKIP
  2260. fi
  2261. IS_RENEW="1"
  2262. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" "$Le_PreHook" "$Le_PostHook" "$Le_RenewHook" "$Le_LocalAddress"
  2263. res=$?
  2264. IS_RENEW=""
  2265. return $res
  2266. }
  2267. #renewAll [stopRenewOnError]
  2268. renewAll() {
  2269. _initpath
  2270. _stopRenewOnError="$1"
  2271. _debug "_stopRenewOnError" "$_stopRenewOnError"
  2272. _ret="0"
  2273. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  2274. d=$(echo $d | cut -d '/' -f 1)
  2275. (
  2276. if _endswith $d "$ECC_SUFFIX" ; then
  2277. _isEcc=$(echo $d | cut -d "$ECC_SEP" -f 2)
  2278. d=$(echo $d | cut -d "$ECC_SEP" -f 1)
  2279. fi
  2280. renew "$d" "$_isEcc"
  2281. )
  2282. rc="$?"
  2283. _debug "Return code: $rc"
  2284. if [ "$rc" != "0" ] ; then
  2285. if [ "$rc" = "$RENEW_SKIP" ] ; then
  2286. _info "Skipped $d"
  2287. elif [ "$_stopRenewOnError" ] ; then
  2288. _err "Error renew $d, stop now."
  2289. return $rc
  2290. else
  2291. _ret="$rc"
  2292. _err "Error renew $d, Go ahead to next one."
  2293. fi
  2294. fi
  2295. done
  2296. return $_ret
  2297. }
  2298. #csr webroot
  2299. signcsr(){
  2300. _csrfile="$1"
  2301. _csrW="$2"
  2302. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  2303. _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
  2304. return 1
  2305. fi
  2306. _initpath
  2307. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2308. if [ "$?" != "0" ] ; then
  2309. _err "Can not read subject from csr: $_csrfile"
  2310. return 1
  2311. fi
  2312. _debug _csrsubj "$_csrsubj"
  2313. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2314. if [ "$?" != "0" ] ; then
  2315. _err "Can not read domain list from csr: $_csrfile"
  2316. return 1
  2317. fi
  2318. _debug "_csrdomainlist" "$_csrdomainlist"
  2319. if [ -z "$_csrsubj" ] ; then
  2320. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  2321. _debug _csrsubj "$_csrsubj"
  2322. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  2323. _debug "_csrdomainlist" "$_csrdomainlist"
  2324. fi
  2325. if [ -z "$_csrsubj" ] ; then
  2326. _err "Can not read subject from csr: $_csrfile"
  2327. return 1
  2328. fi
  2329. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2330. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ] ; then
  2331. _err "Can not read key length from csr: $_csrfile"
  2332. return 1
  2333. fi
  2334. _initpath "$_csrsubj" "$_csrkeylength"
  2335. mkdir -p "$DOMAIN_PATH"
  2336. _info "Copy csr to: $CSR_PATH"
  2337. cp "$_csrfile" "$CSR_PATH"
  2338. issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength"
  2339. }
  2340. showcsr() {
  2341. _csrfile="$1"
  2342. _csrd="$2"
  2343. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  2344. _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
  2345. return 1
  2346. fi
  2347. _initpath
  2348. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2349. if [ "$?" != "0" ] || [ -z "$_csrsubj" ] ; then
  2350. _err "Can not read subject from csr: $_csrfile"
  2351. return 1
  2352. fi
  2353. _info "Subject=$_csrsubj"
  2354. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2355. if [ "$?" != "0" ] ; then
  2356. _err "Can not read domain list from csr: $_csrfile"
  2357. return 1
  2358. fi
  2359. _debug "_csrdomainlist" "$_csrdomainlist"
  2360. _info "SubjectAltNames=$_csrdomainlist"
  2361. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2362. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ] ; then
  2363. _err "Can not read key length from csr: $_csrfile"
  2364. return 1
  2365. fi
  2366. _info "KeyLength=$_csrkeylength"
  2367. }
  2368. list() {
  2369. _raw="$1"
  2370. _initpath
  2371. _sep="|"
  2372. if [ "$_raw" ] ; then
  2373. printf "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew\n"
  2374. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  2375. d=$(echo $d | cut -d '/' -f 1)
  2376. (
  2377. if _endswith $d "$ECC_SUFFIX" ; then
  2378. _isEcc=$(echo $d | cut -d "$ECC_SEP" -f 2)
  2379. d=$(echo $d | cut -d "$ECC_SEP" -f 1)
  2380. fi
  2381. _initpath $d "$_isEcc"
  2382. if [ -f "$DOMAIN_CONF" ] ; then
  2383. . "$DOMAIN_CONF"
  2384. printf "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr\n"
  2385. fi
  2386. )
  2387. done
  2388. else
  2389. if _exists column ; then
  2390. list "raw" | column -t -s "$_sep"
  2391. else
  2392. list "raw" | tr "$_sep" '\t'
  2393. fi
  2394. fi
  2395. }
  2396. installcert() {
  2397. Le_Domain="$1"
  2398. if [ -z "$Le_Domain" ] ; then
  2399. _usage "Usage: $PROJECT_ENTRY --installcert -d domain.com [--ecc] [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  2400. return 1
  2401. fi
  2402. Le_RealCertPath="$2"
  2403. Le_RealKeyPath="$3"
  2404. Le_RealCACertPath="$4"
  2405. Le_ReloadCmd="$5"
  2406. Le_RealFullChainPath="$6"
  2407. _isEcc="$7"
  2408. _initpath $Le_Domain "$_isEcc"
  2409. if [ ! -d "$DOMAIN_PATH" ] ; then
  2410. _err "Domain is not valid:'$Le_Domain'"
  2411. return 1
  2412. fi
  2413. _installcert
  2414. }
  2415. _installcert() {
  2416. _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
  2417. _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
  2418. _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
  2419. _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
  2420. _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
  2421. if [ "$Le_RealCertPath" = "$NO_VALUE" ] ; then
  2422. Le_RealCertPath=""
  2423. fi
  2424. if [ "$Le_RealKeyPath" = "$NO_VALUE" ] ; then
  2425. Le_RealKeyPath=""
  2426. fi
  2427. if [ "$Le_RealCACertPath" = "$NO_VALUE" ] ; then
  2428. Le_RealCACertPath=""
  2429. fi
  2430. if [ "$Le_ReloadCmd" = "$NO_VALUE" ] ; then
  2431. Le_ReloadCmd=""
  2432. fi
  2433. if [ "$Le_RealFullChainPath" = "$NO_VALUE" ] ; then
  2434. Le_RealFullChainPath=""
  2435. fi
  2436. _installed="0"
  2437. if [ "$Le_RealCertPath" ] ; then
  2438. _installed=1
  2439. _info "Installing cert to:$Le_RealCertPath"
  2440. if [ -f "$Le_RealCertPath" ] && [ ! "$IS_RENEW" ] ; then
  2441. cp "$Le_RealCertPath" "$Le_RealCertPath".bak
  2442. fi
  2443. cat "$CERT_PATH" > "$Le_RealCertPath"
  2444. fi
  2445. if [ "$Le_RealCACertPath" ] ; then
  2446. _installed=1
  2447. _info "Installing CA to:$Le_RealCACertPath"
  2448. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ] ; then
  2449. echo "" >> "$Le_RealCACertPath"
  2450. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  2451. else
  2452. if [ -f "$Le_RealCACertPath" ] && [ ! "$IS_RENEW" ] ; then
  2453. cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  2454. fi
  2455. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  2456. fi
  2457. fi
  2458. if [ "$Le_RealKeyPath" ] ; then
  2459. _installed=1
  2460. _info "Installing key to:$Le_RealKeyPath"
  2461. if [ -f "$Le_RealKeyPath" ] && [ ! "$IS_RENEW" ] ; then
  2462. cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  2463. fi
  2464. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  2465. fi
  2466. if [ "$Le_RealFullChainPath" ] ; then
  2467. _installed=1
  2468. _info "Installing full chain to:$Le_RealFullChainPath"
  2469. if [ -f "$Le_RealFullChainPath" ] && [ ! "$IS_RENEW" ] ; then
  2470. cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  2471. fi
  2472. cat "$CERT_FULLCHAIN_PATH" > "$Le_RealFullChainPath"
  2473. fi
  2474. if [ "$Le_ReloadCmd" ] ; then
  2475. _installed=1
  2476. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  2477. if (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd") ; then
  2478. _info "$(__green "Reload success")"
  2479. else
  2480. _err "Reload error for :$Le_Domain"
  2481. fi
  2482. fi
  2483. }
  2484. installcronjob() {
  2485. _initpath
  2486. if ! _exists "crontab" ; then
  2487. _err "crontab doesn't exist, so, we can not install cron jobs."
  2488. _err "All your certs will not be renewed automatically."
  2489. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  2490. return 1
  2491. fi
  2492. _info "Installing cron job"
  2493. if ! crontab -l | grep "$PROJECT_ENTRY --cron" ; then
  2494. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ] ; then
  2495. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  2496. else
  2497. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  2498. return 1
  2499. fi
  2500. if _exists uname && uname -a | grep solaris >/dev/null ; then
  2501. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab --
  2502. else
  2503. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab -
  2504. fi
  2505. fi
  2506. if [ "$?" != "0" ] ; then
  2507. _err "Install cron job failed. You need to manually renew your certs."
  2508. _err "Or you can add cronjob by yourself:"
  2509. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2510. return 1
  2511. fi
  2512. }
  2513. uninstallcronjob() {
  2514. if ! _exists "crontab" ; then
  2515. return
  2516. fi
  2517. _info "Removing cron job"
  2518. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  2519. if [ "$cr" ] ; then
  2520. if _exists uname && uname -a | grep solaris >/dev/null ; then
  2521. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab --
  2522. else
  2523. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  2524. fi
  2525. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  2526. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  2527. fi
  2528. _initpath
  2529. }
  2530. revoke() {
  2531. Le_Domain="$1"
  2532. if [ -z "$Le_Domain" ] ; then
  2533. _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  2534. return 1
  2535. fi
  2536. _isEcc="$2"
  2537. _initpath $Le_Domain "$_isEcc"
  2538. if [ ! -f "$DOMAIN_CONF" ] ; then
  2539. _err "$Le_Domain is not a issued domain, skip."
  2540. return 1;
  2541. fi
  2542. if [ ! -f "$CERT_PATH" ] ; then
  2543. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  2544. return 1
  2545. fi
  2546. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}"| tr -d "\r\n" | _urlencode)"
  2547. if [ -z "$cert" ] ; then
  2548. _err "Cert for $Le_Domain is empty found, skip."
  2549. return 1
  2550. fi
  2551. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  2552. uri="$API/acme/revoke-cert"
  2553. _info "Try domain key first."
  2554. if _send_signed_request $uri "$data" "" "$CERT_KEY_PATH"; then
  2555. if [ -z "$response" ] ; then
  2556. _info "Revoke success."
  2557. rm -f $CERT_PATH
  2558. return 0
  2559. else
  2560. _err "Revoke error by domain key."
  2561. _err "$response"
  2562. fi
  2563. fi
  2564. _info "Then try account key."
  2565. if _send_signed_request $uri "$data" "" "$ACCOUNT_KEY_PATH" ; then
  2566. if [ -z "$response" ] ; then
  2567. _info "Revoke success."
  2568. rm -f $CERT_PATH
  2569. return 0
  2570. else
  2571. _err "Revoke error."
  2572. _debug "$response"
  2573. fi
  2574. fi
  2575. return 1
  2576. }
  2577. #domain vtype
  2578. _deactivate() {
  2579. _d_domain="$1"
  2580. _d_type="$2"
  2581. _initpath
  2582. _d_i=0
  2583. _d_max_retry=9
  2584. while [ "$_d_i" -lt "$_d_max_retry" ] ;
  2585. do
  2586. _info "Deactivate: $_d_domain"
  2587. _d_i="$(_math $_d_i + 1)"
  2588. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_d_domain")\"}}" ; then
  2589. _err "Can not get domain token."
  2590. return 1
  2591. fi
  2592. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2593. _debug "authzUri" "$authzUri"
  2594. if [ ! -z "$code" ] && [ ! "$code" = '201' ] ; then
  2595. _err "new-authz error: $response"
  2596. return 1
  2597. fi
  2598. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"status":"valid","uri"[^\}]*')"
  2599. _debug entry "$entry"
  2600. if [ -z "$entry" ] ; then
  2601. _info "No more valid entry found."
  2602. break
  2603. fi
  2604. _vtype="$(printf "%s\n" "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  2605. _debug _vtype $_vtype
  2606. _info "Found $_vtype"
  2607. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  2608. _debug uri $uri
  2609. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ] ; then
  2610. _info "Skip $_vtype"
  2611. continue
  2612. fi
  2613. _info "Deactivate: $_vtype"
  2614. if ! _send_signed_request "$authzUri" "{\"resource\": \"authz\", \"status\":\"deactivated\"}" ; then
  2615. _err "Can not deactivate $_vtype."
  2616. return 1
  2617. fi
  2618. _info "Deactivate: $_vtype success."
  2619. done
  2620. _debug "$_d_i"
  2621. if [ "$_d_i" -lt "$_d_max_retry" ] ; then
  2622. _info "Deactivated success!"
  2623. else
  2624. _err "Deactivate failed."
  2625. fi
  2626. }
  2627. deactivate() {
  2628. _d_domain_list="$1"
  2629. _d_type="$2"
  2630. _initpath
  2631. _debug _d_domain_list "$_d_domain_list"
  2632. if [ -z "$(echo $_d_domain_list | cut -d , -f 1 )" ] ; then
  2633. _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
  2634. return 1
  2635. fi
  2636. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' ' ) ;
  2637. do
  2638. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ] ; then
  2639. continue
  2640. fi
  2641. if ! _deactivate "$_d_dm" $_d_type ; then
  2642. return 1
  2643. fi
  2644. done
  2645. }
  2646. # Detect profile file if not specified as environment variable
  2647. _detect_profile() {
  2648. if [ -n "$PROFILE" -a -f "$PROFILE" ] ; then
  2649. echo "$PROFILE"
  2650. return
  2651. fi
  2652. DETECTED_PROFILE=''
  2653. SHELLTYPE="$(basename "/$SHELL")"
  2654. if [ "$SHELLTYPE" = "bash" ] ; then
  2655. if [ -f "$HOME/.bashrc" ] ; then
  2656. DETECTED_PROFILE="$HOME/.bashrc"
  2657. elif [ -f "$HOME/.bash_profile" ] ; then
  2658. DETECTED_PROFILE="$HOME/.bash_profile"
  2659. fi
  2660. elif [ "$SHELLTYPE" = "zsh" ] ; then
  2661. DETECTED_PROFILE="$HOME/.zshrc"
  2662. fi
  2663. if [ -z "$DETECTED_PROFILE" ] ; then
  2664. if [ -f "$HOME/.profile" ] ; then
  2665. DETECTED_PROFILE="$HOME/.profile"
  2666. elif [ -f "$HOME/.bashrc" ] ; then
  2667. DETECTED_PROFILE="$HOME/.bashrc"
  2668. elif [ -f "$HOME/.bash_profile" ] ; then
  2669. DETECTED_PROFILE="$HOME/.bash_profile"
  2670. elif [ -f "$HOME/.zshrc" ] ; then
  2671. DETECTED_PROFILE="$HOME/.zshrc"
  2672. fi
  2673. fi
  2674. if [ ! -z "$DETECTED_PROFILE" ] ; then
  2675. echo "$DETECTED_PROFILE"
  2676. fi
  2677. }
  2678. _initconf() {
  2679. _initpath
  2680. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  2681. echo "#ACCOUNT_CONF_PATH=xxxx
  2682. #Account configurations:
  2683. #Here are the supported macros, uncomment them to make them take effect.
  2684. #ACCOUNT_EMAIL=aaa@example.com # the account email used to register account.
  2685. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  2686. #CERT_HOME=\"/path/to/cert/home\"
  2687. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  2688. #LOG_LEVEL=1
  2689. #AUTO_UPGRADE=\"1\"
  2690. #STAGE=1 # Use the staging api
  2691. #FORCE=1 # Force to issue cert
  2692. #DEBUG=1 # Debug mode
  2693. #USER_AGENT=\"$USER_AGENT\"
  2694. #USER_PATH=""
  2695. #dns api
  2696. #######################
  2697. #Cloudflare:
  2698. #api key
  2699. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  2700. #account email
  2701. #CF_Email=\"xxxx@sss.com\"
  2702. #######################
  2703. #Dnspod.cn:
  2704. #api key id
  2705. #DP_Id=\"1234\"
  2706. #api key
  2707. #DP_Key=\"sADDsdasdgdsf\"
  2708. #######################
  2709. #Cloudxns.com:
  2710. #CX_Key=\"1234\"
  2711. #
  2712. #CX_Secret=\"sADDsdasdgdsf\"
  2713. #######################
  2714. #Godaddy.com:
  2715. #GD_Key=\"sdfdsgdgdfdasfds\"
  2716. #
  2717. #GD_Secret=\"sADDsdasdfsdfdssdgdsf\"
  2718. #######################
  2719. #PowerDNS:
  2720. #PDNS_Url=\"http://ns.example.com:8081\"
  2721. #PDNS_ServerId=\"localhost\"
  2722. #PDNS_Token=\"0123456789ABCDEF\"
  2723. #PDNS_Ttl=60
  2724. " > $ACCOUNT_CONF_PATH
  2725. fi
  2726. }
  2727. # nocron
  2728. _precheck() {
  2729. _nocron="$1"
  2730. if ! _exists "curl" && ! _exists "wget"; then
  2731. _err "Please install curl or wget first, we need to access http resources."
  2732. return 1
  2733. fi
  2734. if [ -z "$_nocron" ] ; then
  2735. if ! _exists "crontab" ; then
  2736. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  2737. _err "We need to set cron job to renew the certs automatically."
  2738. _err "Otherwise, your certs will not be able to be renewed automatically."
  2739. if [ -z "$FORCE" ] ; then
  2740. _err "Please add '--force' and try install again to go without crontab."
  2741. _err "./$PROJECT_ENTRY --install --force"
  2742. return 1
  2743. fi
  2744. fi
  2745. fi
  2746. if ! _exists "openssl" ; then
  2747. _err "Please install openssl first."
  2748. _err "We need openssl to generate keys."
  2749. return 1
  2750. fi
  2751. if ! _exists "nc" ; then
  2752. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  2753. _err "We use nc for standalone server if you use standalone mode."
  2754. _err "If you don't use standalone mode, just ignore this warning."
  2755. fi
  2756. return 0
  2757. }
  2758. _setShebang() {
  2759. _file="$1"
  2760. _shebang="$2"
  2761. if [ -z "$_shebang" ] ; then
  2762. _usage "Usage: file shebang"
  2763. return 1
  2764. fi
  2765. cp "$_file" "$_file.tmp"
  2766. echo "$_shebang" > "$_file"
  2767. sed -n 2,99999p "$_file.tmp" >> "$_file"
  2768. rm -f "$_file.tmp"
  2769. }
  2770. _installalias() {
  2771. _initpath
  2772. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  2773. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ] ; then
  2774. echo "$(cat $_envfile)" | sed "s|^LE_WORKING_DIR.*$||" > "$_envfile"
  2775. echo "$(cat $_envfile)" | sed "s|^alias le.*$||" > "$_envfile"
  2776. echo "$(cat $_envfile)" | sed "s|^alias le.sh.*$||" > "$_envfile"
  2777. fi
  2778. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  2779. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  2780. _profile="$(_detect_profile)"
  2781. if [ "$_profile" ] ; then
  2782. _debug "Found profile: $_profile"
  2783. _info "Installing alias to '$_profile'"
  2784. _setopt "$_profile" ". \"$_envfile\""
  2785. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  2786. else
  2787. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  2788. fi
  2789. #for csh
  2790. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  2791. _csh_profile="$HOME/.cshrc"
  2792. if [ -f "$_csh_profile" ] ; then
  2793. _info "Installing alias to '$_csh_profile'"
  2794. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  2795. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  2796. _setopt "$_csh_profile" "source \"$_cshfile\""
  2797. fi
  2798. #for tcsh
  2799. _tcsh_profile="$HOME/.tcshrc"
  2800. if [ -f "$_tcsh_profile" ] ; then
  2801. _info "Installing alias to '$_tcsh_profile'"
  2802. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  2803. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  2804. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  2805. fi
  2806. }
  2807. # nocron
  2808. install() {
  2809. if [ -z "$LE_WORKING_DIR" ] ; then
  2810. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  2811. fi
  2812. _nocron="$1"
  2813. if ! _initpath ; then
  2814. _err "Install failed."
  2815. return 1
  2816. fi
  2817. if [ "$_nocron" ] ; then
  2818. _debug "Skip install cron job"
  2819. fi
  2820. if ! _precheck "$_nocron" ; then
  2821. _err "Pre-check failed, can not install."
  2822. return 1
  2823. fi
  2824. #convert from le
  2825. if [ -d "$HOME/.le" ] ; then
  2826. for envfile in "le.env" "le.sh.env"
  2827. do
  2828. if [ -f "$HOME/.le/$envfile" ] ; then
  2829. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null ; then
  2830. _upgrading="1"
  2831. _info "You are upgrading from le.sh"
  2832. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  2833. mv "$HOME/.le" "$LE_WORKING_DIR"
  2834. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  2835. break;
  2836. fi
  2837. fi
  2838. done
  2839. fi
  2840. _info "Installing to $LE_WORKING_DIR"
  2841. if ! mkdir -p "$LE_WORKING_DIR" ; then
  2842. _err "Can not create working dir: $LE_WORKING_DIR"
  2843. return 1
  2844. fi
  2845. chmod 700 "$LE_WORKING_DIR"
  2846. cp $PROJECT_ENTRY "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  2847. if [ "$?" != "0" ] ; then
  2848. _err "Install failed, can not copy $PROJECT_ENTRY"
  2849. return 1
  2850. fi
  2851. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  2852. _installalias
  2853. if [ -d "dnsapi" ] ; then
  2854. mkdir -p $LE_WORKING_DIR/dnsapi
  2855. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  2856. fi
  2857. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  2858. _initconf
  2859. fi
  2860. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ] ; then
  2861. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  2862. fi
  2863. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ] ; then
  2864. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  2865. fi
  2866. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ] ; then
  2867. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  2868. fi
  2869. if [ -z "$_nocron" ] ; then
  2870. installcronjob
  2871. fi
  2872. if [ -z "$NO_DETECT_SH" ] ; then
  2873. #Modify shebang
  2874. if _exists bash ; then
  2875. _info "Good, bash is found, so change the shebang to use bash as prefered."
  2876. _shebang='#!/usr/bin/env bash'
  2877. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  2878. if [ -d "$LE_WORKING_DIR/dnsapi" ] ; then
  2879. for _apifile in $(ls "$LE_WORKING_DIR/dnsapi/"*.sh) ; do
  2880. _setShebang "$_apifile" "$_shebang"
  2881. done
  2882. fi
  2883. fi
  2884. fi
  2885. _info OK
  2886. }
  2887. # nocron
  2888. uninstall() {
  2889. _nocron="$1"
  2890. if [ -z "$_nocron" ] ; then
  2891. uninstallcronjob
  2892. fi
  2893. _initpath
  2894. _uninstallalias
  2895. rm -f $LE_WORKING_DIR/$PROJECT_ENTRY
  2896. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  2897. }
  2898. _uninstallalias() {
  2899. _initpath
  2900. _profile="$(_detect_profile)"
  2901. if [ "$_profile" ] ; then
  2902. _info "Uninstalling alias from: '$_profile'"
  2903. text="$(cat $_profile)"
  2904. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" > "$_profile"
  2905. fi
  2906. _csh_profile="$HOME/.cshrc"
  2907. if [ -f "$_csh_profile" ] ; then
  2908. _info "Uninstalling alias from: '$_csh_profile'"
  2909. text="$(cat $_csh_profile)"
  2910. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" > "$_csh_profile"
  2911. fi
  2912. _tcsh_profile="$HOME/.tcshrc"
  2913. if [ -f "$_tcsh_profile" ] ; then
  2914. _info "Uninstalling alias from: '$_csh_profile'"
  2915. text="$(cat $_tcsh_profile)"
  2916. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" > "$_tcsh_profile"
  2917. fi
  2918. }
  2919. cron() {
  2920. IN_CRON=1
  2921. _initpath
  2922. if [ "$AUTO_UPGRADE" = "1" ] ; then
  2923. export LE_WORKING_DIR
  2924. (
  2925. if ! upgrade ; then
  2926. _err "Cron:Upgrade failed!"
  2927. return 1
  2928. fi
  2929. )
  2930. . $LE_WORKING_DIR/$PROJECT_ENTRY >/dev/null
  2931. if [ -t 1 ] ; then
  2932. __INTERACTIVE="1"
  2933. fi
  2934. _info "Auto upgraded to: $VER"
  2935. fi
  2936. renewAll
  2937. _ret="$?"
  2938. IN_CRON=""
  2939. exit $_ret
  2940. }
  2941. version() {
  2942. echo "$PROJECT"
  2943. echo "v$VER"
  2944. }
  2945. showhelp() {
  2946. _initpath
  2947. version
  2948. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  2949. Commands:
  2950. --help, -h Show this help message.
  2951. --version, -v Show version info.
  2952. --install Install $PROJECT_NAME to your system.
  2953. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  2954. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT .
  2955. --issue Issue a cert.
  2956. --signcsr Issue a cert from an existing csr.
  2957. --installcert Install the issued cert to apache/nginx or any other server.
  2958. --renew, -r Renew a cert.
  2959. --renewAll Renew all the certs.
  2960. --revoke Revoke a cert.
  2961. --list List all the certs.
  2962. --showcsr Show the content of a csr.
  2963. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  2964. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  2965. --cron Run cron job to renew all the certs.
  2966. --toPkcs Export the certificate and key to a pfx file.
  2967. --updateaccount Update account info.
  2968. --registeraccount Register account key.
  2969. --createAccountKey, -cak Create an account private key, professional use.
  2970. --createDomainKey, -cdk Create an domain private key, professional use.
  2971. --createCSR, -ccsr Create CSR , professional use.
  2972. --deactivate Deactivate the domain authz, professional use.
  2973. Parameters:
  2974. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  2975. --force, -f Used to force to install or force to renew a cert immediately.
  2976. --staging, --test Use staging server, just for test.
  2977. --debug Output debug info.
  2978. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  2979. --standalone Use standalone mode.
  2980. --tls Use standalone tls mode.
  2981. --apache Use apache mode.
  2982. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  2983. --dnssleep [$DEFAULT_DNS_SLEEP] The time in seconds to wait for all the txt records to take effect in dns api mode. Default $DEFAULT_DNS_SLEEP seconds.
  2984. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  2985. --accountkeylength, -ak [2048] Specifies the account key length.
  2986. --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
  2987. --log-level 1|2 Specifies the log level, default is 1.
  2988. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  2989. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  2990. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  2991. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  2992. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  2993. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  2994. --accountconf Specifies a customized account config file.
  2995. --home Specifies the home dir for $PROJECT_NAME .
  2996. --certhome Specifies the home dir to save all the certs, only valid for '--install' command.
  2997. --useragent Specifies the user agent string. it will be saved for future use too.
  2998. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  2999. --accountkey Specifies the account key path, Only valid for the '--install' command.
  3000. --days Specifies the days to renew the cert when using '--issue' command. The max value is $MAX_RENEW days.
  3001. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3002. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3003. --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  3004. --listraw Only used for '--list' command, list the certs in raw format.
  3005. --stopRenewOnError, -se Only valid for '--renewall' command. Stop if one cert has error in renewal.
  3006. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  3007. --ca-bundle Specifices the path to the CA certificate bundle to verify api server's certificate.
  3008. --nocron Only valid for '--install' command, which means: do not install the default cron job. In this case, the certs will not be renewed automatically.
  3009. --ecc Specifies to use the ECC cert. Valid for '--installcert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  3010. --csr Specifies the input csr.
  3011. --pre-hook Command to be run before obtaining any certificates.
  3012. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obain/renew is success or failed.
  3013. --renew-hook Command to be run once for each successfully renewed certificate.
  3014. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  3015. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  3016. --listen-v4 Force standalone/tls server to listen at ipv4.
  3017. --listen-v6 Force standalone/tls server to listen at ipv6.
  3018. "
  3019. }
  3020. # nocron
  3021. _installOnline() {
  3022. _info "Installing from online archive."
  3023. _nocron="$1"
  3024. if [ ! "$BRANCH" ] ; then
  3025. BRANCH="master"
  3026. fi
  3027. target="$PROJECT/archive/$BRANCH.tar.gz"
  3028. _info "Downloading $target"
  3029. localname="$BRANCH.tar.gz"
  3030. if ! _get "$target" > $localname ; then
  3031. _err "Download error."
  3032. return 1
  3033. fi
  3034. (
  3035. _info "Extracting $localname"
  3036. tar xzf $localname
  3037. cd "$PROJECT_NAME-$BRANCH"
  3038. chmod +x $PROJECT_ENTRY
  3039. if ./$PROJECT_ENTRY install "$_nocron" ; then
  3040. _info "Install success!"
  3041. fi
  3042. cd ..
  3043. rm -rf "$PROJECT_NAME-$BRANCH"
  3044. rm -f "$localname"
  3045. )
  3046. }
  3047. upgrade() {
  3048. if (
  3049. _initpath
  3050. export LE_WORKING_DIR
  3051. cd "$LE_WORKING_DIR"
  3052. _installOnline "nocron"
  3053. ) ; then
  3054. _info "Upgrade success!"
  3055. exit 0
  3056. else
  3057. _err "Upgrade failed!"
  3058. exit 1
  3059. fi
  3060. }
  3061. _processAccountConf() {
  3062. if [ "$_useragent" ] ; then
  3063. _saveaccountconf "USER_AGENT" "$_useragent"
  3064. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ] ; then
  3065. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  3066. fi
  3067. if [ "$_accountemail" ] ; then
  3068. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  3069. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ] ; then
  3070. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  3071. fi
  3072. if [ "$_auto_upgrade" ] ; then
  3073. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  3074. elif [ "$AUTO_UPGRADE" ] ; then
  3075. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  3076. fi
  3077. }
  3078. _process() {
  3079. _CMD=""
  3080. _domain=""
  3081. _altdomains="$NO_VALUE"
  3082. _webroot=""
  3083. _keylength=""
  3084. _accountkeylength=""
  3085. _certpath=""
  3086. _keypath=""
  3087. _capath=""
  3088. _fullchainpath=""
  3089. _reloadcmd=""
  3090. _password=""
  3091. _accountconf=""
  3092. _useragent=""
  3093. _accountemail=""
  3094. _accountkey=""
  3095. _certhome=""
  3096. _httpport=""
  3097. _tlsport=""
  3098. _dnssleep=""
  3099. _listraw=""
  3100. _stopRenewOnError=""
  3101. _insecure=""
  3102. _ca_bundle=""
  3103. _nocron=""
  3104. _ecc=""
  3105. _csr=""
  3106. _pre_hook=""
  3107. _post_hook=""
  3108. _renew_hook=""
  3109. _logfile=""
  3110. _log=""
  3111. _local_address=""
  3112. _log_level=""
  3113. _auto_upgrade=""
  3114. _listen_v4=""
  3115. _listen_v6=""
  3116. while [ ${#} -gt 0 ] ; do
  3117. case "${1}" in
  3118. --help|-h)
  3119. showhelp
  3120. return
  3121. ;;
  3122. --version|-v)
  3123. version
  3124. return
  3125. ;;
  3126. --install)
  3127. _CMD="install"
  3128. ;;
  3129. --uninstall)
  3130. _CMD="uninstall"
  3131. ;;
  3132. --upgrade)
  3133. _CMD="upgrade"
  3134. ;;
  3135. --issue)
  3136. _CMD="issue"
  3137. ;;
  3138. --signcsr)
  3139. _CMD="signcsr"
  3140. ;;
  3141. --showcsr)
  3142. _CMD="showcsr"
  3143. ;;
  3144. --installcert|-i)
  3145. _CMD="installcert"
  3146. ;;
  3147. --renew|-r)
  3148. _CMD="renew"
  3149. ;;
  3150. --renewAll|--renewall)
  3151. _CMD="renewAll"
  3152. ;;
  3153. --revoke)
  3154. _CMD="revoke"
  3155. ;;
  3156. --list)
  3157. _CMD="list"
  3158. ;;
  3159. --installcronjob)
  3160. _CMD="installcronjob"
  3161. ;;
  3162. --uninstallcronjob)
  3163. _CMD="uninstallcronjob"
  3164. ;;
  3165. --cron)
  3166. _CMD="cron"
  3167. ;;
  3168. --toPkcs)
  3169. _CMD="toPkcs"
  3170. ;;
  3171. --createAccountKey|--createaccountkey|-cak)
  3172. _CMD="createAccountKey"
  3173. ;;
  3174. --createDomainKey|--createdomainkey|-cdk)
  3175. _CMD="createDomainKey"
  3176. ;;
  3177. --createCSR|--createcsr|-ccr)
  3178. _CMD="createCSR"
  3179. ;;
  3180. --deactivate)
  3181. _CMD="deactivate"
  3182. ;;
  3183. --updateaccount)
  3184. _CMD="updateaccount"
  3185. ;;
  3186. --registeraccount)
  3187. _CMD="registeraccount"
  3188. ;;
  3189. --domain|-d)
  3190. _dvalue="$2"
  3191. if [ "$_dvalue" ] ; then
  3192. if _startswith "$_dvalue" "-" ; then
  3193. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  3194. return 1
  3195. fi
  3196. if _is_idn "$_dvalue" && ! _exists idn ; then
  3197. _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
  3198. return 1
  3199. fi
  3200. if [ -z "$_domain" ] ; then
  3201. _domain="$_dvalue"
  3202. else
  3203. if [ "$_altdomains" = "$NO_VALUE" ] ; then
  3204. _altdomains="$_dvalue"
  3205. else
  3206. _altdomains="$_altdomains,$_dvalue"
  3207. fi
  3208. fi
  3209. fi
  3210. shift
  3211. ;;
  3212. --force|-f)
  3213. FORCE="1"
  3214. ;;
  3215. --staging|--test)
  3216. STAGE="1"
  3217. ;;
  3218. --debug)
  3219. if [ -z "$2" ] || _startswith "$2" "-" ; then
  3220. DEBUG="1"
  3221. else
  3222. DEBUG="$2"
  3223. shift
  3224. fi
  3225. ;;
  3226. --webroot|-w)
  3227. wvalue="$2"
  3228. if [ -z "$_webroot" ] ; then
  3229. _webroot="$wvalue"
  3230. else
  3231. _webroot="$_webroot,$wvalue"
  3232. fi
  3233. shift
  3234. ;;
  3235. --standalone)
  3236. wvalue="$NO_VALUE"
  3237. if [ -z "$_webroot" ] ; then
  3238. _webroot="$wvalue"
  3239. else
  3240. _webroot="$_webroot,$wvalue"
  3241. fi
  3242. ;;
  3243. --local-address)
  3244. lvalue="$2"
  3245. _local_address="$_local_address$lvalue,"
  3246. shift
  3247. ;;
  3248. --apache)
  3249. wvalue="apache"
  3250. if [ -z "$_webroot" ] ; then
  3251. _webroot="$wvalue"
  3252. else
  3253. _webroot="$_webroot,$wvalue"
  3254. fi
  3255. ;;
  3256. --tls)
  3257. wvalue="$W_TLS"
  3258. if [ -z "$_webroot" ] ; then
  3259. _webroot="$wvalue"
  3260. else
  3261. _webroot="$_webroot,$wvalue"
  3262. fi
  3263. ;;
  3264. --dns)
  3265. wvalue="dns"
  3266. if ! _startswith "$2" "-" ; then
  3267. wvalue="$2"
  3268. shift
  3269. fi
  3270. if [ -z "$_webroot" ] ; then
  3271. _webroot="$wvalue"
  3272. else
  3273. _webroot="$_webroot,$wvalue"
  3274. fi
  3275. ;;
  3276. --dnssleep)
  3277. _dnssleep="$2"
  3278. Le_DNSSleep="$_dnssleep"
  3279. shift
  3280. ;;
  3281. --keylength|-k)
  3282. _keylength="$2"
  3283. if [ "$_accountkeylength" = "$NO_VALUE" ] ; then
  3284. _accountkeylength="$2"
  3285. fi
  3286. shift
  3287. ;;
  3288. --accountkeylength|-ak)
  3289. _accountkeylength="$2"
  3290. shift
  3291. ;;
  3292. --certpath)
  3293. _certpath="$2"
  3294. shift
  3295. ;;
  3296. --keypath)
  3297. _keypath="$2"
  3298. shift
  3299. ;;
  3300. --capath)
  3301. _capath="$2"
  3302. shift
  3303. ;;
  3304. --fullchainpath)
  3305. _fullchainpath="$2"
  3306. shift
  3307. ;;
  3308. --reloadcmd|--reloadCmd)
  3309. _reloadcmd="$2"
  3310. shift
  3311. ;;
  3312. --password)
  3313. _password="$2"
  3314. shift
  3315. ;;
  3316. --accountconf)
  3317. _accountconf="$2"
  3318. ACCOUNT_CONF_PATH="$_accountconf"
  3319. shift
  3320. ;;
  3321. --home)
  3322. LE_WORKING_DIR="$2"
  3323. shift
  3324. ;;
  3325. --certhome)
  3326. _certhome="$2"
  3327. CERT_HOME="$_certhome"
  3328. shift
  3329. ;;
  3330. --useragent)
  3331. _useragent="$2"
  3332. USER_AGENT="$_useragent"
  3333. shift
  3334. ;;
  3335. --accountemail )
  3336. _accountemail="$2"
  3337. ACCOUNT_EMAIL="$_accountemail"
  3338. shift
  3339. ;;
  3340. --accountkey )
  3341. _accountkey="$2"
  3342. ACCOUNT_KEY_PATH="$_accountkey"
  3343. shift
  3344. ;;
  3345. --days )
  3346. _days="$2"
  3347. Le_RenewalDays="$_days"
  3348. shift
  3349. ;;
  3350. --httpport )
  3351. _httpport="$2"
  3352. Le_HTTPPort="$_httpport"
  3353. shift
  3354. ;;
  3355. --tlsport )
  3356. _tlsport="$2"
  3357. Le_TLSPort="$_tlsport"
  3358. shift
  3359. ;;
  3360. --listraw )
  3361. _listraw="raw"
  3362. ;;
  3363. --stopRenewOnError|--stoprenewonerror|-se )
  3364. _stopRenewOnError="1"
  3365. ;;
  3366. --insecure)
  3367. _insecure="1"
  3368. HTTPS_INSECURE="1"
  3369. ;;
  3370. --ca-bundle)
  3371. _ca_bundle="$(readlink -f $2)"
  3372. CA_BUNDLE="$_ca_bundle"
  3373. shift
  3374. ;;
  3375. --nocron)
  3376. _nocron="1"
  3377. ;;
  3378. --ecc)
  3379. _ecc="isEcc"
  3380. ;;
  3381. --csr)
  3382. _csr="$2"
  3383. shift
  3384. ;;
  3385. --pre-hook)
  3386. _pre_hook="$2"
  3387. shift
  3388. ;;
  3389. --post-hook)
  3390. _post_hook="$2"
  3391. shift
  3392. ;;
  3393. --renew-hook)
  3394. _renew_hook="$2"
  3395. shift
  3396. ;;
  3397. --ocsp-must-staple|--ocsp)
  3398. Le_OCSP_Stable="1"
  3399. ;;
  3400. --log|--logfile)
  3401. _log="1"
  3402. _logfile="$2"
  3403. if _startswith "$_logfile" '-' ; then
  3404. _logfile=""
  3405. else
  3406. shift
  3407. fi
  3408. LOG_FILE="$_logfile"
  3409. if [ -z "$LOG_LEVEL" ] ; then
  3410. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  3411. fi
  3412. ;;
  3413. --log-level)
  3414. _log_level="$2"
  3415. LOG_LEVEL="$_log_level"
  3416. shift
  3417. ;;
  3418. --auto-upgrade)
  3419. _auto_upgrade="$2"
  3420. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-' ; then
  3421. _auto_upgrade="1"
  3422. else
  3423. shift
  3424. fi
  3425. AUTO_UPGRADE="$_auto_upgrade"
  3426. ;;
  3427. --listen-v4)
  3428. _listen_v4="1"
  3429. Le_Listen_V4="$_listen_v4"
  3430. ;;
  3431. --listen-v6)
  3432. _listen_v6="1"
  3433. Le_Listen_V6="$_listen_v6"
  3434. ;;
  3435. *)
  3436. _err "Unknown parameter : $1"
  3437. return 1
  3438. ;;
  3439. esac
  3440. shift 1
  3441. done
  3442. if [ "${_CMD}" != "install" ] ; then
  3443. __initHome
  3444. if [ "$_log" ]; then
  3445. if [ -z "$_logfile" ] ; then
  3446. _logfile="$DEFAULT_LOG_FILE"
  3447. fi
  3448. fi
  3449. if [ "$_logfile" ] ; then
  3450. _saveaccountconf "LOG_FILE" "$_logfile"
  3451. LOG_FILE="$_logfile"
  3452. fi
  3453. if [ "$_log_level" ] ; then
  3454. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3455. LOG_LEVEL="$_log_level"
  3456. fi
  3457. _processAccountConf
  3458. fi
  3459. if [ "$DEBUG" ] ; then
  3460. version
  3461. fi
  3462. case "${_CMD}" in
  3463. install) install "$_nocron" ;;
  3464. uninstall) uninstall "$_nocron" ;;
  3465. upgrade) upgrade ;;
  3466. issue)
  3467. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address"
  3468. ;;
  3469. signcsr)
  3470. signcsr "$_csr" "$_webroot"
  3471. ;;
  3472. showcsr)
  3473. showcsr "$_csr" "$_domain"
  3474. ;;
  3475. installcert)
  3476. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_ecc"
  3477. ;;
  3478. renew)
  3479. renew "$_domain" "$_ecc"
  3480. ;;
  3481. renewAll)
  3482. renewAll "$_stopRenewOnError"
  3483. ;;
  3484. revoke)
  3485. revoke "$_domain" "$_ecc"
  3486. ;;
  3487. deactivate)
  3488. deactivate "$_domain,$_altdomains"
  3489. ;;
  3490. registeraccount)
  3491. registeraccount
  3492. ;;
  3493. updateaccount)
  3494. updateaccount
  3495. ;;
  3496. list)
  3497. list "$_listraw"
  3498. ;;
  3499. installcronjob) installcronjob ;;
  3500. uninstallcronjob) uninstallcronjob ;;
  3501. cron) cron ;;
  3502. toPkcs)
  3503. toPkcs "$_domain" "$_password" "$_ecc"
  3504. ;;
  3505. createAccountKey)
  3506. createAccountKey "$_accountkeylength"
  3507. ;;
  3508. createDomainKey)
  3509. createDomainKey "$_domain" "$_keylength"
  3510. ;;
  3511. createCSR)
  3512. createCSR "$_domain" "$_altdomains" "$_ecc"
  3513. ;;
  3514. *)
  3515. _err "Invalid command: $_CMD"
  3516. showhelp;
  3517. return 1
  3518. ;;
  3519. esac
  3520. _ret="$?"
  3521. if [ "$_ret" != "0" ] ; then
  3522. return $_ret
  3523. fi
  3524. if [ "${_CMD}" = "install" ] ; then
  3525. if [ "$_log" ] ; then
  3526. if [ -z "$LOG_FILE" ] ; then
  3527. LOG_FILE="$DEFAULT_LOG_FILE"
  3528. fi
  3529. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  3530. fi
  3531. if [ "$_log_level" ] ; then
  3532. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3533. fi
  3534. _processAccountConf
  3535. fi
  3536. }
  3537. if [ "$INSTALLONLINE" ] ; then
  3538. INSTALLONLINE=""
  3539. _installOnline $BRANCH
  3540. exit
  3541. fi
  3542. main() {
  3543. [ -z "$1" ] && showhelp && return
  3544. if _startswith "$1" '-' ; then _process "$@"; else "$@";fi
  3545. }
  3546. main "$@"